path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/lt/markmerkk/dagger/modules/NetworkModule.kt
marius-m
67,072,115
false
null
package lt.markmerkk.dagger.modules import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import lt.markmerkk.Tags import lt.markmerkk.widgets.network.Api import okhttp3.ConnectionSpec import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.slf4j.LoggerFactory import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class NetworkModule { @Provides @Singleton fun providesGson(): Gson { return GsonBuilder() .create() } @Provides @Singleton fun provideApi( gson: Gson ): Api { val interceptorLogging = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger { override fun log(message: String) { loggerNetwork.debug(message) } }).apply { level = HttpLoggingInterceptor.Level.HEADERS } val httpClient = OkHttpClient.Builder() .readTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .connectionSpecs(Arrays.asList(ConnectionSpec.COMPATIBLE_TLS)) .addInterceptor(interceptorLogging) .build() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient) .baseUrl("https://raw.githubusercontent.com/marius-m/wt4/") .build() return retrofit.create(Api::class.java) } companion object { val loggerNetwork = LoggerFactory.getLogger(Tags.NETWORK)!! } }
1
null
1
26
6632d6bfd53de4760dbc3764c361f2dcd5b5ebce
1,915
wt4
Apache License 2.0
app/src/main/java/ir/rainyday/listexample/api/MovieService.kt
MostafaTaghipour
119,284,187
false
null
package ir.rainyday.listexample.api /** * Created by mostafa-taghipour on 11/28/17. */ import ir.rainyday.listexample.model.PopularMovies import ir.rainyday.listexample.model.TopRatedMovies import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Pagination * Created by Suleiman19 on 10/27/16. * Copyright (c) 2016. <NAME>. All rights reserved. */ interface MovieService { @GET("top_rated") fun getTopRatedMovies( @Query("api_key") apiKey: String=MovieApi.API_KEY, @Query("language") language: String="en_US", @Query("page") pageIndex: Int ): Call<TopRatedMovies> @GET("popular") fun getPopularMovies( @Query("api_key") apiKey: String=MovieApi.API_KEY, @Query("language") language: String="en_US", @Query("page") pageIndex: Int ): Call<PopularMovies> }
0
null
3
15
817ca24021293493f6b085014c1a4af30dd0d75c
888
AndroidEasyList
MIT License
kata/src/test/kotlin/org/suggs/codewars/kata/StockListTest.kt
suggitpe
391,844,797
false
null
package org.suggs.codewars.kata import io.kotest.assertions.assertSoftly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import org.suggs.codewars.kata.StockList.countBooksFrom import org.suggs.codewars.kata.StockList.extractCategoryAndCountFrom import org.suggs.codewars.kata.StockList.stockSummary class StockListTest { @Test fun `counts books in a category list`() { assertSoftly { stockSummary(arrayOf("BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600"), arrayOf("A", "B", "C", "D")) shouldBe "(A : 0) - (B : 1290) - (C : 515) - (D : 600)" stockSummary(arrayOf("ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"), arrayOf("A", "B")) shouldBe "(A : 200) - (B : 1140)" } } @Test fun `counts books into categories`() { assertSoftly { countBooksFrom(arrayOf("ADXE 75"), arrayOf("A")) shouldBe mapOf("A" to 75) countBooksFrom(arrayOf("BBAR 150", "ADXE 75"), arrayOf("A", "B")) shouldBe mapOf("A" to 75, "B" to 150) countBooksFrom(arrayOf("BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600"), arrayOf("B", "C", "D")) shouldBe mapOf("B" to 1290, "C" to 515, "D" to 600) } } @Test fun `extracts book category and number from string`() { assertSoftly { extractCategoryAndCountFrom("BBAR 150") shouldBe Pair("B", 150) extractCategoryAndCountFrom("CDXE 56") shouldBe Pair("C", 56) } } @Test fun `orders output based on the categories defined`() { assertSoftly { stockSummary(arrayOf("ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"), arrayOf("A", "B")) shouldBe "(A : 200) - (B : 1140)" stockSummary(arrayOf("ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"), arrayOf("B", "A")) shouldBe "(B : 1140) - (A : 200)" } } }
0
Kotlin
0
0
7a877d6b7bc8c99617de4643a66bf7a5decce328
1,903
code-wars
Apache License 2.0
app/src/main/java/com/nux/studio/dvor/ui/components/atoms/textfields/ShowSearch.kt
Ledokol-IT
502,100,836
false
null
package com.nux.studio.dvor.ui.components.atoms.textfields import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import com.nux.studio.dvor.R @OptIn(ExperimentalComposeUiApi::class) @Composable fun ShowSearch( textSearch: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, ) { val keyboard = LocalSoftwareKeyboardController.current Search( placeholder = stringResource(id = R.string.enter_nickname_search), text = textSearch, icon = Icons.Default.Close, onValueChange = { onValueChange(it) }, trailingButtonClick = { if (textSearch != "") { onValueChange("") } }, modifier = Modifier .then(modifier) // .clip(RoundedCornerShape(16.dp)) .padding(top = 0.dp), imeAction = ImeAction.Done, keyboardActions = KeyboardActions(onDone = { keyboard!!.hide() }) ) }
0
Kotlin
0
0
f9b171c33807325ad068e79fa3f9dd52f685f4d1
1,468
nux-application
MIT License
firebase-sessions/src/test/kotlin/com/google/firebase/sessions/testing/FakeFirebaseInstallations.kt
firebase
146,941,185
false
null
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.sessions.testing import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.firebase.installations.FirebaseInstallationsApi import com.google.firebase.installations.InstallationTokenResult import com.google.firebase.installations.internal.FidListener import com.google.firebase.installations.internal.FidListenerHandle /** Fake [FirebaseInstallationsApi] that implements [getId] and always returns the given [fid]. */ internal class FakeFirebaseInstallations(private val fid: String = "") : FirebaseInstallationsApi { override fun getId(): Task<String> = Tasks.forResult(fid) override fun getToken(forceRefresh: Boolean): Task<InstallationTokenResult> = throw NotImplementedError("getToken not faked.") override fun delete(): Task<Void> = throw NotImplementedError("delete not faked.") override fun registerFidListener(listener: FidListener): FidListenerHandle = throw NotImplementedError("registerFidListener not faked.") }
393
null
537
2,169
2865f2b61ab1872b1fdb514b9100cd06edfd2648
1,611
firebase-android-sdk
Apache License 2.0
app/src/main/java/cz/dmn/cpska/data/api/source/ConfigurationDataSource.kt
kletzander
141,282,285
false
{"Kotlin": 138837}
package cz.dmn.cpska.data.api.source import cz.dmn.cpska.data.api.cfg.Configuration import io.reactivex.Observable interface ConfigurationDataSource { fun getConfiguration(): Observable<Configuration> }
0
Kotlin
0
0
17a0b9e855458b73ac014bb7aab9698f89b741d2
208
cpska-android
MIT License
src/main/kotlin/io/github/andrewbgm/reactswingruntime/impl/view/ViewManager.kt
AndrewBGM
352,441,655
false
null
package io.github.andrewbgm.reactswingruntime.impl.view import io.github.andrewbgm.reactswingruntime.api.* import io.github.andrewbgm.reactswingruntime.impl.component.* import javax.swing.* private const val ROOT_CONTAINER_ID = "00000000-0000-0000-0000-000000000000" /** * View manager. */ class ViewManager { /** * Map of type name to remote component adapter. */ private val adapterByTypeName = mutableMapOf<String, IRemoteComponentAdapter<out Any>>() /** * Map of View ID to View. */ private val viewById = mutableMapOf<String, View>( ROOT_CONTAINER_ID to ContainerView(ROOT_CONTAINER_ID) ) /** * Associates a remote component type with an adapter. * * @param type Remote component type. * @param adapter Remote component adapter. */ fun registerAdapter( type: IRemoteComponentType, adapter: IRemoteComponentAdapter<*>, ): ViewManager = this.apply { val typeName = type.toString() require(!adapterByTypeName.contains(typeName)) { "$typeName already has an associated IRemoteComponentAdapter" } adapterByTypeName[typeName] = adapter } /** * Creates a new view. * * @param id View ID. * @param type Remote component type. * @param props View props. * @param ctx Message context. */ fun createView( id: String, type: IRemoteComponentType, props: Map<String, Any?>, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val view = RemoteComponentView(id, type) viewById[id] = view val adapter = findAdapter(view) view.obj = adapter.create(view, props, RemoteComponentContext(ctx, view)) } /** * Updates an existing view. * * @param id View ID. * @param changedProps Props that have changed. * @param ctx Message context. */ fun updateView( id: String, changedProps: Map<String, Any?>, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val view = findView<RemoteComponentView>(id) val adapter = findAdapter(view) adapter.update(view, view.obj!!, changedProps, RemoteComponentContext(ctx, view)) } /** * (Re)sets the children for an existing view. * * @param parentId Parent view ID. * @param childrenIds Children view IDs. * @param ctx Message context. */ fun setChildren( parentId: String, childrenIds: List<String>, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val parent = findView<View>(parentId) val children = childrenIds.map { findView<RemoteComponentView>(it) } parent.clear(children) when (parent) { is ContainerView -> { children.forEach { val adapter = findAdapter(it) adapter.appendToContainer(it, it.obj!!, RemoteComponentContext(ctx, it)) } } is RemoteComponentView -> { val childrenObjects = children.map { it.obj!! } val adapter = findAdapter(parent) adapter.setChildren(parent, parent.obj!!, childrenObjects, RemoteComponentContext(ctx, parent)) } } } /** * Appends a child to an existing view. * * @param parentId Parent view ID. * @param childId Child view ID. * @param ctx Message context. */ fun appendChild( parentId: String, childId: String, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val parent = findView<View>(parentId) val child = findView<RemoteComponentView>(childId) parent += child when (parent) { is ContainerView -> { val adapter = findAdapter(child) adapter.appendToContainer(child, child.obj!!, RemoteComponentContext(ctx, child)) } is RemoteComponentView -> { val adapter = findAdapter(parent) adapter.appendChild(parent, parent.obj!!, child.obj!!, RemoteComponentContext(ctx, parent)) } } } /** * Removes a child from an existing view. * * @param parentId Parent view ID. * @param childId Child view ID. * @param ctx Message context. */ fun removeChild( parentId: String, childId: String, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val parent = findView<View>(parentId) val child = findView<RemoteComponentView>(childId) parent -= child when (parent) { is ContainerView -> { val adapter = findAdapter(child) adapter.removeFromContainer(child, child.obj!!, RemoteComponentContext(ctx, child)) } is RemoteComponentView -> { val adapter = findAdapter(parent) adapter.removeChild(parent, parent.obj!!, child.obj!!, RemoteComponentContext(ctx, parent)) } } cleanupView(child) } /** * Inserts a child into an existing view, before another child. * This is used to both reorder children within the parent and add new children. * * @param parentId Parent view ID. * @param childId Child view ID. * @param beforeChildId Before child view ID. * @param ctx Message context. */ fun insertChild( parentId: String, childId: String, beforeChildId: String, ctx: IMessageContext, ) = SwingUtilities.invokeAndWait { val parent = findView<View>(parentId) val child = findView<RemoteComponentView>(childId) val beforeChild = findView<RemoteComponentView>(beforeChildId) parent.insertBefore(child, beforeChild) when (parent) { is ContainerView -> { val adapter = findAdapter(child) adapter.insertInContainer(child, child.obj!!, beforeChild.obj!!, RemoteComponentContext(ctx, child)) } is RemoteComponentView -> { val adapter = findAdapter(parent) adapter.insertChild(parent, parent.obj!!, child.obj!!, beforeChild.obj!!, RemoteComponentContext(ctx, parent)) } } } private fun cleanupView( view: View, ) { view.children.forEach(::cleanupView) viewById.remove(view.id) } /** * Utility function for getting an adapter based on a view. */ @Suppress("UNCHECKED_CAST") private fun findAdapter( view: RemoteComponentView, ): IRemoteComponentAdapter<Any> { val typeName = view.type.toString() return requireNotNull(adapterByTypeName[typeName]) { "$typeName has no associated IRemoteComponentAdapter" } as IRemoteComponentAdapter<Any> } /** * Utility function for getting a view based on an ID. */ private inline fun <reified T : View> findView( id: String, ): T { val view = requireNotNull(viewById[id]) { "#$id has no associated View" } require(view is T) { "$view is not a valid ${T::class.java}" } return view } }
0
Kotlin
0
3
9fd9037178cb3bc5a0e3f899d4cea051a3336d3f
6,661
react-swing-runtime
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/ui/submission/SymptomCalendarEvent.kt
CoraLibre
268,867,734
true
null
package de.rki.coronawarnapp.ui.submission sealed class SymptomCalendarEvent { object NavigateToNext : SymptomCalendarEvent() object NavigateToPrevious : SymptomCalendarEvent() }
5
Kotlin
3
36
8e3d915aa194cae0645ff668cca2114d9bb3d7c2
188
CoraLibre-android
Apache License 2.0
src/commonMain/kotlin/unsigned/unsigned.kt
kotlin-graphics
71,552,988
false
{"Kotlin": 248117}
package unsigned /** * Created by GBarbieri on 06.10.2016. */ // TODO if == unsigned.Ubyte? //fun Number.toUbyte() = Ubyte(toByte()) // //fun Number.toUint() = Uint(this) //fun Number.toUlong() = Ulong(toLong()) //fun Number.toUshort() = Ushort(toShort()) // //// TODO char? // //fun Char.toUbyte() = Ubyte(code.toByte()) //fun Char.toUint() = Uint(code) //fun Char.toUlong() = Ulong(code.toLong()) //fun Char.toUshort() = Ushort(code.toShort())
3
Kotlin
7
74
5c711c463bca664febd86435f144bb528b909595
449
kotlin-unsigned
MIT License
fixture/src/test/kotlin/com/appmattus/kotlinfixture/decorator/filter/DelegatingFilterTest.kt
appmattus
208,850,028
false
null
/* * Copyright 2020 Appmattus Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.appmattus.kotlinfixture.decorator.filter import com.appmattus.kotlinfixture.Context import com.appmattus.kotlinfixture.resolver.Resolver import com.nhaarman.mockitokotlin2.mock import java.util.concurrent.locks.Lock import kotlin.test.Test import kotlin.test.assertEquals class DelegatingFilterTest { private val mockLock = mock<Lock>() private val mockResolver = mock<Resolver>() private val mockResolverAlternate = mock<Resolver>() private val mockContext = mock<Context>() private val mockContextAlternate = mock<Context>() private val delegateFilter = object : Filter { override val lock = mockLock override val iterator = (1..10).iterator() override var resolver: Resolver = mockResolver override var context: Context = mockContext } private val filter = DelegatingFilter(delegateFilter) { this } @Test fun `getLock delegates`() { assertEquals(mockLock, filter.lock) } @Test fun `getResolver delegates`() { assertEquals(mockResolver, filter.resolver) } @Test fun `setResolver delegates`() { filter.resolver = mockResolverAlternate assertEquals(mockResolverAlternate, delegateFilter.resolver) } @Test fun `getContext delegates`() { assertEquals(mockContext, filter.context) } @Test fun `setContext delegates`() { filter.context = mockContextAlternate assertEquals(mockContextAlternate, delegateFilter.context) } @Test fun `no filter applied returns the original iterator`() { assertEquals(delegateFilter.iterator, filter.iterator) } @Test fun `filter applies to the iterator`() { val filter = DelegatingFilter(delegateFilter) { filter { (it as Int) > 2 } } assertEquals(3, filter.iterator.next()) } @Test fun `chaining applies all filters to the iterator`() { val filter = DelegatingFilter( DelegatingFilter(delegateFilter) { filter { (it as Int) > 2 } } ) { filter { (it as Int) % 2 == 0 } } assertEquals(4, filter.iterator.next()) } }
11
null
13
252
6d715e3c3a141cb32a5f3fbcd4fb0027ec6ba44c
2,764
kotlinfixture
Apache License 2.0
plugin-build/plugin/src/main/java/com/github/hervian/gradle/plugins/SetApiVersionTask.kt
Hervian
654,717,020
false
null
package com.github.hervian.gradle.plugins import io.github.z4kn4fein.semver.Version import io.github.z4kn4fein.semver.nextMajor import io.github.z4kn4fein.semver.nextMinor import io.github.z4kn4fein.semver.nextPatch import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option import org.openapitools.openapidiff.core.OpenApiCompare import org.openapitools.openapidiff.core.model.DiffResult import java.io.File abstract class SetApiVersionTask : DefaultTask() { /* init { description = "Just a sample template task" // Don't forget to set the group here. // group = BasePlugin.BUILD_GROUP }*/ @get:InputFile @get:Option( option = "oldApi", description = "The old openapi document, i.e. typically the one that is in test or production", ) abstract val oldApi: RegularFileProperty // = project.objects.fileProperty() @get:InputFile @get:Option( option = "newApi", description = "The new openapi document, i.e. typically the one that contain your changes", ) abstract val newApi: RegularFileProperty // = project.objects.fileProperty() @get:Input @get:Option( option = "versionSuffix", description = "A string that is suffixed to the inferred version number. Typically a timestamp or build number", ) abstract val versionSuffix: Property<String> // by lazy { project.objects.property(String::class.java).convention("") } @get:Input @get:Option( option = "modus", description = "Which level of API change should be allowed, " + "i.e. result in a version upgrade, and which change should produce an OpenApiDiffException", ) abstract val acceptableDiffLevel: Property<SemVerDif> // = project.objects.property(Modus::class.java) @get:OutputFile abstract val versionFile: RegularFileProperty @TaskAction fun nextApiVersion(): String { return calculateNextVersion() } fun calculateNextVersion(): String { validateVersionSuffix(versionSuffix) val oldApiFile = oldApi.get().asFile val newApiFile = newApi.get().asFile logger.lifecycle("oldApi is: ${oldApiFile.absolutePath}") logger.lifecycle("newApi is: ${newApiFile.absolutePath}") val oldVersion = project.version.toString() val newVersion = inferVersionByInspectingTheApisDiff(oldApiFile, newApiFile, versionSuffix.get(), acceptableDiffLevel.get()) if (!versionFile.get().asFile.exists()) { versionFile.get().asFile.createNewFile() } versionFile.get().asFile.writeText("$newVersion") return newVersion } @TaskAction fun setVersion() { val newVersion = calculateNextVersion() updateVersion(newVersion) } private fun inferVersionByInspectingTheApisDiff(oldApiFile: File, newApiFile: File, versionSuffix: String, acceptedDiffLevel: SemVerDif): String { val diff = OpenApiCompare.fromFiles(oldApiFile, newApiFile) var indexOfFirstcharFromSemverBuildPart = diff.oldSpecOpenApi.info.version.indexOfFirst { !it.isDigit() && it != '.' } val oldApiVersionWithBuildInfoPartRemoved = if (indexOfFirstcharFromSemverBuildPart > 0) { diff.oldSpecOpenApi.info.version.subSequence( 0, indexOfFirstcharFromSemverBuildPart, ) } else { diff.oldSpecOpenApi.info.version } indexOfFirstcharFromSemverBuildPart = diff.oldSpecOpenApi.info.version.indexOfFirst { !it.isDigit() && it != '.' } val newApiVersionWithBuildInfoPartRemoved = if (indexOfFirstcharFromSemverBuildPart > 0) { diff.newSpecOpenApi.info.version.subSequence( 0, indexOfFirstcharFromSemverBuildPart, ) } else { diff.newSpecOpenApi.info.version } val oldApiVersion = Version.parse(oldApiVersionWithBuildInfoPartRemoved.toString()) val newApiVersion = Version.parse(newApiVersionWithBuildInfoPartRemoved.toString()) if (oldApiVersion.compareTo(newApiVersion) == 1) { throw RuntimeException( "The old openapi document specifies a version that is higher than the new openapi" + "specification's version. This is not supported.", ) } val versionDiff: SemVerDif = getVersionDiff(oldApiVersion, newApiVersion) val diffResult = diff.isChanged if (diffResult.weight > acceptedDiffLevel.weight && versionDiff.weight < diffResult.weight) { // Example: user has configured that unflagged breaking changes should cause an exception // That is, the plugin is configured with fx ChangeLevel.MINOR and the openapi doc's version // has not had it's major upgraded. throw OpenApiDiffException(diffResult, acceptedDiffLevel) } println("diffResult" + diffResult) println("diffResult.isDifferent" + diffResult.isDifferent) System.out.flush() var newVersion: Version when (diffResult) { DiffResult.NO_CHANGES -> newVersion = Version(newApiVersion.major, newApiVersion.minor, newApiVersion.patch) // newApiVersion.buildMetadata.nextPreRelease(versionSuffix) DiffResult.METADATA -> newVersion = Version(newApiVersion.major, newApiVersion.minor, newApiVersion.patch).nextPatch() DiffResult.COMPATIBLE -> newVersion = newApiVersion.nextMinor() DiffResult.UNKNOWN -> throw UnsupportedOperationException( "The openapi diff tool invoked by this plugin was " + "unable to detect the type of diff", ) DiffResult.INCOMPATIBLE -> newVersion = newApiVersion.nextMajor() } logger.lifecycle("openapi-diff result = $diffResult") val newVersionAsStringWithSuffix = newVersion.toString() + versionSuffix logger.lifecycle("old version number is: ${diff.oldSpecOpenApi.info.version}") logger.lifecycle("new version number is: $newVersionAsStringWithSuffix") return newVersionAsStringWithSuffix } private fun getVersionDiff(oldApiVersion: Version, newApiVersion: Version): SemVerDif { if (newApiVersion.major > oldApiVersion.major) { return SemVerDif.MAJOR } if (newApiVersion.minor > oldApiVersion.minor) { return SemVerDif.MINOR } if (newApiVersion.patch > oldApiVersion.patch) { return SemVerDif.PATCH } return SemVerDif.NONE } /*fun getChangeLevel(changedOperation: ChangedOperation): ChangeLevel { return ChangeLevel.NONE }*/ /** * https://semver.org/ */ private fun validateVersionSuffix(versionSuffix: Property<String>) { assert(versionSuffix.get().startsWith("-") || versionSuffix.get().startsWith("+")) } private fun updateVersion(version: String) { if (hasProperty("version")) { setProperty("version", version) } } }
0
Kotlin
0
0
79b003e61356ae92e99a79a06bfbc4e5968ec6ed
7,395
setversion-gradle-plugin
MIT License
app/src/main/java/com/app/androidPixabay/datasource/api/NetworkState.kt
yash786agg
241,149,101
false
null
package com.app.androidPixabay.datasource.api sealed class NetworkState<T> { class Success<T> : NetworkState<T>() class Loading<T> : NetworkState<T>() class Error<T> : NetworkState<T>() }
0
Kotlin
0
0
a2ace2aa34b25afa6fa7adfee0d64868ff6ee2b7
201
PixaBay-Android
Apache License 2.0
app/src/main/kotlin/batect/docker/build/DockerfileParser.kt
uBuFun
190,537,998
false
{"Gradle": 20, "INI": 2, "Markdown": 26, "Shell": 25, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "YAML": 41, "Kotlin": 391, "Dockerfile": 25, "HTML": 5, "Groovy": 4, "Python": 2, "Java": 1, "JSON": 2, "JavaScript": 8}
/* Copyright 2017-2018 <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 batect.docker.build import batect.docker.ImageBuildFailedException import java.nio.file.Files import java.nio.file.Path class DockerfileParser { fun extractBaseImageName(dockerfilePath: Path): String { val lines = Files.readAllLines(dockerfilePath) val fromInstruction = lines.firstOrNull { it.startsWith("FROM") } if (fromInstruction == null) { throw ImageBuildFailedException("The Dockerfile '$dockerfilePath' is invalid: there is no FROM instruction.") } return fromInstruction.substringAfter("FROM ") } }
1
null
1
1
b02013e2b0ab3e9ba3298f160c69971543bda985
1,172
batect
Apache License 2.0
lib_base/src/main/java/redrock/tongji/lib_base/base/BaseBindVMActivity.kt
G-Pegasus
513,767,503
false
{"Kotlin": 226090, "Java": 3881}
package redrock.tongji.lib_base.base import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding /** * @Author Tongji * @Description * @Date create in 2022/7/14 19:58 */ abstract class BaseBindVMActivity<VM : BaseViewModel, DB : ViewDataBinding> : BaseVMActivity<VM>() { lateinit var mBind: DB override fun setLayout() { mBind = DataBindingUtil.setContentView( this, getLayoutRes ) mBind.lifecycleOwner = this } override fun initEvent() { } override fun onDestroy() { super.onDestroy() if (::mBind.isInitialized) { mBind.unbind() } } }
0
Kotlin
0
1
3b7fa222244e19bda5390e3e68aace00aed9707a
685
RedRockExam
Apache License 2.0
backstackpressedmanager/src/main/java/com/mgsoftware/backstackpressedmanager/api/FragmentProvider.kt
mgolebiowski95
518,466,050
false
{"Kotlin": 32784}
package com.mgsoftware.backstackpressedmanager.api import androidx.fragment.app.Fragment /** * Created by Mariusz */ interface FragmentProvider { fun getFragment(keyFragment: String): Fragment? }
0
Kotlin
0
0
5477b5f95aeee6af1ed02163b39599a4afe1470f
205
backstackpressedmanager
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/covidcertificate/vaccination/core/VaccinatedPersonTest.kt
rgrenz
390,331,768
false
{"Gradle": 4, "JSON": 32, "CODEOWNERS": 1, "Java Properties": 2, "Markdown": 11, "INI": 1, "Shell": 1, "Text": 2, "Ignore List": 3, "Batchfile": 1, "EditorConfig": 1, "Proguard": 1, "YAML": 4, "XML": 833, "Java": 7, "Kotlin": 1981, "HTML": 7, "Checksums": 18, "JAR Manifest": 1, "Protocol Buffer": 59, "Groovy": 1, "SVG": 1}
package de.rki.coronawarnapp.covidcertificate.vaccination.core import de.rki.coronawarnapp.covidcertificate.DaggerCovidCertificateTestComponent import de.rki.coronawarnapp.covidcertificate.vaccination.core.repository.storage.VaccinatedPersonData import de.rki.coronawarnapp.covidcertificate.vaccination.core.repository.storage.VaccinationContainer import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import org.joda.time.DateTimeZone import org.joda.time.Instant import org.joda.time.LocalDate import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import testhelpers.BaseTest import java.util.TimeZone import javax.inject.Inject class VaccinatedPersonTest : BaseTest() { @Inject lateinit var testData: VaccinationTestData lateinit var defaultTimezone: DateTimeZone @BeforeEach fun setup() { DaggerCovidCertificateTestComponent.factory().create().inject(this) defaultTimezone = DateTimeZone.getDefault() DateTimeZone.setDefault(DateTimeZone.UTC) } @AfterEach fun teardown() { DateTimeZone.setDefault(defaultTimezone) } @Test fun `test name combinations`() { val certificate = mockk<VaccinationCertificate>() val vaccinationContainer = mockk<VaccinationContainer>().apply { every { toVaccinationCertificate(any()) } returns certificate } val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf(vaccinationContainer) } val vaccinatedPerson = VaccinatedPerson( data = personData, valueSet = null ) certificate.apply { every { fullName } returns "<NAME>" } vaccinatedPerson.fullName shouldBe "<NAME>" certificate.apply { every { fullName } returns "Siphon" } vaccinatedPerson.fullName shouldBe "Siphon" } @Test fun `vaccination status - INCOMPLETE`() { val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf(testData.personAVac1Container) } val vaccinatedPerson = VaccinatedPerson( data = personData, valueSet = null ) vaccinatedPerson.getVaccinationStatus(Instant.EPOCH) shouldBe VaccinatedPerson.Status.INCOMPLETE } @Test fun `vaccination status - COMPLETE`() { val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf(testData.personAVac1Container, testData.personAVac2Container) } val vaccinatedPerson = VaccinatedPerson( data = personData, valueSet = null ) vaccinatedPerson.getVaccinationStatus(Instant.EPOCH) shouldBe VaccinatedPerson.Status.COMPLETE } @Test fun `vaccination status - IMMUNITY`() { // vaccinatedAt "2021-04-27" val immunityContainer = testData.personAVac2Container val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf(testData.personAVac1Container, immunityContainer) } val vaccinatedPerson = VaccinatedPerson( data = personData, valueSet = null ) vaccinatedPerson.apply { // Less than 14 days getVaccinationStatus( Instant.parse("2021-04-27T12:00:00.000Z") ) shouldBe VaccinatedPerson.Status.COMPLETE getVaccinationStatus( Instant.parse("2021-05-10T12:00:00.000Z") ) shouldBe VaccinatedPerson.Status.COMPLETE // 14 days exactly getVaccinationStatus( Instant.parse("2021-05-11T12:00:00.000Z") ) shouldBe VaccinatedPerson.Status.COMPLETE // More than 14 days getVaccinationStatus( Instant.parse("2021-05-12T12:00:00.000Z") ) shouldBe VaccinatedPerson.Status.IMMUNITY } } @Test fun `time until status IMMUNITY`() { // vaccinatedAt "2021-04-27" val immunityContainer = testData.personAVac2Container val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf(testData.personAVac1Container, immunityContainer) } VaccinatedPerson(data = personData, valueSet = null).apply { Instant.parse("2021-04-27T12:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 15 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } Instant.parse("2021-05-10T12:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 2 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } Instant.parse("2021-05-11T12:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 1 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } Instant.parse("2021-05-12T0:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 0 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.IMMUNITY } } } @Test fun `time until immunity - case #3562`() { DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/Berlin"))) val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf( mockk<VaccinationContainer>().apply { every { toVaccinationCertificate(any()) } returns mockk<VaccinationCertificate>().apply { every { vaccinatedOn } returns LocalDate.parse("2021-06-13") every { doseNumber } returns 2 every { totalSeriesOfDoses } returns 2 } } ) } VaccinatedPerson(data = personData, valueSet = null).apply { // User was in GMT+2 timezone (UTC+2) , we want their MIDNIGHT // Last day before immunity, UI shows 1 day until immunity Instant.parse("2021-06-27T12:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 1 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } // Immunity should be reached at midnight in the users timezone Instant.parse("2021-06-27T22:00:00.000Z").let { now -> getDaysUntilImmunity(now)!!.apply { this shouldBe 0 } getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.IMMUNITY } } } @Test fun `time until immunity - case Luka#1`() { DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/Berlin"))) val personData = mockk<VaccinatedPersonData>().apply { every { vaccinations } returns setOf( mockk<VaccinationContainer>().apply { every { toVaccinationCertificate(any()) } returns mockk<VaccinationCertificate>().apply { every { vaccinatedOn } returns LocalDate.parse("2021-01-01") every { doseNumber } returns 2 every { totalSeriesOfDoses } returns 2 } } ) } VaccinatedPerson(data = personData, valueSet = null).apply { Instant.parse("2021-01-14T0:00:00.000Z").let { now -> getDaysUntilImmunity(now)!! shouldBe 2 getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } Instant.parse("2021-01-15T0:00:00.000Z").let { now -> getDaysUntilImmunity(now)!! shouldBe 1 getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } // Case Luka#1 happens on 15.01.21, this mean it's winter time! // The users timezone is GMT+1 (winter-time) (UTC+1), not GMT+2 (summer-time) (UTC+2) Instant.parse("2021-01-15T22:00:00.000Z").let { now -> getDaysUntilImmunity(now)!! shouldBe 1 getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.COMPLETE } Instant.parse("2021-01-16T0:00:00.000Z").let { now -> getDaysUntilImmunity(now)!! shouldBe 0 getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.IMMUNITY } Instant.parse("2021-01-15T23:00:00.000Z").let { now -> getDaysUntilImmunity(now)!! shouldBe 0 getVaccinationStatus(now) shouldBe VaccinatedPerson.Status.IMMUNITY } } } }
1
null
1
1
bd2b989daff48881949402dbbc8827a1d3806425
9,178
cwa-app-android
Apache License 2.0
src/main/java/com/will/utils/Utils.kt
z2z2qp
86,769,932
false
null
package com.will.utils import java.util.* /** * Created by EastLanCore on 2017/5/29. */ /** * 插入字符串 */ fun String.insert(str:CharSequence,index:Int):String{ val sb = StringBuilder(this) sb.insert(index,str) return sb.toString() } /** * 是否奇数 */ fun Number.isOdd() = this.toLong() % 2 != 0L /** * 集合为空或者size = 0 */ fun Collection<*>?.isNullOrEmpty() = this == null || this.isEmpty() /** * 获得随机字符串 */ fun Random.nextString(length:Int = 16):String{ val str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var code = "" val random = Random(Date().time) for (i in 0..length - 1) { code += str[random.nextInt(str.length)].toString() } return code }
6
Kotlin
1
2
97fbf03a0ce011629135dd541c4e4d59e13454db
720
msm
The Unlicense
image-utils/src/test/kotlin/no/nav/dagpenger/io/DetectTest.kt
navikt
186,607,232
false
{"Kotlin": 182403, "Java": 1728}
package no.nav.dagpenger.io import io.kotest.matchers.shouldBe import no.nav.dagpenger.io.Detect.isImage import no.nav.dagpenger.io.Detect.isJpeg import no.nav.dagpenger.io.Detect.isPdf import no.nav.dagpenger.io.Detect.isPng import no.nav.dagpenger.pdf.fileAsBufferedInputStream import no.nav.dagpenger.pdf.fileAsByteArray import org.junit.jupiter.api.Test class DetectTest { @Test fun `detect pdf`() { "/pdfs/minimal.pdf".fileAsBufferedInputStream().use { it.isPdf() shouldBe true } "/pdfs/fake_pdf.pdf".fileAsBufferedInputStream().use { it.isPdf() shouldBe false } } @Test fun `detect list of byte arrays representing pdfs`() { val legalPdf = "/pdfs/minimal.pdf".fileAsByteArray() val illegalPdf = "/pdfs/fake_pdf.pdf".fileAsByteArray() listOf(legalPdf, legalPdf).isPdf() shouldBe true listOf(legalPdf).isPdf() shouldBe true emptyList<ByteArray>().isPdf() shouldBe false listOf(illegalPdf).isPdf() shouldBe false listOf(legalPdf, illegalPdf).isPdf() shouldBe false } @Test fun `detect png`() { "/images/bilde.png".fileAsBufferedInputStream().use { it.isPng() shouldBe true } "/images/fake_png.png".fileAsBufferedInputStream().use { it.isPng() shouldBe false } } @Test fun `detect jpg`() { "/images/bilde.jpeg".fileAsBufferedInputStream().use { it.isJpeg() shouldBe true } "/images/fake_jpeg.jpeg".fileAsBufferedInputStream().use { it.isJpeg() shouldBe false } } @Test fun `detect image`() { "/images/bilde.jpeg".fileAsBufferedInputStream().use { it.isImage() shouldBe true } "/images/bilde.jpeg".fileAsBufferedInputStream().use { it.isImage() shouldBe true } } }
7
Kotlin
2
1
2348af15ea1d62bf73a548291124de336f13e608
1,919
dp-biblioteker
MIT License
bookmark/domain/src/main/java/tickmarks/bookmark/domain/AddBookmark.kt
annypatel
137,336,539
false
{"Kotlin": 80750, "Shell": 600}
package tickmarks.bookmark.domain import io.reactivex.Completable import tickmarks.base.domain.rx.CompletableUseCase import tickmarks.base.domain.rx.RxSchedulers import javax.inject.Inject /** * Use case for adding a bookmark, takes web page url as input. */ interface AddBookmark : CompletableUseCase<String> /** * Internal implementation of AddBookmark use case. */ internal class AddBookmarkImpl @Inject constructor( private val schedulers: RxSchedulers, private val crawlerRepository: CrawlerRepository, private val bookmarkRepository: BookmarkRepository ) : AddBookmark { override fun invoke(input: String): Completable { return crawlerRepository.crawl(input) .observeOn(schedulers.computation) .map { Bookmark( it.title, it.url ?: input, it.image, it.description ) } .flatMapCompletable { bookmarkRepository.saveBookmark(it) } } }
0
Kotlin
0
9
5ad30bca0329bd79334748baf228d9a0f1ba4dbb
1,061
tickmarks
Apache License 2.0
app/src/main/kotlin/de/p72b/mocklation/usecase/MapBoundsUseCase.kt
P72B
101,384,379
false
{"Kotlin": 171895}
package de.p72b.mocklation.usecase import de.p72b.mocklation.data.util.Resource import de.p72b.mocklation.data.util.Status import de.p72b.mocklation.util.convertToMultiPoint import de.p72b.mocklation.util.convertToPoints import de.p72b.mocklation.util.geometryFactory import org.locationtech.jts.geom.Coordinate import org.locationtech.jts.geom.Geometry import org.locationtech.jts.geom.MultiPoint class MapBoundsUseCase( private val getCollectionUseCase: GetCollectionUseCase ) { suspend fun invoke(): Resource<Geometry?> { val collection = getCollectionUseCase.invoke() when (collection.status) { Status.SUCCESS -> { collection.data?.let { if (it.isEmpty()) { return Resource( status = Status.SUCCESS, data = null ) } else { var allCoordinates: Array<Coordinate> = emptyArray() for (feature in it) { allCoordinates = allCoordinates.plus(feature.nodes.convertToMultiPoint().coordinates) } return Resource( status = Status.SUCCESS, data = MultiPoint( allCoordinates.convertToPoints(), geometryFactory ).envelope ) } } } Status.ERROR -> return Resource( status = Status.SUCCESS, data = null ) } return Resource( status = Status.SUCCESS, data = null ) } }
0
Kotlin
5
17
b638b5f75beb35d891f04aa5060c16c377512d3b
1,806
Mocklation
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/frauddetector/EventVariablePropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.frauddetector import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.frauddetector.CfnEventType @Generated public fun buildEventVariableProperty(initializer: @AwsCdkDsl CfnEventType.EventVariableProperty.Builder.() -> Unit): CfnEventType.EventVariableProperty = CfnEventType.EventVariableProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
469
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/newgamesoftware/moviesappdemo/base/view/recyclerView/BaseRecyclerViewHasSnapHelper.kt
nejatboy
426,532,203
false
null
package com.newgamesoftware.moviesappdemo.base.view.recyclerView import android.content.Context import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import com.newgamesoftware.moviesappdemo.base.layout.BaseConstraintLayout abstract class BaseRecyclerViewHasSnapHelper<SV: BaseConstraintLayout, A: RecyclerView.Adapter<*>>(context: Context) : BaseRecyclerView<SV, A>(context) { init { val linearSnapHelper = LinearSnapHelper() linearSnapHelper.attachToRecyclerView(this) } }
0
Kotlin
0
2
f1f4a0f21834b1f32d914cd4a0e089d0a587a46e
549
MoviesDemo-Android
MIT License
src/main/kotlin/no/nav/k9/los/eventhandler/RefreshK9v3.kt
navikt
238,874,021
false
{"Kotlin": 1850565, "Shell": 899, "JavaScript": 741, "Dockerfile": 459, "PLpgSQL": 167}
package no.nav.k9.los.eventhandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import no.nav.k9.los.nyoppgavestyring.ko.KøpåvirkendeHendelse import org.slf4j.LoggerFactory import java.util.concurrent.Executors class RefreshK9v3( val refreshK9v3Tjeneste: RefreshK9v3Tjeneste ) { fun CoroutineScope.start(channel: Channel<KøpåvirkendeHendelse>) = launch(Executors.newSingleThreadExecutor().asCoroutineDispatcherWithErrorHandling()) { val hendelser = mutableListOf<KøpåvirkendeHendelse>() hendelser.add(channel.receive()) while (true) { val hendelse = channel.tryReceive().getOrNull() if (hendelse == null) { try { ChannelMetrikker.timeSuspended("refresh_k9sak_v3") { refreshK9v3Tjeneste.refreshK9(hendelser) hendelser.clear() } } catch (e: Exception) { log.error("Feilet ved refresh av oppgaver i k9-sak: " + hendelser.joinToString(", "), e) } hendelser.add(channel.receive()) } else { hendelser.add(hendelse) } } } companion object { val log = LoggerFactory.getLogger("RefreshK9v3") } }
8
Kotlin
0
0
06a14f9315665169510c101c771a33bc98c1ccb8
1,444
k9-los-api
MIT License
verik-importer/src/main/kotlin/io/verik/importer/preprocess/PreprocessorListener.kt
frwang96
269,980,078
false
null
/* * Copyright (c) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.verik.importer.preprocess import io.verik.importer.antlr.SystemVerilogPreprocessorParser import io.verik.importer.antlr.SystemVerilogPreprocessorParserBaseListener class PreprocessorListener( private val preprocessContext: PreprocessContext ) : SystemVerilogPreprocessorParserBaseListener() { override fun enterDirectiveIfdef(ctx: SystemVerilogPreprocessorParser.DirectiveIfdefContext?) { BasePreprocessor.preprocessDirectiveIfdef(ctx!!, preprocessContext) } override fun enterDirectiveIfndef(ctx: SystemVerilogPreprocessorParser.DirectiveIfndefContext?) { BasePreprocessor.preprocessDirectiveIfndef(ctx!!, preprocessContext) } override fun enterDirectiveElse(ctx: SystemVerilogPreprocessorParser.DirectiveElseContext?) { BasePreprocessor.preprocessDirectiveElse(ctx!!, preprocessContext) } override fun enterDirectiveEndif(ctx: SystemVerilogPreprocessorParser.DirectiveEndifContext?) { BasePreprocessor.preprocessDirectiveEndif(ctx!!, preprocessContext) } override fun enterDirectiveInclude(ctx: SystemVerilogPreprocessorParser.DirectiveIncludeContext?) { if (preprocessContext.isEnable()) BasePreprocessor.preprocessDirectiveInclude(ctx!!, preprocessContext) } override fun enterDirectiveUndefineAll(ctx: SystemVerilogPreprocessorParser.DirectiveUndefineAllContext?) { if (preprocessContext.isEnable()) MacroPreprocessor.preprocessDirectiveUndefineAll(preprocessContext) } override fun enterDirectiveUndef(ctx: SystemVerilogPreprocessorParser.DirectiveUndefContext?) { if (preprocessContext.isEnable()) MacroPreprocessor.preprocessDirectiveUndef(ctx!!, preprocessContext) } override fun enterDirectiveDefine(ctx: SystemVerilogPreprocessorParser.DirectiveDefineContext?) { if (preprocessContext.isEnable()) MacroPreprocessor.preprocessDirectiveDefine(ctx!!, preprocessContext) } override fun enterDirectiveMacro(ctx: SystemVerilogPreprocessorParser.DirectiveMacroContext?) { if (preprocessContext.isEnable()) MacroPreprocessor.preprocessDirectiveMacro(ctx!!, preprocessContext) } override fun enterDirectiveMacroArg(ctx: SystemVerilogPreprocessorParser.DirectiveMacroArgContext?) { if (preprocessContext.isEnable()) MacroPreprocessor.preprocessDirectiveMacroArg(ctx!!, preprocessContext) } override fun enterCode(ctx: SystemVerilogPreprocessorParser.CodeContext?) { if (preprocessContext.isEnable()) BasePreprocessor.preprocessCode(ctx!!, preprocessContext) } }
0
Kotlin
1
7
a40d6195f3b57bebac813b3e5be59d17183433c7
3,247
verik
Apache License 2.0
src/main/kotlin/by/mrpetchenka/flanscore/common/blocks/tile/TileEntitySit.kt
PeTcHeNkA
506,586,519
false
null
package by.mrpetchenka.flanscore.common.blocks.tile class TileEntitySit : TileMod() { override fun canUpdate(): Boolean { return false } }
0
Kotlin
0
0
f4f5eef2db6631e3ba6adbaa4e6d5a36391798e2
156
FlansCore
MIT License
src/main/kotlin/cn/yiiguxing/plugin/translate/trans/youdao/YoudaoLanguageAdapter.kt
YiiGuxing
60,159,997
false
{"Kotlin": 949025, "HTML": 95020, "Java": 92135}
package cn.yiiguxing.plugin.translate.trans.youdao import cn.yiiguxing.plugin.translate.trans.BaseLanguageAdapter import cn.yiiguxing.plugin.translate.trans.Lang /** * Language adapter for Youdao Translator. */ object YoudaoLanguageAdapter : BaseLanguageAdapter() { private val SUPPORTED_LANGUAGES: List<Lang> = listOf( Lang.AUTO, Lang.CHINESE, Lang.CHINESE_TRADITIONAL, Lang.ENGLISH, Lang.JAPANESE, Lang.KOREAN, Lang.DUTCH, Lang.VIETNAMESE, Lang.RUSSIAN, Lang.PORTUGUESE, Lang.ITALIAN, Lang.INDONESIAN, Lang.FRENCH, Lang.SPANISH, Lang.GERMAN, Lang.THAI, Lang.ARABIC, ) override val supportedSourceLanguages: List<Lang> = SUPPORTED_LANGUAGES override val supportedTargetLanguages: List<Lang> = SUPPORTED_LANGUAGES override fun getAdaptedLanguages(): Map<String, Lang> = mapOf( "zh-CHS" to Lang.CHINESE, "zh-CHT" to Lang.CHINESE_TRADITIONAL, ) } /** * Language code for Youdao Translator. */ val Lang.youdaoLanguageCode: String get() = YoudaoLanguageAdapter.getLanguageCode(this) /** * Returns the [language][Lang] for the specified Youdao Translator language [code]. */ fun Lang.Companion.fromYoudaoLanguageCode(code: String): Lang { return YoudaoLanguageAdapter.getLanguage(code) }
52
Kotlin
781
11,230
f9de0659dadc4bce4606d306699dd1d7cf75ec13
1,382
TranslationPlugin
MIT License
app/src/main/java/com/kirakishou/photoexchange/di/module/activity/ViewTakenPhotoActivityModule.kt
K1rakishou
109,590,033
false
null
package com.kirakishou.photoexchange.di.module.activity import androidx.lifecycle.ViewModelProviders import com.kirakishou.photoexchange.di.scope.PerActivity import com.kirakishou.photoexchange.helper.concurrency.coroutines.DispatchersProvider import com.kirakishou.photoexchange.helper.database.repository.TakenPhotosRepository import com.kirakishou.photoexchange.helper.database.repository.SettingsRepository import com.kirakishou.photoexchange.mvrx.viewmodel.ViewTakenPhotoActivityViewModel import com.kirakishou.photoexchange.mvrx.viewmodel.factory.ViewTakenPhotoActivityViewModelFactory import com.kirakishou.photoexchange.ui.activity.ViewTakenPhotoActivity import dagger.Module import dagger.Provides /** * Created by kirakishou on 3/9/2018. */ @Module open class ViewTakenPhotoActivityModule( val activity: ViewTakenPhotoActivity ) { @PerActivity @Provides open fun provideViewModelFactory(takenPhotosRepository: TakenPhotosRepository, settingsRepository: SettingsRepository, dispatchersProvider: DispatchersProvider): ViewTakenPhotoActivityViewModelFactory { return ViewTakenPhotoActivityViewModelFactory( takenPhotosRepository, settingsRepository, dispatchersProvider ) } @PerActivity @Provides fun provideViewModel( viewModelFactory: ViewTakenPhotoActivityViewModelFactory ): ViewTakenPhotoActivityViewModel { return ViewModelProviders.of( activity, viewModelFactory ).get(ViewTakenPhotoActivityViewModel::class.java) } }
0
Kotlin
1
4
15f67029376a98353a01b5523dfb42d183a26bf2
1,578
photoexchange-android
Do What The F*ck You Want To Public License
src/main/kotlin/ru/nsu/lupa/Configuration.kt
lilvadim
576,661,907
false
{"Kotlin": 22514, "Java": 836}
package ru.nsu.lupa import java.io.File open class Configuration( /** * `Resource.id -> param_name -> value` */ val parameters: Map<String, Map<String, String>>, /** * Initial dataset */ val profiles: List<Profile>, val outputFile: File? ) { fun param(resourceId: String, paramName: String): String? { return parameters[resourceId]?.get(paramName) } }
0
Kotlin
0
0
9388aa69457bc625317a3732f2afcd52e02ef1a1
410
lupa
Apache License 2.0
server/src/main/kotlin/org/kryptonmc/krypton/event/command/KryptonCommandExecuteEvent.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.krypton.event.command import org.kryptonmc.api.command.Sender import org.kryptonmc.api.event.command.CommandExecuteEvent import org.kryptonmc.api.event.type.AbstractDeniableEventWithResult class KryptonCommandExecuteEvent( override val sender: Sender, override val command: String ) : AbstractDeniableEventWithResult<CommandExecuteEvent.Result>(), CommandExecuteEvent
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
1,133
Krypton
Apache License 2.0
src/androidTest/java/com/justforfun/simplexml/model/kt_models/TestFeedEntryConstructorParams.kt
vmalikov
94,436,440
false
null
package com.justforfun.simplexml.model.kt_models import com.justforfun.simplexml.annotation.XmlName /** * Created by Vladimir on 6/16/17. */ @XmlName(name = "item") data class TestFeedEntryConstructorParams(@XmlName(name = "title") var title: String = "", @XmlName(names = *arrayOf("content:encoded", "description")) var description: String = "", @XmlName(name = "link") var link: String = "", @XmlName(name = "pubDate") var pubDate: String = "")
1
Kotlin
2
4
280a101bea521b737292a19dfd3ff2b333a0d823
464
simpleXMLParser
Apache License 2.0
koleton-base/src/main/kotlin/koleton/custom/TextKoletonView.kt
ericktijerou
267,768,682
false
null
package koleton.custom import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.View import android.view.ViewGroup import koleton.mask.KoletonMask import koleton.util.* internal class SimpleKoletonView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : KoletonView(context, attrs, defStyleAttr) { private var koletonMask: KoletonMask? = null override var isSkeletonShown: Boolean = false private var isMeasured: Boolean = false private val viewList = arrayListOf<View>() var attributes: Attributes? = null set(value) { field = value value?.let { applyAttributes() } } private fun hideVisibleChildren(view: View) { when (view) { is ViewGroup -> view.children().forEach { hideVisibleChildren(it) } else -> hideVisibleChild(view) } } private fun hideVisibleChild(view: View) { if (view.isVisible()) { view.invisible() viewList.add(view) } } override fun showSkeleton() { isSkeletonShown = true if (isMeasured && childCount > 0) { hideVisibleChildren(this) applyAttributes() } } override fun hideSkeleton() { isSkeletonShown = false if (childCount > 0) { viewList.forEach { it.visible() } hideShimmer() koletonMask = null } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) isMeasured = width > NUMBER_ZERO && height > NUMBER_ZERO if (isSkeletonShown) { showSkeleton() } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.let { koletonMask?.draw(it) } } override fun applyAttributes() { if (isMeasured) { attributes?.let { attrs -> if (attrs !is SimpleViewAttributes || !attrs.isShimmerEnabled) { hideShimmer() } else { setShimmer(attrs.shimmer) } koletonMask = KoletonMask(this, attrs.color, attrs.cornerRadius, attrs.lineSpacing) } } } }
6
Kotlin
12
87
58b7a54674ee3bf0c2351f21101181ca203a3d06
2,375
koleton
Apache License 2.0
wubbaboo/src/main/java/com/lianyi/wubbaboo/ui/splash/data/EvolveAnimationData.kt
QooLianyi
435,314,581
false
{"Kotlin": 1855635}
package com.lianyi.wubbaboo.ui.splash.data import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.tween data class EvolveAnimationData( val resId: Int, val duration: Int, val initValue: Float = 0f, val targetValue: Float = 360f, val repeatMode: RepeatMode = RepeatMode.Restart ) { val anim = Animatable(initValue) suspend fun play() { anim.stop() anim.animateTo( targetValue, infiniteRepeatable(tween(duration, easing = LinearEasing), repeatMode) ) } suspend fun stop() { anim.stop() } }
1
Kotlin
2
36
7af1f8cce2f8eea3f72b3735e820508510b3112e
782
PaimonsNotebook
MIT License
kestrel-core/src/main/kotlin/com/dreweaster/ddd/kestrel/application/scheduling/Scheduler.kt
DrewEaster
110,524,776
false
null
package com.dreweaster.ddd.kestrel.application.scheduling import reactor.core.publisher.Mono import java.time.Duration interface Job { val name: String /** * @return whether the job should be immediately rescheduled on completion or whether it should wait delay for * its default scheduling cycle before its next execution */ fun execute(): Mono<Boolean> } interface Scheduler { fun scheduleManyTimes(repeatSchedule: Duration, timeout: Duration, job: Job) // TODO: Terminate all scheduled jobs so that JVM can shutdown as gracefully as possible // Should help for hot restart situations in development fun shutdown(): Mono<Void> }
4
Kotlin
4
5
3f8a7bed9c93058210b5912c0c9824b4a2d11f85
688
kestrel
Apache License 2.0
app/src/main/java/com/github/nyanfantasia/shizurunotes/data/action/DamageCutAction.kt
TragicLifeHu
440,741,412
true
{"Kotlin": 727863}
package com.github.nyanfantasia.shizurunotes.data.action import com.github.nyanfantasia.shizurunotes.R import com.github.nyanfantasia.shizurunotes.common.I18N.Companion.getString import com.github.nyanfantasia.shizurunotes.data.Property class DamageCutAction : ActionParameter() { enum class DamageType(val value: Int) { Physical(1), Magic(2), All(3); companion object { fun parse(value: Int): DamageType { for (item in values()) { if (item.value == value) return item } return All } } } private var damageType: DamageType? = null private var durationValues: MutableList<ActionValue> = ArrayList() override fun childInit() { damageType = DamageType.parse(actionDetail1) actionValues.add(ActionValue(actionValue1!!, actionValue2!!, null)) durationValues.add(ActionValue(actionValue3!!, actionValue4!!, null)) } override fun localizedDetail(level: Int, property: Property?): String? { return when (damageType) { DamageType.Physical -> getString( R.string.Reduce_s1_physical_damage_taken_by_s2_for_s3_sec, buildExpression(level, actionValues, null, property), targetParameter!!.buildTargetClause(), buildExpression(level, durationValues, null, property) ) DamageType.Magic -> getString( R.string.Reduce_s1_magic_damage_taken_by_s2_for_s3_sec, buildExpression(level, actionValues, null, property), targetParameter!!.buildTargetClause(), buildExpression(level, durationValues, null, property) ) DamageType.All -> getString( R.string.Reduce_s1_all_damage_taken_by_s2_for_s3_sec, buildExpression(level, actionValues, null, property), targetParameter!!.buildTargetClause(), buildExpression(level, durationValues, null, property) ) else -> super.localizedDetail(level, property) } } }
0
Kotlin
0
1
7d06e6dfc6268312eff6f5af359ae0c3153a6d50
2,144
ShizuruNotes
Apache License 2.0
app/src/main/java/br/com/livroandroid/carros/utils/Prefs.kt
luizgoes10
148,938,163
false
null
package br.com.livroandroid.carros.utils import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import br.com.livroandroid.carros.CarrosApplication import br.com.livroandroid.carros.R import java.lang.reflect.Array.setInt class Prefs { companion object { private const val PREF_ID = "carros" private fun prefs(): SharedPreferences { val context = CarrosApplication.getInstance().applicationContext return context.getSharedPreferences(PREF_ID, 0) } fun putInt(key: String, valor: Int) = prefs().edit().putInt(key, valor).apply() fun getInt(key: String) = prefs().getInt(key, 0) fun putString(key: String, valor: String) = prefs().edit().putString(key, valor).apply() fun getString(key: String) = prefs().getString(key, "")!! var lastTabIdx: Int get() = getInt("tabIdx") set(value) = putInt("tabIdx", value) fun isCacheOn(): Boolean { val context = CarrosApplication.getInstance().applicationContext val prefs = PreferenceManager.getDefaultSharedPreferences(context) val key = context.getString(R.string.key_fazer_cache) return prefs.getBoolean(key, false) } } }
0
Kotlin
0
0
89402735b32f29b5f1d2b55d1cba737ee46fcac1
1,317
aula15-09-2018
MIT License
idea/tests/testData/intentions/convertToBlockBody/annotatedExpr.kt
JetBrains
278,369,660
false
null
@Target(AnnotationTarget.EXPRESSION) @Retention(AnnotationRetention.SOURCE) annotation class ann fun foo(): Int = <caret>@ann 1
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
128
intellij-kotlin
Apache License 2.0
src/main/kotlin/com/moseoh/programmers_helper/conversion/action/service/impl/IConversionService.kt
azqazq195
615,468,409
false
null
package com.moseoh.programmers_helper.conversion.action.service.impl interface IConversionService { fun convert(code: String): String }
0
Kotlin
0
0
afc4ffc2b871305c47f408e62defcb1fa03fccd1
140
programmers_helper
MIT License
subprojects/publish-intellij-plugin/src/main/kotlin/intellij/plugin/portal/model/IdeaVersion.kt
nise-nabe
410,484,552
false
{"Kotlin": 29813}
package com.nisecoder.gradle.plugin.intellij.plugin.portal.model import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty data class IdeaVersion( @JacksonXmlProperty(isAttribute = true) val sinceBuild: String, @JacksonXmlProperty(isAttribute = true) val untilBuild: String, )
0
Kotlin
0
0
38853d592858bdeb7f048bbccceb945dcabcd0b8
311
gradle-plugins
MIT License
sct_project/app/src/main/java/com/spbarber/sct_project/entities/TrainingData.kt
SantipBarber
356,630,674
false
null
package com.spbarber.sct_project.entities import com.spbarber.sct_project.entities.VarsTraining data class TrainingData(val trainingData: MutableMap<String, VarsTraining>) { constructor(): this(trainingData = mutableMapOf()) override fun toString(): String { return trainingData.toString() } }
0
Kotlin
0
0
18b0f9847c60bba4b8c59855830727aec2550671
317
sct
MIT License
app/src/test/java/me/lazy_assedninja/demo/ui/demo/DemoViewModelTest.kt
henryhuang1219
357,838,778
false
null
package me.lazy_assedninja.demo.ui.demo import androidx.arch.core.executor.testing.InstantTaskExecutorRule import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import me.lazy_assedninja.demo.common.MainCoroutineRule import me.lazy_assedninja.demo.common.mock import me.lazy_assedninja.demo.data.Resource import me.lazy_assedninja.demo.domain.demo.GetDemoList import me.lazy_assedninja.demo.util.LiveDataUtil.getValue import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.`when` import org.mockito.Mockito.verify @ExperimentalCoroutinesApi @RunWith(JUnit4::class) class DemoViewModelTest { @get:Rule val instantExecutorRule = InstantTaskExecutorRule() @get:Rule val mainCoroutineRule = MainCoroutineRule() private val demo1 = "demo1" private val demo2 = "demo2" private val demos = listOf(demo1, demo2) private val getDemoList = mock<GetDemoList>() private lateinit var viewModel: DemoViewModel @Before fun init() { runTest { `when`(getDemoList.invoke()).thenReturn(Resource.success(demos)) } viewModel = DemoViewModel(getDemoList) } @Test fun loadDemosWhenViewModelInit() = runTest { assertThat(getValue(viewModel.isLoading), `is`(true)) withContext(mainCoroutineRule.dispatcher) { verify(getDemoList).invoke() assertThat(getValue(viewModel.demos), `is`(demos)) assertThat(getValue(viewModel.isLoading), `is`(false)) } } @Test fun openDemo() { viewModel.openDemo(demo1) assertThat(getValue(viewModel.openDemo).peekContent(), `is`(demo1)) } }
0
Kotlin
1
2
2f5a79974f8d6b6af516a8959824558324bab8ce
1,900
Android-Demo
Apache License 2.0
feature-notes-domain/src/main/kotlin/dev/bogdanzurac/marp/feature/notes/domain/ObserveUserNotesUseCase.kt
bogdanzurac
637,440,236
false
null
package dev.bogdanzurac.marp.feature.notes.domain import dev.bogdanzurac.marp.core.auth.AuthManager import dev.bogdanzurac.marp.core.mapResult import dev.bogdanzurac.marp.feature.crypto.domain.CryptoRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapConcat import org.koin.core.annotation.Singleton @Singleton class ObserveUserNotesUseCase( private val authManager: AuthManager, private val cryptoRepository: CryptoRepository, private val notesRepository: NotesRepository, ) { operator fun invoke(): Flow<Result<List<Note>>> = authManager.observeUser() .filterNotNull() .flatMapConcat { user -> notesRepository.observeNotes( listOf(Triple("userId", true, user.id)) ) } .mapResult { notes -> notes.map { note -> note.cryptoId?.let { return@map note.copy( cryptoAsset = cryptoRepository.getCryptoAsset(it).getOrNull() ) } ?: note } } }
0
Kotlin
0
0
e19a1494fbb0abadac81833a1fec108e613f04d4
1,199
marp-feature-notes
Apache License 2.0
presentation/src/main/java/com/arafat1419/collektr/presentation/ui/features/detail/DetailViewModel.kt
arafat1419
864,966,256
false
{"Kotlin": 175597}
package com.arafat1419.collektr.presentation.ui.features.detail import androidx.lifecycle.viewModelScope import com.arafat1419.collektr.domain.model.chatbid.ChatBid import com.arafat1419.collektr.domain.usecase.auction.countdown.GetAuctionCountdownUseCase import com.arafat1419.collektr.domain.usecase.auction.detail.GetAuctionDetailsUseCase import com.arafat1419.collektr.domain.usecase.chatbid.highest.GetAuctionHighestBidUseCase import com.arafat1419.collektr.domain.usecase.chatbid.list.GetAuctionChatBidsUseCase import com.arafat1419.collektr.domain.usecase.chatbid.send.SendAuctionBidUseCase import com.arafat1419.collektr.domain.usecase.chatbid.send.SendAuctionChatUseCase import com.arafat1419.collektr.domain.usecase.favorite.SetFavoriteAuctionUseCase import com.arafat1419.collektr.presentation.ui.viewmodel.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( private val getAuctionDetailsUseCase: GetAuctionDetailsUseCase, private val setFavoriteAuctionUseCase: SetFavoriteAuctionUseCase, private val getAuctionChatBidsUseCase: GetAuctionChatBidsUseCase, private val getHighestBidUseCase: GetAuctionHighestBidUseCase, private val sendAuctionBidUseCase: SendAuctionBidUseCase, private val sendAuctionChatUseCase: SendAuctionChatUseCase, private val getAuctionCountdownUseCase: GetAuctionCountdownUseCase ) : BaseViewModel<DetailViewState, DetailViewEvent>() { override fun createInitialState(): DetailViewState = DetailViewState() override fun onTriggerEvent(event: DetailViewEvent) { when (event) { is DetailViewEvent.GetAuctionDetail -> getAuctionDetail(event.auctionId) is DetailViewEvent.SetFavoriteAuction -> setFavoriteAuction( event.auctionId, event.state ) is DetailViewEvent.GetAuctionBids -> getAuctionBids(event.auctionId) is DetailViewEvent.GetHighestBid -> getHighestBid(event.auctionId) is DetailViewEvent.OnBidAmountChange -> setState { copy(bidAmount = event.amount) } is DetailViewEvent.OnChatMessageChange -> setState { copy(chatMessage = event.message) } is DetailViewEvent.SendBid -> sendBid(event.auctionId) is DetailViewEvent.SendMessage -> sendMessage(event.auctionId, event.message) is DetailViewEvent.GetAuctionCountdown -> getAuctionCountdown(event.targetTime) DetailViewEvent.ShowPlaceBidBottomSheet -> { setState { copy( bidError = "", bidAmount = maxOf( currentState.highestBid.bidAmount, currentState.auction.startBid ) + 10 ) } setEvent(DetailViewEvent.ShowPlaceBidBottomSheet) } DetailViewEvent.HidePlaceBidBottomSheet -> setEvent(DetailViewEvent.HidePlaceBidBottomSheet) } } private fun getAuctionDetail(auctionId: Int) { viewModelScope.launch { getAuctionDetailsUseCase.invoke(auctionId).collect { resource -> handleResource( resource = resource, setLoading = { setState { copy(isLoading = it) } }, setError = { setState { copy(error = it) } }, ) { data -> setState { copy(auction = data) } onTriggerEvent(DetailViewEvent.GetAuctionBids(auctionId)) onTriggerEvent(DetailViewEvent.GetAuctionCountdown(data.auctionEnd)) } } } } private fun getAuctionBids(auctionId: Int) { viewModelScope.launch { getAuctionChatBidsUseCase.invoke(auctionId).collect { resource -> handleResource( resource = resource, setLoading = { }, setError = { setState { copy(error = it) } }, { data -> setState { val uniqueBids = data.filter { newBid -> currentState.chatBids.none { existingBid -> existingBid.id == newBid.id && existingBid.isBid == newBid.isBid } } copy(chatBids = uniqueBids + currentState.chatBids) } onTriggerEvent(DetailViewEvent.GetHighestBid(auctionId)) } ) } } } private fun getHighestBid(auctionId: Int) { viewModelScope.launch { getHighestBidUseCase.invoke(auctionId).collect { resource -> handleResource( resource = resource, setLoading = { }, setError = { setState { copy(error = it) } }, { data -> setState { copy(highestBid = data) } } ) } } } private fun sendBid(auctionId: Int) { viewModelScope.launch { sendAuctionBidUseCase.invoke( ChatBid( auctionId = auctionId, userName = "<NAME>", bidAmount = currentState.bidAmount, isBid = true, createdAt = System.currentTimeMillis() / 1000 ), maxOf(currentState.highestBid.bidAmount, currentState.auction.startBid) ).also { setState { copy(bidError = it) } if (it.isEmpty()) { setEvent(DetailViewEvent.HidePlaceBidBottomSheet) } } } } private fun sendMessage(auctionId: Int, message: String) { viewModelScope.launch { sendAuctionChatUseCase.invoke( ChatBid( auctionId = auctionId, userName = "<NAME>", chatMessage = message, isBid = false, createdAt = System.currentTimeMillis() / 1000 ) ) setState { copy(chatMessage = "") } } } private fun setFavoriteAuction(auctionId: Int, state: Boolean) { viewModelScope.launch { setFavoriteAuctionUseCase.invoke(auctionId, state) } } private fun getAuctionCountdown(targetTime: Long) { viewModelScope.launch { getAuctionCountdownUseCase.invoke(targetTime).collect { resource -> handleResource( resource = resource, setLoading = { setState { copy(isLoading = it) } }, setError = { setState { copy(error = it) } }, ) { data -> setState { copy(countdown = data) } } } } } }
0
Kotlin
0
0
e59a55193624312377430216c2c464c77da999d1
7,071
Collektr-Test
Apache License 2.0
data/src/main/java/com/alexzaitsev/modern/data/source/api/api/ApiV1.kt
alexzaitsev
590,866,312
false
null
package com.alexzaitsev.modern.data.source.api.api import com.alexzaitsev.modern.data.source.api.model.ApiTestModel /** * This should be extended to Retrofit interface */ internal interface ApiV1 { fun getData(): List<ApiTestModel> }
0
Kotlin
0
0
a70ffd571b62a164814bc519f1fc7b44e156cd93
243
android-modern-architecture
MIT License
dd-sdk-android/src/main/kotlin/com/datadog/android/core/internal/persistence/file/batch/EncryptedBatchReaderWriter.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.core.internal.persistence.file.batch import androidx.annotation.WorkerThread import com.datadog.android.api.InternalLogger import com.datadog.android.security.Encryption import java.io.File internal class EncryptedBatchReaderWriter( internal val encryption: Encryption, internal val delegate: BatchFileReaderWriter, private val internalLogger: InternalLogger ) : BatchFileReaderWriter by delegate { @WorkerThread override fun writeData( file: File, data: ByteArray, append: Boolean ): Boolean { val encryptedData = encryption.encrypt(data) if (data.isNotEmpty() && encryptedData.isEmpty()) { internalLogger.log( InternalLogger.Level.ERROR, InternalLogger.Target.USER, { BAD_ENCRYPTION_RESULT_MESSAGE } ) return false } return delegate.writeData( file, encryptedData, append ) } @WorkerThread override fun readData( file: File ): List<ByteArray> { return delegate.readData(file) .map { encryption.decrypt(it) } } companion object { internal const val BAD_ENCRYPTION_RESULT_MESSAGE = "Encryption of non-empty data produced" + " empty result, aborting write operation." } }
42
Kotlin
48
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
1,669
dd-sdk-android
Apache License 2.0
app/src/main/java/com/sharkaboi/mediahub/di/ProfileModule.kt
susyimes
374,498,548
true
{"Kotlin": 395754}
package com.sharkaboi.mediahub.di import com.sharkaboi.mediahub.common.data.datastore.DataStoreRepository import com.sharkaboi.mediahub.common.data.retrofit.UserService import com.sharkaboi.mediahub.modules.profile.repository.ProfileRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.hilt.android.scopes.ActivityRetainedScoped @InstallIn(ActivityRetainedComponent::class) @Module object ProfileModule { @Provides @ActivityRetainedScoped fun getProfileRepository( userService: UserService, dataStoreRepository: DataStoreRepository ): ProfileRepository = ProfileRepository(userService, dataStoreRepository) }
0
null
0
0
2eb16521df7dbfb7a615b63054f01f54ebe6ce5c
760
MediaHub
MIT License
src/main/kotlin/com/example/kotlin/api/repository/entity/ExampleEntity.kt
jorgecodelia
764,383,918
false
{"Kotlin": 9909}
package com.example.kotlin.api.repository.entity import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import org.hibernate.Hibernate @Entity data class ExampleEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long = 0, val name: String ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false other as ExampleEntity return id != null && id == other.id } override fun hashCode(): Int = javaClass.hashCode() @Override override fun toString(): String { return this::class.simpleName + "(id = $id )" } }
0
Kotlin
0
0
6eeb4e25c9dbcf9b038724d19c347edb0f63fd16
813
kotlinApi
MIT License
src/main/kotlin/kr/syeyoung/LinkManager.kt
Dungeons-Guide
584,048,540
false
null
package kr.syeyoung import dev.kord.common.entity.Snowflake object LinkManager { suspend fun makeLink(issueNum: Long, parentId: Snowflake, threadId: Snowflake) { redisClient.set("link.github.$issueNum", "$parentId-$threadId") redisClient.set("link.discord.$parentId.$threadId", issueNum.toString()) } suspend fun unLink(issueNum: Long, parentId: Snowflake, threadId: Snowflake) { redisClient.del("link.github.$issueNum", "link.discord.$parentId.$threadId"); } suspend fun linkMessage(githubIssueNum: Long, githubCommentId: Long, threadId: Snowflake, messageId: Snowflake) { redisClient.set("mlink.github.$githubIssueNum-$githubCommentId", "$threadId-$messageId") redisClient.set("mlink.discord.$threadId-$messageId", "$githubIssueNum-$githubCommentId") } suspend fun linkTMessage(githubIssueNum: Long, threadId: Snowflake, messageId: Snowflake) { redisClient.set("tlink.github.$githubIssueNum", "$threadId-$messageId") redisClient.set("tlink.discord.$threadId-$messageId", "$githubIssueNum") } suspend fun getThreadIdByGithub(issueNum: Long): Pair<Snowflake, Snowflake> { return redisClient.get("link.github.$issueNum") ?.split("-") ?.let { Pair(Snowflake(it[0].toULong()), Snowflake(it[1].toULong())) } ?: throw IllegalStateException("Not found"); } suspend fun getThreadIdByDiscord(parentId: Snowflake, id: Snowflake): Long { return redisClient.get("link.discord.$parentId.$id")?.toLong() ?: throw IllegalStateException("Not found"); } suspend fun getMessageIdByGithub(issueNum: Long, commentId: Long): Pair<Snowflake, Snowflake> { return redisClient.get("mlink.github.$issueNum-$commentId")?.split("-")?.let { Snowflake(it[0].toULong()) to Snowflake(it[1].toULong()) }?: throw IllegalStateException("Not found"); } suspend fun getGithubIdByDiscord(threadId: Snowflake, messageId: Snowflake): Pair<Long, Long> { return redisClient.get("mlink.discord.$threadId-$messageId")?.split("-")?.let { it[0].toLong() to it[1].toLong() }?: throw IllegalStateException("Not found") } suspend fun getGithubIdByTDiscord(threadId: Snowflake, messageId: Snowflake): Long? { return redisClient.get("tlink.discord.$threadId-$messageId")?.toLong(); } suspend fun getDiscordIdByTGithub(issueNum: Long): Pair<Long, Long>? { return redisClient.get("tlink.github.$issueNum")?.split("-")?.let { it[0].toLong() to it[1].toLong() } } }
0
Kotlin
0
0
632155e345b4b62d5a83d2174ab9e5541c7abd23
2,525
DGLink
MIT License
features/detail_screen/src/main/java/com/yigitozgumus/detail_screen/presentation/DetailViewModel.kt
yigitozgumus
475,998,040
false
{"Kotlin": 49621}
/* * Created by yigitozgumus on 4/4/22, 10:18 PM * Copyright (c) 2022 . All rights reserved. * Last modified 4/4/22, 10:18 PM */ package com.yigitozgumus.detail_screen.presentation import com.yigitozgumus.base_feature.base.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor() : BaseViewModel()
0
Kotlin
0
0
ca3ff32aaab6fd96fcee9f7c69098f99d10300ed
399
DemoCurrencyApplication
MIT License
app/src/main/java/com/put/mrugas/pepperdemo/MainActivity.kt
mrugacz95
157,788,650
false
null
package com.put.mrugas.pepperdemo import android.os.Bundle import android.util.Log import com.aldebaran.qi.sdk.QiContext import com.aldebaran.qi.sdk.QiSDK import com.aldebaran.qi.sdk.RobotLifecycleCallbacks import com.aldebaran.qi.sdk.builder.* import com.aldebaran.qi.sdk.design.activity.RobotActivity class MainActivity : RobotActivity(), RobotLifecycleCallbacks { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) QiSDK.register(this, this) } override fun onRobotFocusGained(qiContext: QiContext?) { val say = SayBuilder.with(qiContext) .withText("Hello ISWD!") .build() say.run() val topic = TopicBuilder.with(qiContext) .withResource(R.raw.greetings) .build() val chatBot = QiChatbotBuilder.with(qiContext) .withTopic(topic) .build() val chat = ChatBuilder.with(qiContext) .withChatbot(chatBot) .build() chat.addOnHeardListener { phrase -> if (phrase.text == "cheers") { val animation = AnimationBuilder.with(qiContext).withResources(R.raw.cheers).build() val animate = AnimateBuilder.with(qiContext).withAnimation(animation).build() animate.async().run() } } chat.async().run() } override fun onRobotFocusLost() { Log.d("Pepper", "onRobotFocusLost") } override fun onRobotFocusRefused(reason: String?) { Log.d("Pepper", "onRobotFocusRefused") } override fun onDestroy() { QiSDK.unregister(this, this) super.onDestroy() } }
0
Kotlin
0
0
c8aac1cf1e1b8b5b89feecb2fee093f8c6dd0819
1,742
PepperDemo
MIT License
privacysandbox/tools/tools/src/main/java/androidx/privacysandbox/tools/PrivacySandboxCallback.kt
androidx
256,589,781
false
null
/* * Copyright 2022 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.privacysandbox.tools /** * Annotated callbacks that can be passed to an SDK running in the privacy sandbox. * * Callbacks should be public interfaces that only declare functions without implementation. * Callback functions should be fire-and-forget: non-suspending functions that have no return value. */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class PrivacySandboxCallback
23
Kotlin
740
4,353
3492e5e1782b1524f2ab658f1728c89a35c7336d
1,056
androidx
Apache License 2.0
src/DcircleChain/wallet/app/src/main/java/com/example/myapplication/ui/dashboard/DashboardFragment.kt
wanxiang-blockchain
683,936,032
false
{"Kotlin": 564771, "Java": 393645, "TypeScript": 313064, "Go": 182715, "SCSS": 72564, "CSS": 6411, "Solidity": 4012, "JavaScript": 2433, "HTML": 2352}
package com.example.myapplication.ui.dashboard import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.myapplication.databinding.FragmentDashboardBinding import com.example.myapplication.fundation.ThirdWallet import com.example.myapplication.fundation.ThirdWalletHelper import com.example.myapplication.fundation.db.DCWalletDataBase import com.example.myapplication.fundation.wallet.PolygonWallet import kotlinx.coroutines.* import java.math.BigInteger import kotlin.concurrent.thread class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private var startSync:Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java) _binding = FragmentDashboardBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.blance dashboardViewModel.text.observe(viewLifecycleOwner) { textView.text = it } var user = DCWalletDataBase.getUserDao(context!!)?.me() var wallet = PolygonWallet.loadWalletWithMnemonic(context!!,user!!) thread(start = true) { binding.address.text = "地址:${wallet.getAddress()}" Log.d("DashboardFragment","地址:${wallet.getAddress()}") syncBalanceTask(dashboardViewModel,wallet) } var transferBtn :Button = binding.transferBtn transferBtn.setOnClickListener(View.OnClickListener { GlobalScope.launch(Dispatchers.IO) { var result:Deferred<String> = async { try { return@async wallet.transferContract( PolygonWallet.DCTOKEN_ADDRESS, "0x3cF26E1590b443A7D015D9A9E0A68EFadeB68782", BigInteger.valueOf(100) ) } catch (e:java.lang.Exception) { alert(inflater.context,"错误",e.message.toString()) return@async "" } } var txn = result.await() if (txn != "") { alert(inflater.context, "操作成功", "交易已经提交:txn:${txn}") } } }) var depositBtn :Button = binding.depositBtn depositBtn.setOnClickListener(View.OnClickListener { GlobalScope.launch(Dispatchers.IO) { var result:Deferred<String> = async { try { return@async wallet.depositsWithToken( PolygonWallet.DCTOKEN_ADDRESS, PolygonWallet.DCChainToken_Address, "0x3cF26E1590b443A7D015D9A9E0A68EFadeB68782", BigInteger.valueOf(100) ) } catch (e:java.lang.Exception) { alert(inflater.context,"错误",e.message.toString()) return@async "" } } var txn = result.await() if (txn != "") { alert(inflater.context, "操作成功", "交易已经提交:txn:${txn}") } } }) return root } fun alert(context:Context,title:String,message: String) { GlobalScope.launch { withContext(Dispatchers.Main) { var ethEstimateGasAlert = AlertDialog.Builder(context) .setTitle(title) .setMessage(message) .setPositiveButton( "确定", DialogInterface.OnClickListener { dialog, which -> // Handle button click dialog.dismiss() } ) .create() ethEstimateGasAlert.show() } } } fun syncBalanceTask(dashboardViewModel:DashboardViewModel,wallet:PolygonWallet) { if (startSync == false) { GlobalScope.launch { while (true) { var mainBlance = "MATIC:" + wallet.getBalance().toString() + "MATIC" var tokenBlance = "\nTOKEN:" + wallet.getTokenBalance(PolygonWallet.DCTOKEN_ADDRESS) .toString() var dcc = wallet.getTokenBalance(PolygonWallet.DCChainToken_Address)!! .divide(BigInteger("100000000000000000")) var dcCoinBlance = "\nDcChain Coin(DCC):" +dcc .toString() var blanceString = "余额\n${mainBlance} ${dcCoinBlance} ${tokenBlance}" dashboardViewModel.changeText(blanceString) delay(5000) Log.i("syncBalance", blanceString) } } startSync= true } } fun startMetaMaskTokenTransaction(context:Context,wallet:ThirdWallet,tokenAddress: String, toAddress: String, amount: Int) { val packageName = ThirdWalletHelper.getWalletPackage(wallet) val intent = Intent(Intent.ACTION_VIEW) // intent.data = Uri.parse("ethereum:token-transfer?address=$tokenAddress&to=$toAddress&uint256=$amount") intent.data = Uri.parse("ethereum:${tokenAddress}/?address=$toAddress&value=$amount") intent.setPackage(packageName) if (isPackageInstalled(context,packageName)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) Toast.makeText(context,"启动 ${wallet.name}!",Toast.LENGTH_SHORT).show() context.startActivity(intent) } else { // MetaMask 应用未安装 // 可以在这里提示用户安装 MetaMask 应用 Toast.makeText(context,"${wallet.name} not installed!",Toast.LENGTH_SHORT).show() } } fun isPackageInstalled(context: Context, packageName: String?): Boolean { return try { val pm: PackageManager = context.getPackageManager() pm.getPackageInfo(packageName!!, 0) true } catch (e: PackageManager.NameNotFoundException) { false } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
8
29
d3a91f9fb7b0a5b29806bcd2968e4dc8d894581b
7,115
2023WXH-DcircleChain
MIT License
sync/sync-impl/src/main/java/com/duckduckgo/sync/impl/ui/setup/SyncCreateAccountViewModel.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.sync.impl.ui.setup import androidx.annotation.StringRes import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.duckduckgo.anvil.annotations.ContributesViewModel import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.ActivityScope import com.duckduckgo.sync.impl.R import com.duckduckgo.sync.impl.SyncAccountRepository import com.duckduckgo.sync.impl.onFailure import com.duckduckgo.sync.impl.onSuccess import com.duckduckgo.sync.impl.pixels.SyncPixels import com.duckduckgo.sync.impl.ui.setup.SaveRecoveryCodeViewModel.Command import com.duckduckgo.sync.impl.ui.setup.SyncCreateAccountViewModel.Command.FinishSetupFlow import com.duckduckgo.sync.impl.ui.setup.SyncCreateAccountViewModel.ViewMode.CreatingAccount import javax.inject.* import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch @ContributesViewModel(ActivityScope::class) class SyncCreateAccountViewModel @Inject constructor( private val syncAccountRepository: SyncAccountRepository, private val syncPixels: SyncPixels, private val dispatchers: DispatcherProvider, ) : ViewModel() { private val command = Channel<Command>(1, DROP_OLDEST) private val viewState = MutableStateFlow(ViewState()) fun viewState(): Flow<ViewState> = viewState.onStart { createAccount() } fun commands(): Flow<Command> = command.receiveAsFlow() sealed class Command { object FinishSetupFlow : Command() object AbortFlow : Command() object Error : Command() data class ShowError(@StringRes val message: Int, val reason: String? = "") : Command() } data class ViewState( val viewMode: ViewMode = CreatingAccount, ) sealed class ViewMode { object CreatingAccount : ViewMode() object SignedIn : ViewMode() } private fun createAccount() = viewModelScope.launch(dispatchers.io()) { viewState.emit(ViewState(CreatingAccount)) if (syncAccountRepository.isSignedIn()) { command.send(FinishSetupFlow) } else { syncAccountRepository.createAccount().onSuccess { syncPixels.fireSignupDirectPixel() command.send(FinishSetupFlow) }.onFailure { command.send(Command.ShowError(R.string.sync_create_account_generic_error, it.reason)) } } } fun onErrorDialogDismissed() { viewModelScope.launch(dispatchers.io()) { command.send(Command.AbortFlow) } } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
2,799
DuckDuckGo
Apache License 2.0
app/src/main/kotlin/de/markusfisch/android/binaryeye/fragment/EncodeFragment.kt
yzqzss
248,396,812
true
{"Kotlin": 117332, "Shell": 1967, "RenderScript": 625, "Makefile": 566}
package de.markusfisch.android.binaryeye.fragment import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.* import com.google.zxing.BarcodeFormat import de.markusfisch.android.binaryeye.R import de.markusfisch.android.binaryeye.app.addFragment import de.markusfisch.android.binaryeye.app.prefs import de.markusfisch.android.binaryeye.app.setWindowInsetListener import de.markusfisch.android.binaryeye.view.setPadding class EncodeFragment : Fragment() { private lateinit var formatView: Spinner private lateinit var sizeView: TextView private lateinit var sizeBarView: SeekBar private lateinit var contentView: EditText private val writers = arrayListOf( BarcodeFormat.AZTEC, BarcodeFormat.CODABAR, BarcodeFormat.CODE_39, BarcodeFormat.CODE_128, BarcodeFormat.DATA_MATRIX, BarcodeFormat.EAN_8, BarcodeFormat.EAN_13, BarcodeFormat.ITF, BarcodeFormat.PDF_417, BarcodeFormat.QR_CODE, BarcodeFormat.UPC_A ) override fun onCreate(state: Bundle?) { super.onCreate(state) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, state: Bundle? ): View? { val ac = activity ?: return null ac.setTitle(R.string.compose_barcode) val view = inflater.inflate( R.layout.fragment_encode, container, false ) formatView = view.findViewById(R.id.format) formatView.adapter = ArrayAdapter<String>( ac, android.R.layout.simple_list_item_1, writers.map { it.name } ) sizeView = view.findViewById(R.id.size_display) sizeBarView = view.findViewById(R.id.size_bar) initSizeBar() contentView = view.findViewById<EditText>(R.id.content) val args = arguments args?.also { contentView.setText(it.getString(CONTENT)) } val barcodeFormat = args?.getSerializable(FORMAT) as BarcodeFormat? if (barcodeFormat != null) { formatView.setSelection(writers.indexOf(barcodeFormat)) } else if (state == null) { formatView.post { formatView.setSelection(prefs.indexOfLastSelectedFormat) } } view.findViewById<View>(R.id.encode).setOnClickListener { v -> encode() } setWindowInsetListener { insets -> (view.findViewById(R.id.inset_layout) as View).setPadding(insets) (view.findViewById(R.id.scroll_view) as View).setPadding(insets) } return view } override fun onPause() { super.onPause() prefs.indexOfLastSelectedFormat = formatView.selectedItemPosition } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.fragment_encode, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.next -> { encode() true } else -> super.onOptionsItemSelected(item) } } private fun encode() { val format = writers[formatView.selectedItemPosition] val size = getSize(sizeBarView.progress) val content = contentView.text.toString() if (content.isEmpty()) { Toast.makeText( context, R.string.error_no_content, Toast.LENGTH_SHORT ).show() } else { hideSoftKeyboard(contentView) addFragment( fragmentManager, BarcodeFragment.newInstance(content, format, size) ) } } private fun initSizeBar() { updateSize(sizeBarView.progress) sizeBarView.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged( seekBar: SeekBar, progressValue: Int, fromUser: Boolean ) { updateSize(progressValue) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) } private fun updateSize(power: Int) { val size = getSize(power) sizeView.text = getString(R.string.width_by_height, size, size) } private fun getSize(power: Int) = 128 * (power + 1) private fun hideSoftKeyboard(view: View) { val im = activity?.getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager? im?.let { im.hideSoftInputFromWindow(view.windowToken, 0) } } companion object { private const val CONTENT = "content" private const val FORMAT = "format" fun newInstance( content: String, format: BarcodeFormat? = null ): Fragment { val args = Bundle() args.putString(CONTENT, content) format?.let { args.putSerializable(FORMAT, format) } val fragment = EncodeFragment() fragment.arguments = args return fragment } } }
0
Kotlin
0
0
8e24673d08627545035c14d1b78c0433282753ad
4,697
BinaryEye
MIT License
app/src/main/java/tech/medina/adichallenge/data/repository/ReviewRepository.kt
eamedina87
364,712,252
false
null
package tech.medina.adichallenge.data.repository import tech.medina.adichallenge.data.api.ReviewApi import tech.medina.adichallenge.data.api.dto.ReviewDto import javax.inject.Inject interface IReviewRepository { suspend fun getReviewsForProductWithId(productId: String): List<ReviewDto> suspend fun addReviewForProductWithId(productId: String, review: ReviewDto): ReviewDto } class ReviewRepository @Inject constructor(private val api: ReviewApi): IReviewRepository { override suspend fun getReviewsForProductWithId(productId: String): List<ReviewDto> = api.getAllReviewsForProductWithId(productId) override suspend fun addReviewForProductWithId(productId: String, review: ReviewDto): ReviewDto = api.postReviewForProductWithId(productId, review) }
0
Kotlin
0
0
4172b5e4707c6cb1872b725692af9ff2e57bb6b7
786
adichallenge
The Unlicense
app/src/main/java/com/master/iot/luzi/ui/utils/EventGenerator.kt
pa7ri
541,784,867
false
null
package com.master.iot.luzi.ui.utils import android.os.Bundle import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.FirebaseAnalytics.Param.ITEM_NAME class EventGenerator { companion object { const val SCREEN_VIEW_ELECTRICITY = "electricity-screen" const val SCREEN_VIEW_PETROL = "petrol-screen" const val SCREEN_VIEW_REWARDS = "rewards-screen" const val SCREEN_VIEW_SETTINGS = "settings-screen" const val SCREEN_VIEW_VERIFIER = "verifier-screen" const val ACTION_ELECTRICITY_SHOW_CHART = "electricity-show-chart" const val ACTION_ELECTRICITY_SHOW_LIST = "electricity-show-list" const val ACTION_ELECTRICITY_CHANGE_DATE = "electricity-change-date" const val ACTION_ELECTRICITY_CHANGE_LOCATION = "electricity-change-location" const val ACTION_ELECTRICITY_CHANGE_FEE = "electricity-change-fee" const val ACTION_ELECTRICITY_ENABLE_PUSH_NOTIFICATION = "electricity-enable-push-notification" const val ACTION_ELECTRICITY_DISABLE_PUSH_NOTIFICATION = "electricity-disable-push-notification" const val ACTION_PETROL_CHANGE_LOCATION = "petrol-change-location" const val ACTION_PETROL_CHANGE_PRODUCT = "petrol-change-product" const val ACTION_REWARDS_CHECK_POINTS = "rewards-check-points" const val ACTION_REWARDS_CHECK_SAVING = "rewards-check-saving" const val ACTION_REWARDS_CREATE_APPLIANCE_REPORT = "rewards-create-appliance-report" const val ACTION_REWARDS_CREATE_RECEIPT_REPORT = "rewards-create-receipt-report" private fun createSimpleEvent(name: String): Bundle { return Bundle().apply { putString(ITEM_NAME, name) } } fun sendScreenViewEvent(firebaseAnalytics: FirebaseAnalytics, action: String) { firebaseAnalytics.logEvent( FirebaseAnalytics.Event.SCREEN_VIEW, createSimpleEvent(action) ) } fun sendActionEvent(firebaseAnalytics: FirebaseAnalytics, action: String) { firebaseAnalytics.logEvent( FirebaseAnalytics.Event.SELECT_CONTENT, createSimpleEvent(action) ) } } }
0
Kotlin
0
0
a35ff3c7cbbb5704f10980b3472f3217725a0db9
2,268
luzi
MIT License
app/src/main/java/divyansh/tech/wallup/home/browse/screens/popularTags/source/PopularTagsDataSource.kt
justdvnsh
409,287,171
false
null
package divyansh.tech.wallup.home.browse.screens.popularTags.source import divyansh.tech.wallup.home.browse.datamodel.Wallpapers import divyansh.tech.wallup.utils.Result import kotlinx.coroutines.flow.Flow interface PopularTagsDataSource { suspend fun getWallpapers(url: String): Flow<Result<ArrayList<Wallpapers>>> }
15
Kotlin
6
7
b23f982ae5ff7b21adc3af62f38f639e054fef62
323
WallUP
The Unlicense
test/src/main/kotlin/de/faweizz/poc/util/OpenIdGrant.kt
faweizz
390,689,980
false
null
package de.faweizz.poc.util import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class OpenIdGrant( @SerialName("access_token") val accessToken: String, @SerialName("expires_in") val expiresIn: Long, @SerialName("refresh_expires_in") val refreshExpiresIn: Long, @SerialName("refresh_token") val refreshToken: String, @SerialName("token_type") val tokenType: String, @SerialName("id_token") val idToken: String, @SerialName("not-before-policy") val notBeforePolicy: Long, val scope: String, @SerialName("session_state") val sessionState: String, )
0
Kotlin
0
0
b5b494e81e6643c86d51f884309497bc78715f36
665
florescence
Apache License 2.0
packages/gradle-plugin/shared/src/main/kotlin/com/facebook/react/model/ModelAutolinkingDependenciesPlatformAndroidJson.kt
react-native-tvos
177,633,560
false
{"C++": 4398815, "Java": 2649623, "JavaScript": 2551815, "Objective-C++": 1803949, "Kotlin": 1628327, "Objective-C": 1421207, "Ruby": 453872, "CMake": 109113, "TypeScript": 85912, "Shell": 58251, "C": 57980, "Assembly": 14920, "HTML": 1473, "Swift": 739}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.model data class ModelAutolinkingDependenciesPlatformAndroidJson( val sourceDir: String, val packageImportPath: String, val packageInstance: String, val buildTypes: List<String>, val libraryName: String? = null, val componentDescriptors: List<String> = emptyList(), val cmakeListsPath: String? = null, val cxxModuleCMakeListsModuleName: String? = null, val cxxModuleCMakeListsPath: String? = null, val cxxModuleHeaderName: String? = null, val dependencyConfiguration: String? = null )
7
C++
147
942
692bc66a98c8928c950bece9a22d04c13f0c579d
748
react-native-tvos
MIT License
app/src/main/java/inoxoft/simon/shop/model/cash/CashDao.kt
Sighmore
872,072,217
false
{"Kotlin": 22850}
package inoxoft.simon.shop.model.cash import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import kotlinx.coroutines.flow.Flow @Dao interface CashDao { @Upsert //parameter stock of type Stock suspend fun upsertRecord(record: Record) @Delete suspend fun deleteRecord(record: Record) @Query("SELECT * FROM Record") fun getRecords(): Flow<List<Record>> }
0
Kotlin
0
0
2670e304a51282f79134e01ad53253c321b72e62
441
Rizz-Shop
MIT License
app/src/main/kotlin/com/thundermaps/apilib/android/api/ExcludeFromJacocoGeneratedReport.kt
SaferMe
240,105,080
false
null
package com.thundermaps.apilib.android.api import java.lang.annotation.Retention @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.FIELD, AnnotationTarget.PROPERTY, AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER ) annotation class ExcludeFromJacocoGeneratedReport
2
Kotlin
0
0
e10d64c126cb13e56e5089e8bedd249534dc2ccf
552
saferme-api-client-android
MIT License
sample/me/src/main/java/club/fdawei/comkit/sample/me/MeAppDelegate.kt
fangdawei
194,708,082
false
{"Groovy": 46142, "Kotlin": 10022}
package club.fdawei.comkit.sample.me import android.app.Application import android.util.Log import club.fdawei.comkit.annotation.AppDelegate import club.fdawei.comkit.api.app.IAppDelegate /** * Create by david on 2019/07/21. */ @AppDelegate class MeAppDelegate : IAppDelegate { override fun onCreate(app: Application) { Log.i("me", "MeAppDelegate onCreate") } }
0
Groovy
0
1
9845e262613487880d70598a19df6187a513e171
381
ComKit
Apache License 2.0
src/main/java/io/ejekta/kambrik/ext/render/ExtVertexConsumer.kt
ejektaflex
273,374,760
false
null
package io.ejekta.kambrik.ext.render import net.minecraft.client.render.VertexConsumer import net.minecraft.util.math.Matrix4f import net.minecraft.util.math.Vec3d import net.minecraft.util.math.Vec3f inline fun VertexConsumer.vertex(matrix4f: Matrix4f, vec3d: Vec3d): VertexConsumer { return apply { vertex(matrix4f, vec3d.x.toFloat(), vec3d.y.toFloat(), vec3d.z.toFloat()) } } inline fun VertexConsumer.vertex(matrix4f: Matrix4f, vec3f: Vec3f): VertexConsumer { return apply { vertex(matrix4f, vec3f.x, vec3f.y, vec3f.z) } }
1
Kotlin
2
8
4689a76f64968e463b3332f6a6534656ca85af24
561
Kambrik
MIT License
app/src/main/java/dev/ankurg/statetest/MainActivity.kt
ankurg22
326,782,202
false
null
package dev.ankurg.statetest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), GreetingView { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun showProgress(show: Boolean) { progressBar.visibility = if (show) View.VISIBLE else View.GONE } override fun showError(error: String?) { errorTextView.visibility = View.VISIBLE errorTextView.text = error } override fun showGreeting(greeting: String?) { greetingTextView.visibility = View.VISIBLE greetingTextView.text = greeting } }
0
Kotlin
0
5
48c34a05fc78e50f9624c4d9023677a3eef3a513
805
state-rendering-demo
Apache License 2.0
plugins/python/src/main/kotlin/io/paddle/plugin/python/dependencies/repositories/PyPackageRepository.kt
TanVD
377,213,824
false
null
package io.paddle.plugin.python.dependencies.repositories import io.paddle.plugin.python.PaddlePyConfig import io.paddle.plugin.python.dependencies.index.PyPackageRepositoryIndexer import io.paddle.plugin.python.dependencies.index.distributions.PyDistributionInfo import io.paddle.plugin.python.dependencies.index.wordlist.PackedWordList import io.paddle.plugin.python.dependencies.index.wordlist.PackedWordListSerializer import io.paddle.plugin.python.utils.* import io.paddle.utils.hash.StringHashable import kotlinx.serialization.* import java.io.File @Serializable class PyPackageRepository(val url: PyPackagesRepositoryUrl, val name: String) { constructor(metadata: Metadata) : this(metadata.url, metadata.name) @Serializable data class Metadata(val url: PyPackagesRepositoryUrl, val name: String) val metadata = Metadata(url, name) companion object { val PYPI_REPOSITORY = PyPackageRepository("https://pypi.org", "pypi") } // Index is loaded from cache @Serializable(with = PackedWordListSerializer::class) private var packagesNamesCache: PackedWordList = PackedWordList.empty // Index is loaded from cache private val distributionsCache: MutableMap<PyPackageName, List<PyDistributionInfo>> = HashMap() @Transient val urlSimple: PyPackagesRepositoryUrl = url.join("simple") @Transient val cacheFileName: String = StringHashable(url).hash() suspend fun updateIndex() { packagesNamesCache = PackedWordList(PyPackageRepositoryIndexer.downloadPackagesNames(this).toSet()) } fun loadCache(file: File) { require(file.name == this.cacheFileName) val cachedCopy: PyPackageRepository = jsonParser.decodeFromString(file.readText()) packagesNamesCache = cachedCopy.packagesNamesCache } fun getPackagesNamesByPrefix(prefix: String): Sequence<PyPackageName> = packagesNamesCache.prefix(prefix) suspend fun findAvailableDistributionsByPackageName(packageName: PyPackageName, useCache: Boolean = true): List<PyDistributionInfo> { val distributions = PyPackageRepositoryIndexer.downloadDistributionsList(packageName, this) return if (useCache) { distributionsCache.getOrPut(packageName) { distributions } } else { distributions } } fun saveCache() { PaddlePyConfig.indexDir.resolve(this.cacheFileName).toFile() .writeText(jsonParser.encodeToString(this)) } override fun hashCode() = metadata.hashCode() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PyPackageRepository return metadata == other.metadata } }
6
Kotlin
2
2
39004697aa9c9ece4fadc4df5d5bdd19a63f2181
2,757
paddle
MIT License
src/main/kotlin/com/evilcorp/soulmanager/dto/SigninPayload.kt
SuicideSin
225,010,137
true
{"Kotlin": 23857}
package com.evilcorp.soulmanager.dto import com.evilcorp.soulmanager.entity.User data class SigninPayload(val token: String, val user: User)
0
null
0
0
e8e62641f0983aca6dcd72e060e64a16f2d72e8f
142
SoulManager
Apache License 2.0
kodein-di/src/jvmMain/kotlin/org/kodein/di/erased/ESubTypesJVM.kt
romainbsl
251,124,051
true
{"Kotlin": 679207, "Java": 16368}
package org.kodein.di.erased import org.kodein.di.bindings.DIBinding import org.kodein.di.bindings.TypeBinderSubTypes import org.kodein.type.TypeToken import org.kodein.type.generic /** * Allows to define a binding that will be called for any subtype of this type. * * First part of the `bind<Type>().subTypes() with { type -> binding }` syntax. * * @param T The parent type. * @param block A function that will give the binding for the provided sub-type. */ inline infix fun <reified C : Any, reified A : Any, reified T: Any> TypeBinderSubTypes<T>.with(noinline block: (TypeToken<out T>) -> DIBinding<in C, in A, out T>) = With<C, A>(generic<C>(), generic<A>(), generic<T>(), block)
0
Kotlin
0
0
17534da15c806d094808a619fcc930bec729297e
694
Kodein-DI
MIT License
src/com/rian/osu/beatmap/hitobject/sliderobject/SliderHead.kt
osudroid
248,937,035
false
{"Java": 2551119, "Kotlin": 759688, "HTML": 1699, "Batchfile": 50}
package com.rian.osu.beatmap.hitobject.sliderobject import com.rian.osu.math.Vector2 /** * Represents the head of a slider. */ class SliderHead( /** * The start time of this [SliderHead], in milliseconds. */ startTime: Double, /** * The position of this [SliderHead] relative to the play field. */ position: Vector2 ) : SliderHitObject(startTime, position, 0, startTime)
27
Java
77
521
9f1da90c2c26b179bf425fb55fbb626515c2fc97
412
osu-droid
Apache License 2.0
core/src/gameobjects/GameScreenUI.kt
PatriotCodes
114,823,813
false
null
package gameobjects import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.GlyphLayout import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Button import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.TextField import enums.BonusType import utils.GameScreenAssets import utils.MyScreenUtils class GameScreenUI(private val assets: GameScreenAssets, private val gameGrid: GameGrid, private val bonuses: Map<BonusType,Int>) { // TODO: check why circle of different size on phone and on desktop private val screenUtils = MyScreenUtils() private var colWidth = Gdx.graphics.width.toFloat() * 0.4f private var colHeight = Gdx.graphics.height.toFloat() / 9f private var widthAddition = screenUtils.initScreenWidth / 10f private val movesCircleRadius = (Gdx.graphics.width.toFloat() - (colWidth * 2)) / 2 // height = width private val moveCircleCenter = Vector2(colWidth + movesCircleRadius,Gdx.graphics.height.toFloat() - movesCircleRadius) private val shape = ShapeRenderer() private val decreasePercent : Float = 360f / gameGrid.movesLeft.toFloat() private var progressArcColor = Color.GREEN private val buttonSize = (movesCircleRadius * 2) / 1.5f private val menuButtonPosition = Vector2(Gdx.graphics.width - colHeight,Gdx.graphics.height - colHeight) init { assert(bonuses.size < 5,{ "Max number of bonuses is 4!!!" }) } fun draw(batch: SpriteBatch) { drawUIBars(batch) batch.end() drawProgressArc() batch.begin() drawTopBarMoves(batch) drawTopBarButtons(batch) drawBottomBarButtons(batch) drawScore(batch) drawObjectives(batch) } private fun drawUIBars(batch: SpriteBatch) { batch.draw(assets.uiBar, screenUtils.initXOffset - (widthAddition / 2f),Gdx.graphics.height.toFloat() - colHeight,(screenUtils.initScreenWidth + widthAddition),colHeight) batch.draw(assets.uiBar, screenUtils.initXOffset - (widthAddition / 2f),0f, (screenUtils.initScreenWidth + widthAddition) / 2f, colHeight / 2f,screenUtils.initScreenWidth + widthAddition,colHeight,1f,1f,180f) } private fun drawTopBarButtons(batch: SpriteBatch) { batch.draw(assets.menuButton,menuButtonPosition.x,menuButtonPosition.y,buttonSize,buttonSize) } // TODO: draw count private fun drawBottomBarButtons(batch: SpriteBatch) { val bonusPosition = Vector2(0f,0f) val columnWidth = Gdx.graphics.width / bonuses.size var counter = 0 for (bonus in bonuses) { counter++ var heightDivider = 4 if (bonuses.size == 3) { if (counter == 2) heightDivider = 2 } if (bonuses.size == 4) { if (counter == 2 || counter == 3) heightDivider = 2 } bonusPosition.set(((columnWidth * counter) - columnWidth / 2) - buttonSize / 2, colHeight / heightDivider) when (bonus.key) { BonusType.HAMMER -> { batch.draw(assets.menuButton,bonusPosition.x,bonusPosition.y,buttonSize,buttonSize) assets.fontScore.draw(batch,bonus.value.toString(),(bonusPosition.x + buttonSize) - buttonSize / 8,bonusPosition.y + buttonSize / 6) } BonusType.MASH -> { batch.draw(assets.menuButton,bonusPosition.x,bonusPosition.y,buttonSize,buttonSize) assets.fontScore.draw(batch,bonus.value.toString(),(bonusPosition.x + buttonSize) - buttonSize / 8,bonusPosition.y + buttonSize / 6) } BonusType.BOMB -> { batch.draw(assets.menuButton,bonusPosition.x,bonusPosition.y,buttonSize,buttonSize) assets.fontScore.draw(batch,bonus.value.toString(),(bonusPosition.x + buttonSize) - buttonSize / 8,bonusPosition.y + buttonSize / 6) } BonusType.COLOR_REMOVE -> { batch.draw(assets.menuButton,bonusPosition.x,bonusPosition.y,buttonSize,buttonSize) assets.fontScore.draw(batch,bonus.value.toString(),(bonusPosition.x + buttonSize) - buttonSize / 8,bonusPosition.y + buttonSize / 6) } } } } private fun drawObjectives(batch: SpriteBatch) { // TODO: implement } private fun drawScore(batch: SpriteBatch) { // TODO: remove hardcode assets.fontScore.draw(batch,"SCORE:",menuButtonPosition.x - 60,menuButtonPosition.y + buttonSize + colHeight / 8) assets.fontScore.draw(batch,gameGrid.score.toInt().toString(),menuButtonPosition.x - 60,menuButtonPosition.y + buttonSize / 2 + colHeight / 8) } private fun drawTopBarMoves(batch: SpriteBatch) { // TODO: use screenUtils, remove hardCode batch.draw(assets.movesCircle,colWidth + 5f,(Gdx.graphics.height.toFloat() - movesCircleRadius * 2) + 5f,(movesCircleRadius * 2) - 10f, (movesCircleRadius * 2) - 10f) assets.fontScore.color = Color.WHITE val fontLayout = GlyphLayout(assets.fontScore,gameGrid.movesLeft.toString()) assets.fontScore.draw(batch,fontLayout,moveCircleCenter.x - (fontLayout.width / 2),moveCircleCenter.y + (fontLayout.height / 2)) } private fun drawProgressArc() { shape.begin(ShapeRenderer.ShapeType.Filled) shape.color = Color.BLACK // TODO: remove hardcode shape.circle(moveCircleCenter.x,moveCircleCenter.y,movesCircleRadius + 5f) shape.color = progressArcColor shape.arc(moveCircleCenter.x,moveCircleCenter.y,movesCircleRadius, 90f,gameGrid.movesLeft * decreasePercent) shape.end() } fun resize(width : Int, height : Int) { } }
13
Kotlin
0
5
3c654ce4744c1e0dab9c8727c25738baabfd304f
6,158
Diamond-Story
MIT License
presenter/src/main/java/com/dannyjung/githubapi/presenter/ui/login/LoginState.kt
danny-jung
461,742,760
false
{"Kotlin": 98644}
package com.dannyjung.githubapi.presenter.ui.login import com.airbnb.mvrx.Async import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Uninitialized import com.dannyjung.githubapi.domain.model.AccessToken data class LoginState( val accessToken: String? = null, val requestAccessTokenAsync: Async<AccessToken> = Uninitialized, val clearAccessTokenAsync: Async<Unit> = Uninitialized ) : MavericksState
0
Kotlin
0
0
91229d48f81389bb3e8c72c231f7e8743fee2cd8
420
GithubApiSample
Apache License 2.0
feature/my/src/main/java/com/hankki/feature/my/mypage/MySideEffect.kt
Team-Hankki
816,081,730
false
{"Kotlin": 587452}
package com.hankki.feature.my.mypage sealed class MySideEffect { data object ShowLogoutSuccess : MySideEffect() data object ShowDeleteWithdrawSuccess : MySideEffect() data class ShowWebView(val type: String) : MySideEffect() }
3
Kotlin
0
43
e83ea4cf5cfd0b23d71da164090c29ba0e253b18
240
hankki-android
Apache License 2.0
client/src/main/kotlin/org/authlab/http/client/ClientResponse.kt
AuthLab
116,606,960
false
{"Gradle": 10, "YAML": 2, "Shell": 6, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 6, "XML": 22, "Kotlin": 107, "Java": 9, "Java Properties": 1, "HTML": 2, "Dockerfile": 1, "Groovy": 7}
/* * MIT License * * Copyright (c) 2018 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.authlab.http.client import org.authlab.http.Headers import org.authlab.http.Response import org.authlab.http.ResponseLine import org.authlab.http.bodies.Body import org.authlab.http.bodies.BodyReader import org.authlab.http.bodies.DelayedBody class ClientResponse<out B : Body> internal constructor(private val internalResponse: Response, private val body: B) { val responseLine: ResponseLine get() = internalResponse.responseLine val headers: Headers get() = internalResponse.headers val statusCode: Int get() = internalResponse.responseLine.statusCode val contentType: String? get() = internalResponse.headers .getHeader("Content-Type")?.getFirst() val contentLength: Int get() = internalResponse.headers .getHeader("Content-Length")?.getFirstAsInt() ?: 0 fun toHar() = internalResponse.toHar() fun getBody(): B = body inline fun <reified B : Body> getBody(bodyReader: BodyReader<B>): B { val body = getBody() return when (body) { is B -> body is DelayedBody -> body.read(bodyReader) else -> convertBody(body, bodyReader) } } }
1
null
1
1
b35f95e4fd220e811db63736a29c82ca3ddfe499
2,430
http
MIT License
src/main/kotlin/ar/edu/unq/arqs1/MercadilloLibreBack/services/LineItemsService.kt
ArqSoft-Unq
406,999,376
false
{"Kotlin": 136681, "Dockerfile": 132}
package ar.edu.unq.arqs1.MercadilloLibreBack.services import ar.edu.unq.arqs1.MercadilloLibreBack.models.LineItem import ar.edu.unq.arqs1.MercadilloLibreBack.models.Order import ar.edu.unq.arqs1.MercadilloLibreBack.models.Product import ar.edu.unq.arqs1.MercadilloLibreBack.repositories.line_item.LineItemRepository import org.springframework.stereotype.Service import java.util.* @Service class LineItemsService(val lineItemRepository: LineItemRepository) { fun addLineItem(lineItem: LineItem): Result<LineItem> { return try { validateOrder(lineItem) validateProduct(lineItem) validateProductStock(lineItem.product, lineItem.quantity) lineItem.price = lineItem.product.price Result.success(lineItemRepository.save(lineItem)) } catch (e:Exception) { Result.failure(e) } } private fun validateProduct(lineItem: LineItem) { if(!lineItem.product.isActive) throw LineItem.ProductDeactivated() } private fun validateOrder(lineItem: LineItem) { if(lineItem.order!!.isCharged()) { throw Order.OrderCharged() } } fun deleteLineItem(lineItem: LineItem): Result<Unit> { return try { validateOrder(lineItem) lineItemRepository.delete(lineItem) Result.success(Unit) } catch (e: Exception) { Result.failure(e) } } fun updateQuantity(lineItem: LineItem, quantity: Int): Result<LineItem> { return try { validateOrder(lineItem) validateProductStock(lineItem.product, quantity) lineItem.quantity = quantity Result.success(lineItemRepository.save(lineItem)) } catch (e: Exception) { Result.failure(e) } } private fun validateProductStock(product: Product, quantity: Int) { if (!product.canSupplyStockFor(quantity)) { throw Product.MissingStock() } } fun findById(lineItemId: Long): Optional<LineItem> { return lineItemRepository.findById(lineItemId) } }
0
Kotlin
0
0
e3ded142d9194166dc1d24050e972f05e16a3daf
2,136
MercadilloLibreBack
MIT License
test/fullstack/src/main/kotlin/application/TestEventHandler.kt
IceCream-QAQ
208,843,258
false
{"Kotlin": 221774, "Java": 4783}
package application import rain.event.annotation.EventListener import rain.event.annotation.SubscribeEvent import rain.job.JobRunExceptionEvent @EventListener class TestEventHandler { @SubscribeEvent fun onJobError(event: JobRunExceptionEvent) { event.error.printStackTrace() } }
9
Kotlin
12
60
c2f92f2d0b942f59773f27208663e24991ca4562
304
Rain
Apache License 2.0
buildSrc/src/main/kotlin/CommonConfig.kt
ktorio
40,136,600
false
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
/* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import internal.* import org.gradle.api.* import org.gradle.kotlin.dsl.* fun Project.configureCommon() { kotlin { sourceSets { commonMain { dependencies { api(libs.kotlinx.coroutines.core) } } commonTest { dependencies { implementation(libs.kotlin.test) } } } } }
156
Kotlin
1051
12,926
f90f2edf11caca28a61dbe9973faae64c17a2842
570
ktor
Apache License 2.0
app/src/main/java/com/example/gwent/RecyclerActivity.kt
HorizonParadox
359,972,956
false
null
package com.example.gwent import android.content.Context import android.content.res.AssetManager import android.os.Bundle import android.view.ContextThemeWrapper import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.selection.* import androidx.recyclerview.widget.LinearLayoutManager import com.example.gwent.chat_test.MainActivity import com.example.gwent.recycler_view.ListAdapter import com.example.gwent.recycler_view.MyItemDetailsLookup import kotlinx.android.synthetic.main.recycler_activity.* import java.io.IOException class RecyclerActivity : AppCompatActivity() { private var imgList: MutableList<String> = mutableListOf() private lateinit var adapter: ListAdapter private lateinit var tracker: SelectionTracker<Long> private lateinit var mActivity: MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.recycler_activity) mActivity = MainActivity() dialogView() txtDescription.text = "Выбранное количество карт: 0" val imgArray = getImage(this) imgArray?.forEach { img -> imgList.add(img) } adapter = ListAdapter(imgList) cards_recycler_view.layoutManager = LinearLayoutManager(this) cards_recycler_view.adapter = adapter setupTracker() adapter.notifyDataSetChanged() } private fun dialogView() { val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AlertDialogCustom)) builder.setTitle(getString(R.string.description)) builder.setPositiveButton(android.R.string.yes) { _, _ -> } builder.show() } private fun setupTracker() { tracker = SelectionTracker.Builder( "mySelection", cards_recycler_view, StableIdKeyProvider(cards_recycler_view), MyItemDetailsLookup(cards_recycler_view), StorageStrategy.createLongStorage() ).withSelectionPredicate( SelectionPredicates.createSelectAnything() ).build() tracker.addObserver( object : SelectionTracker.SelectionObserver<Long>() { override fun onSelectionChanged() { super.onSelectionChanged() val nItems: Int = tracker.selection.size() txtDescription.text = "Выбранное количество карт: $nItems" val listItems = tracker.selection.toList() if (nItems == 22) { val imgList22: ArrayList<String> = ArrayList() listItems.forEach { num -> imgList22.add(imgList[num.toInt()]) } cardDisplay(imgList22) } } }) adapter.tracker = tracker } private fun cardDisplay(selection: ArrayList<String>) { GameActivity.launch(this, selection) this.finish() } @Throws(IOException::class) private fun getImage(context: Context): Array<String>? { val assetManager: AssetManager = context.assets return assetManager.list("sev_cards") } }
0
Kotlin
0
0
065a747d6c43f8738b4f67e25d465c9b79f4e901
3,211
DirectWiFiGame
MIT License
src/test/kotlin/io/github/ivsokol/poe/policy/IPolicySerializerTest.kt
ivsokol
850,045,264
false
{"Kotlin": 1891986}
package io.github.ivsokol.poe.policy import io.github.ivsokol.poe.SemVer import io.github.ivsokol.poe.action.PolicyActionRef import io.github.ivsokol.poe.condition.PolicyConditionDefault import io.github.ivsokol.poe.condition.PolicyConditionRef import io.kotest.assertions.json.shouldEqualJson import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.kotest.matchers.string.shouldStartWith import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class IPolicySerializerTest : DescribeSpec({ val json = Json { serializersModule = policySerializersModule explicitNulls = false encodeDefaults = true } describe("exceptions") { it("bad json") { val given = """{targetEffect": "permit"}""" shouldThrow<IllegalArgumentException> { json.decodeFromString<IPolicy>(given) } .message shouldStartWith "Unexpected JSON token at offset" } it("wrong json") { val given = """false""" shouldThrow<IllegalArgumentException> { json.decodeFromString<IPolicy>(given) } .message shouldStartWith "Not correct JsonElement for IPolicy DeserializationStrategy" } it("bad targetEffect") { val given = """{"targetEffect": "bad"}""" shouldThrow<IllegalArgumentException> { json.decodeFromString<IPolicy>(given) } .message shouldContain "PolicyTargetEffectEnum does not contain element with name 'bad'" } it("no targetEffect field") { val given = """{"left":{"type":"int","value":1},"right":{"type":"int","value":1}}""" shouldThrow<IllegalArgumentException> { json.decodeFromString<IPolicy>(given) } .message shouldBe "No corresponding operation field for IPolicy DeserializationStrategy" } } describe("Policy") { it("should serialize minimal") { val given: IPolicy = Policy( targetEffect = PolicyTargetEffectEnum.DENY, condition = PolicyConditionDefault(true)) val expected = """{"targetEffect": "deny","condition":{"default":true}}""" val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize minimal") { val expected: IPolicy = Policy( targetEffect = PolicyTargetEffectEnum.DENY, condition = PolicyConditionDefault(true)) val given = """{"targetEffect": "deny","condition":{"default":true}}""" val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } it("should serialize full") { val given = Policy( id = "1", version = SemVer(1, 0, 0), description = "desc", labels = listOf("1"), targetEffect = PolicyTargetEffectEnum.DENY, condition = PolicyConditionDefault(true), strictTargetEffect = false, constraint = PolicyConditionRef(id = "2"), actions = listOf(PolicyActionRelationship(action = PolicyActionRef(id = "3"))), lenientConstraints = false, actionExecutionStrategy = ActionExecutionStrategyEnum.STOP_ON_FAILURE, ignoreErrors = false, priority = 100) val expected = """ { "id": "1", "version": "1.0.0", "description": "desc", "labels": [ "1" ], "constraint": { "id": "2", "refType": "PolicyConditionRef" }, "actions": [ { "action": { "id": "3", "refType": "PolicyActionRef" } } ], "lenientConstraints": false, "actionExecutionStrategy": "stopOnFailure", "ignoreErrors": false, "targetEffect": "deny", "condition": { "default": true }, "strictTargetEffect": false, "priority": 100 } """ val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize full") { val expected = Policy( id = "1", version = SemVer(1, 0, 0), description = "desc", labels = listOf("1"), targetEffect = PolicyTargetEffectEnum.DENY, condition = PolicyConditionDefault(true), strictTargetEffect = false, constraint = PolicyConditionRef(id = "2"), actions = listOf(PolicyActionRelationship(action = PolicyActionRef(id = "3"))), lenientConstraints = false, actionExecutionStrategy = ActionExecutionStrategyEnum.STOP_ON_FAILURE, ignoreErrors = false, priority = 100) val given = """ { "id": "1", "version": "1.0.0", "description": "desc", "labels": [ "1" ], "constraint": { "id": "2", "refType": "PolicyConditionRef" }, "actions": [ { "action": { "id": "3", "refType": "PolicyActionRef" } } ], "lenientConstraints": false, "actionExecutionStrategy": "stopOnFailure", "ignoreErrors": false, "targetEffect": "deny", "condition": { "default": true }, "strictTargetEffect": false, "priority": 100 } """ val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } } describe("PolicySet") { it("should serialize minimal") { val given: IPolicy = PolicySet( policyCombinationLogic = PolicyCombinationLogicEnum.DENY_OVERRIDES, policies = listOf(PolicyRelationship(policy = PolicyDefault(PolicyResultEnum.PERMIT)))) val expected = """{"policyCombinationLogic": "denyOverrides", "policies":[{"policy":{"default":"permit","id":"${'$'}permit"}}]}""" val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize minimal") { val expected: IPolicy = PolicySet( policyCombinationLogic = PolicyCombinationLogicEnum.DENY_OVERRIDES, policies = listOf(PolicyRelationship(policy = PolicyDefault(PolicyResultEnum.PERMIT)))) val given = """{"policyCombinationLogic": "denyOverrides", "policies":[{"policy":{"default":"permit","id":"${'$'}permit"}}]}""" val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } it("should serialize full") { val given = PolicySet( id = "1", version = SemVer(1, 0, 0), description = "desc", labels = listOf("1"), policyCombinationLogic = PolicyCombinationLogicEnum.DENY_OVERRIDES, policies = listOf(PolicyRelationship(policy = PolicyDefault(PolicyResultEnum.PERMIT))), runChildActions = false, strictUnlessLogic = true, constraint = PolicyConditionRef(id = "2"), actions = listOf(PolicyActionRelationship(action = PolicyActionRef(id = "3"))), lenientConstraints = false, actionExecutionStrategy = ActionExecutionStrategyEnum.STOP_ON_FAILURE, ignoreErrors = false, priority = 100) val expected = """ { "id": "1", "version": "1.0.0", "description": "desc", "labels": [ "1" ], "constraint": { "id": "2", "refType": "PolicyConditionRef" }, "actions": [ { "action": { "id": "3", "refType": "PolicyActionRef" } } ], "lenientConstraints": false, "actionExecutionStrategy": "stopOnFailure", "ignoreErrors": false, "policyCombinationLogic": "denyOverrides", "policies": [ { "policy": { "default": "permit", "id": "${'$'}permit" } } ], "runChildActions": false, "strictUnlessLogic": true, "priority": 100 } """ .trimIndent() val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize full") { val expected = PolicySet( id = "1", version = SemVer(1, 0, 0), description = "desc", labels = listOf("1"), policyCombinationLogic = PolicyCombinationLogicEnum.DENY_OVERRIDES, policies = listOf(PolicyRelationship(policy = PolicyDefault(PolicyResultEnum.PERMIT))), runChildActions = false, strictUnlessLogic = true, constraint = PolicyConditionRef(id = "2"), actions = listOf(PolicyActionRelationship(action = PolicyActionRef(id = "3"))), lenientConstraints = false, actionExecutionStrategy = ActionExecutionStrategyEnum.STOP_ON_FAILURE, ignoreErrors = false, priority = 100) val given = """ { "id": "1", "version": "1.0.0", "description": "desc", "labels": [ "1" ], "constraint": { "id": "2", "refType": "PolicyConditionRef" }, "actions": [ { "action": { "id": "3", "refType": "PolicyActionRef" } } ], "lenientConstraints": false, "actionExecutionStrategy": "stopOnFailure", "ignoreErrors": false, "policyCombinationLogic": "denyOverrides", "policies": [ { "policy": { "default": "permit", "id": "${'$'}permit" } } ], "runChildActions": false, "strictUnlessLogic": true, "priority": 100 } """ .trimIndent() val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } } describe("PolicyConditionDefault") { it("should serialize minimal") { val given: IPolicy = PolicyDefault(PolicyResultEnum.PERMIT) val expected = """{"default":"permit","id":"${'$'}permit"}""" val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize minimal") { val expected: IPolicy = PolicyDefault(PolicyResultEnum.DENY) val given = """{"default":"deny","id":"${'$'}deny"}""" val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } it("should serialize full") { val given: IPolicy = PolicyDefault( default = PolicyResultEnum.PERMIT, constraint = PolicyConditionDefault(true), actions = listOf(PolicyActionRelationship(action = PolicyActionRef("1"))), actionExecutionStrategy = ActionExecutionStrategyEnum.UNTIL_SUCCESS, lenientConstraints = false, priority = 100) val expected = """{"id":"${'$'}permit","default":"permit","constraint":{"default": true},"actions":[{"action":{"id": "1","refType": "PolicyActionRef"}}],"actionExecutionStrategy":"untilSuccess","lenientConstraints":false,"priority": 100}""" val actual = json.encodeToString(given) actual shouldEqualJson expected } it("should deserialize full") { val expected: IPolicy = PolicyDefault( default = PolicyResultEnum.PERMIT, constraint = PolicyConditionDefault(true), actions = listOf(PolicyActionRelationship(action = PolicyActionRef("1"))), actionExecutionStrategy = ActionExecutionStrategyEnum.UNTIL_SUCCESS, lenientConstraints = false, priority = 100) val given = """{"id":"${'$'}permit","default":"permit","constraint":{"default": true},"actions":[{"action":{"id": "1","refType": "PolicyActionRef"}}],"actionExecutionStrategy":"untilSuccess","lenientConstraints":false,"priority": 100}""" val actual = json.decodeFromString<IPolicy>(given) actual shouldBe expected } } })
0
Kotlin
0
1
e1513c000ced3eafefad6778fc6085df8c4b17ee
12,650
policy-engine
Apache License 2.0
player/playback-engine/src/test/kotlin/com/tidal/sdk/player/playbackengine/mediasource/streamingsession/ExplicitStreamingSessionFactoryTest.kt
tidal-music
806,866,286
false
{"Kotlin": 1628779, "Shell": 9249}
package com.tidal.sdk.player.playbackengine.mediasource.streamingsession import com.tidal.sdk.player.common.Configuration import com.tidal.sdk.player.common.UUIDWrapper internal class ExplicitStreamingSessionFactoryTest : StreamingSessionFactoryTest() { override val streamingSessionFactoryF = { uuidWrapper: UUIDWrapper, versionedCdmCalculator: VersionedCdm.Calculator, configuration: Configuration, -> StreamingSession.Factory.Explicit(uuidWrapper, versionedCdmCalculator, configuration) } }
33
Kotlin
0
20
306d8a17e5b29722f1c3aa22a87a759cd9403d83
589
tidal-sdk-android
Apache License 2.0
catowserAndroid/app/src/main/java/org/cotton/app/CottonActivity.kt
kyzmitch
90,989,082
false
{"Swift": 852534, "Kotlin": 83129, "JavaScript": 12500, "Ruby": 8534, "Makefile": 8274, "Objective-C": 4975, "HTML": 3562}
package org.cotton.app import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity abstract class CottonActivity : ComponentActivity() { override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) handleIntent(intent) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) handleIntent(intent) } open fun handleIntent(intent: Intent) {} }
17
Swift
0
5
f0e3a91c6bb34a5a7117f664be556eb4cdf654d3
485
Cotton
MIT No Attribution
Projects/Case Studies/ShoppingList/app/src/main/java/com/androiddevs/shoppinglisttestingyt/repositories/ShoppingRepository.kt
devrath
367,809,239
false
{"Kotlin": 156362, "Java": 9710}
package com.androiddevs.shoppinglisttestingyt.repositories import androidx.lifecycle.LiveData import com.androiddevs.shoppinglisttestingyt.data.local.ShoppingItem import com.androiddevs.shoppinglisttestingyt.data.remote.responses.ImageResponse import com.androiddevs.shoppinglisttestingyt.other.Resource import retrofit2.Response interface ShoppingRepository { suspend fun insertShoppingItem(shoppingItem: ShoppingItem) suspend fun deleteShoppingItem(shoppingItem: ShoppingItem) fun observeAllShoppingItems(): LiveData<List<ShoppingItem>> fun observeTotalPrice(): LiveData<Float> suspend fun searchForImage(imageQuery: String): Resource<ImageResponse> }
0
Kotlin
0
0
f8300fe58b759be7203069ec8500d067ec87977b
680
automatic-octo-fiesta
Apache License 2.0
day10/src/main/kotlin/com/nohex/aoc/day10/Solution.kt
mnohe
433,396,563
false
{"Kotlin": 105740}
package com.nohex.aoc.day10 import com.nohex.aoc.PuzzleInput fun main() { val input = getInput("input.txt") val analyser = ChunkAnalyser(input) println("Day 10, part 1: ${analyser.corruptedScore}") println("Day 10, part 2: ${analyser.middleScore}") } fun getInput(path: String) = PuzzleInput(path).asSequence()
0
Kotlin
0
0
4d7363c00252b5668c7e3002bb5d75145af91c23
335
advent_of_code_2021
MIT License
android/android-core/src/main/java/cn/yizems/util/ktx/android/anim/AnimationEx.kt
yizems
429,726,361
false
null
package cn.yizems.util.ktx.android.anim import android.view.View import android.view.animation.AnimationUtils import androidx.annotation.AnimRes /** * 应用动画 * @param anim 动画资源id */ fun View.startAnimationEx(@AnimRes anim: Int) { this.startAnimation(AnimationUtils.loadAnimation(context, anim)) }
0
Kotlin
1
31
ad9b289f07e8cc54a91a420c3b74195db93695c9
304
KUtil
MIT License
src/main/kotlin/com/devcharly/kotlin/ant/util/firstmatchmapper.kt
DevCharly
61,804,395
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.devcharly.kotlin.ant import org.apache.tools.ant.util.FileNameMapper import org.apache.tools.ant.util.FirstMatchMapper /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IFirstMatchMapperNested { fun firstmatchmapper( from: String? = null, to: String? = null, nested: (KFirstMatchMapper.() -> Unit)? = null) { _addFirstMatchMapper(FirstMatchMapper().apply { _init(from, to, nested) }) } fun _addFirstMatchMapper(value: FirstMatchMapper) } fun IFileNameMapperNested.firstmatchmapper( from: String? = null, to: String? = null, nested: (KFirstMatchMapper.() -> Unit)? = null) { _addFileNameMapper(FirstMatchMapper().apply { _init(from, to, nested) }) } fun FirstMatchMapper._init( from: String?, to: String?, nested: (KFirstMatchMapper.() -> Unit)?) { if (from != null) setFrom(from) if (to != null) setTo(to) if (nested != null) nested(KFirstMatchMapper(this)) } class KFirstMatchMapper(val component: FirstMatchMapper) : IFileNameMapperNested { override fun _addFileNameMapper(value: FileNameMapper) = component.addConfigured(value) }
0
Kotlin
2
6
b73219cd1b9b57972ed42048c80c6618474f4395
1,839
kotlin-ant-dsl
Apache License 2.0
src/main/kotlin/no/risc/exception/exceptions/SopsConfigFetchException.kt
kartverket
738,125,421
false
{"Kotlin": 89137, "Dockerfile": 493}
package no.risc.exception.exceptions data class SopsConfigFetchException( override val message: String, val riScId: String, val responseMessage: String, ) : Exception()
14
Kotlin
1
2
7e1d798d194d0211733224677cca7087052106b2
182
backstage-plugin-risk-scorecard-backend
MIT License
python/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibOverridingTypeProvider.kt
saifullah007
94,907,835
true
{"Text": 2942, "XML": 4439, "Ant Build System": 20, "Shell": 41, "Markdown": 13, "Ignore List": 26, "Git Attributes": 6, "Batchfile": 29, "Kotlin": 1201, "Java": 54800, "Java Properties": 89, "HTML": 2580, "Groovy": 2396, "INI": 188, "JavaScript": 186, "JFlex": 23, "XSLT": 109, "CSS": 73, "desktop": 2, "Python": 9663, "SVG": 189, "C#": 32, "Diff": 115, "Roff": 73, "Roff Manpage": 4, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 256, "CoffeeScript": 3, "JSON with Comments": 1, "Perl": 4, "J": 18, "Protocol Buffer": 2, "JAR Manifest": 8, "fish": 1, "Gradle": 41, "E-mail": 18, "YAML": 95, "Maven POM": 1, "Checksums": 58, "Java Server Pages": 24, "C": 40, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "Scala": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "Microsoft Visual Studio Solution": 8, "C++": 18, "Objective-C": 9, "CMake": 3, "OpenStep Property List": 2, "VBScript": 1, "NSIS": 8, "EditorConfig": 1, "Thrift": 2, "Cython": 9, "TeX": 7, "reStructuredText": 41, "Gettext Catalog": 125, "Jupyter Notebook": 5, "Regular Expression": 3}
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.codeInsight.stdlib import com.intellij.psi.PsiElement import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.impl.PyOverridingTypeProvider import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.PyTypeProviderBase import com.jetbrains.python.psi.types.TypeEvalContext class PyStdlibOverridingTypeProvider : PyTypeProviderBase(), PyOverridingTypeProvider { override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyType? { return if (isTypingNamedTupleInit(referenceTarget)) PyStdlibTypeProvider.getNamedTupleType(referenceTarget, context, anchor) else null } private fun isTypingNamedTupleInit(referenceTarget: PsiElement): Boolean { return referenceTarget is PyFunction && PyNames.INIT == referenceTarget.name && PyTypingTypeProvider.NAMEDTUPLE == referenceTarget.containingClass?.qualifiedName } }
0
Java
0
1
6db8e97198de8abee8801356a1fa197e4a302448
1,673
intellij-community
Apache License 2.0
fitfriend-api/src/main/kotlin/com/health/fitfriend/controller/MeditationController.kt
this-Aditya
654,565,739
false
null
package com.health.fitfriend.controller import com.health.fitfriend.model.Meditation import com.health.fitfriend.service.MeditationService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import kotlin.IllegalArgumentException @RestController @RequestMapping("/yoga/meditations") class MeditationController(private val service: MeditationService) { @ExceptionHandler(NoSuchElementException::class) fun handleNotFound(e: NoSuchElementException): ResponseEntity<String> = ResponseEntity(e.message, HttpStatus.NOT_FOUND) @ExceptionHandler(IllegalArgumentException::class) fun handleBadRequest(e: IllegalArgumentException): ResponseEntity<String> = ResponseEntity(e.message, HttpStatus.BAD_REQUEST) @GetMapping fun getMeditations() = service.getMeditations() @GetMapping("id/{id}") fun getMeditationById(@PathVariable id: Int) = service.getMeditationById(id) @GetMapping("/name/{name}") fun getMediatationByName(@PathVariable name:String) = service.getMeditationByName(name) @PostMapping @ResponseStatus(HttpStatus.CREATED) fun addMeditation(@RequestBody meditation: Meditation): Meditation = service.addMeditation(meditation) @PatchMapping fun updateMeditation(@RequestBody meditation: Meditation): Meditation = service.updateMeditation(meditation) @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun deleteMeditation(@PathVariable id: Int): Unit = service.deleteMeditation(id) }
0
Kotlin
0
0
5580c516ec686a43cd586f22bad204121a31e582
2,137
FitFriend
Apache License 2.0
Sleek v0.2 b8.0.1 BETA/src/main/java/today/sleek/base/scripting/ScriptManager.kt
cipherwithadot
492,177,269
false
{"Markdown": 1, "Text": 1, "Shell": 2, "HTML": 1, "Maven POM": 2, "Ignore List": 2, "Batchfile": 2, "INI": 2, "JavaScript": 3, "JSON": 4009, "Java": 4052, "Kotlin": 50, "JAR Manifest": 4, "GLSL": 78, "Java Properties": 74}
package today.sleek.base.scripting import net.minecraft.client.Minecraft import net.minecraft.util.EnumChatFormatting import net.minecraft.util.EnumFacing import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.exception.ExceptionUtils import today.sleek.Sleek import today.sleek.base.scripting.base.lib.* import today.sleek.base.scripting.base.ScriptFile import today.sleek.client.utils.chat.ChatUtil import java.io.File import java.io.FileReader import javax.script.ScriptEngine import javax.script.ScriptEngineManager class ScriptManager(val dir: File) { val scripts = arrayListOf<ScriptFile>() val factory = ScriptEngineManager() var engine: ScriptEngine = factory.getEngineByName("Nashorn") fun unloadScripts() { scripts.clear() Sleek.instance().moduleManager.unloadScripts() } fun loadScripts() { for (file in dir.listFiles()!!) { println(file.name) if (FilenameUtils.getExtension(file.name) == "js") { scripts.add(ScriptFile(file, FilenameUtils.removeExtension(file.name).replace(" ", ""))) } } } fun loadScript(name: String) { for (script in scripts) { if (script.name.equals(name, ignoreCase = true)) { try { engine.eval(FileReader(script.file)) } catch (nigga: Exception) { val stacktrace: String = ExceptionUtils.getStackTrace(nigga) ChatUtil.log(EnumChatFormatting.RED.toString() + stacktrace) nigga.printStackTrace() } } } } init { if (!dir.exists()) { dir.mkdirs() } engine.put("script", ScriptAPI) engine.put("chat", Chat) engine.put("player", Player) engine.put("packets", Packets) engine.put("mc", Minecraft.getMinecraft()) engine.put("stopwatch", Stopwatch) loadScripts() } }
1
null
1
1
4a9045dd90f56d1e4c08cfa56f469859b58f5a48
2,002
leaked-sleek-builds-fork
The Unlicense
app/src/main/java/com/d34th/nullpointer/baseconvert/models/SubsStringFormatBase.kt
Hcnc100
560,188,186
false
{"Kotlin": 54390}
package com.d34th.nullpointer.baseconvert.models data class SubsStringFormatBase( val hasPartFractional: Boolean, val signed: String, val partInteger: String, val partFractional: String )
0
Kotlin
0
0
49f3cef9503e5a31bf48f07eeddd7a3449f6ba9a
205
BaseConvert
MIT License
src/main/kotlin/com/gitlab/daring/image/command/structure/FindContoursCommand.kt
daring2
98,345,175
false
null
package com.gitlab.daring.image.command.structure import com.gitlab.daring.image.command.CommandEnv import com.gitlab.daring.image.command.KBaseCommand import com.gitlab.daring.image.opencv.toList import org.bytedeco.javacpp.opencv_core.MatVector import org.bytedeco.javacpp.opencv_imgproc.findContours internal class FindContoursCommand(params: Array<String>) : KBaseCommand(params) { val mode = enumParam(Mode.List) val method = enumParam(ApproxMethod.None) override fun execute(env: CommandEnv) { val mv = MatVector() findContours(env.mat.clone(), mv, mode.vi, method.vi + 1) env.contours = mv.toList().map(::Contour) } enum class Mode { External, List, CComp, Tree, FloodFill } enum class ApproxMethod { None, Simple, TC89_L1, TC89_KCOS } }
0
Kotlin
0
0
e46de09cbd129bd99ee8db1adee1741a10c773af
824
image-sandbox
Apache License 2.0
src/main/resources/archetype-resources/frontend/src/main/kotlin/__frontendAppName__/reducer/__frontendAppNameUpperCamelCase__Reducer.kt
linked-planet
194,834,047
false
null
package ${frontendAppName}.reducer import ${frontendAppName}.app.${frontendAppNameUpperCamelCase}Application import ${frontendAppName}.app.${frontendAppNameUpperCamelCase}Application.Companion.appStore import redux.RAction // ------------------------------------------------------------------------------------------ // ACTIONS // ------------------------------------------------------------------------------------------ class SetScreenAction(val screen: ${frontendAppNameUpperCamelCase}Application.Screen) : RAction // ------------------------------------------------------------------------------------------ // REDUCER // ------------------------------------------------------------------------------------------ fun screen( state: ${frontendAppNameUpperCamelCase}Application.Screen = ${frontendAppNameUpperCamelCase}Application.Screen.Loading, action: RAction ): ${frontendAppNameUpperCamelCase}Application.Screen = when (action) { is SetScreenAction -> action.screen else -> state } // ------------------------------------------------------------------------------------------ // HANDLER // ------------------------------------------------------------------------------------------ object ${frontendAppNameUpperCamelCase}Handler { fun setScreen(screen: ${frontendAppNameUpperCamelCase}Application.Screen) { appStore.dispatch(SetScreenAction(screen)) } }
5
Kotlin
2
6
c7ccc4409fb92f02cdcdec74a91e9a7b416a7ad2
1,414
atlassian-plugin-kotlin
Creative Commons Zero v1.0 Universal
src/main/kotlin/xyz/flaflo/snes/rom/header/capacity/SnesSaveRamSize.kt
Flaflo
326,484,584
false
{"Kotlin": 21166}
@file:Suppress("EnumEntryName", "EnumEntryName", "EnumEntryName", "EnumEntryName", "EnumEntryName", "unused", "unused", "unused", "unused" ) package xyz.flaflo.snes.rom.header.capacity /** * Enumerates the possible save ram sizes that can be determined by the rom header * * @param flag the flag that is used to store the save ram size into the header */ enum class SnesSaveRamSize(val flag: Int) { Unknown(-1), None(0x00), `16Kbit`(0x01), `32Kbit`(0x02), `64Kbit`(0x03), `128Kbit`(0x04), `256Kbit`(0x05); companion object { /** * @param flag the save ram size flag * @return the save ram size according to the provided flag */ fun fromFlag(flag: Int): SnesSaveRamSize { return values().firstOrNull { it.flag == flag } ?: Unknown } } }
0
Kotlin
0
4
58c4c42635d3913a8a3182b77dc0169ca10f1417
845
KSNES
MIT License
android/src/main/kotlin/com/sayx/hm_cloud/widget/EditRouletteKey.kt
Rambo0422
584,657,563
false
{"Kotlin": 511975, "Objective-C": 417868, "C++": 23762, "CMake": 19412, "Dart": 8471, "HTML": 4798, "C": 3793, "Swift": 1581, "Java": 1522, "Ruby": 1406}
package com.sayx.hm_cloud.widget import android.animation.Animator import android.animation.ObjectAnimator import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.view.animation.AccelerateInterpolator import android.widget.FrameLayout import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.get import androidx.databinding.DataBindingUtil import com.blankj.utilcode.util.LogUtils import com.blankj.utilcode.util.SizeUtils import com.blankj.utilcode.util.ToastUtils import com.sayx.hm_cloud.R import com.sayx.hm_cloud.model.KeyInfo import com.sayx.hm_cloud.callback.AddKeyListener import com.sayx.hm_cloud.callback.AnimatorListenerImp import com.sayx.hm_cloud.callback.HideListener import com.sayx.hm_cloud.constants.ControllerStatus import com.sayx.hm_cloud.constants.KeyType import com.sayx.hm_cloud.constants.controllerStatus import com.sayx.hm_cloud.databinding.ViewEditRouletteKeyBinding import com.sayx.hm_cloud.utils.AppSizeUtils import java.util.UUID class EditRouletteKey @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : ConstraintLayout(context, attrs, defStyleAttr) { private var dataBinding: ViewEditRouletteKeyBinding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.view_edit_roulette_key, this, true ) private var keyList: HashMap<Int, KeyInfo?> = hashMapOf() private var full = false var isShow = false var onHideListener: HideListener? = null var addKeyListener: AddKeyListener? = null var keyInfo: KeyInfo? = null var tempList : List<KeyInfo>? = null init { initView() visibility = INVISIBLE } private fun initView() { dataBinding.ivBack.setOnClickListener { val newData: MutableList<KeyInfo> = mutableListOf() keyList.keys.forEach { val keyInfo = keyList[it] if (keyInfo != null) { newData.add(keyInfo) } } if (keyInfo != null) { val oldData = tempList val addList = newData.filter { info -> info !in (oldData ?: listOf()) } val removeList = oldData?.filter { info -> info !in newData } // rou移除的数据会加回列表 addKeyListener?.rouRemoveData(addList) // rou添加的数据会从列表移除 addKeyListener?.rouAddData(removeList) keyInfo!!.updateRouList(oldData ?: listOf()) addKeyListener?.onUpdateKey() } else { newData.forEach { info -> addKeyListener?.onKeyRemove(info) } } hideLayout() } dataBinding.btnSaveEdit.setOnClickListener { saveKey() } // 初始化添加按键 for (index in 0..7) { val editKeyView = EditKeyView(context) keyList[index] = null editKeyView.setOnClickListener { val data = editKeyView.getData() if (data != null) { keyList[index] = null editKeyView.setData(null) full = false addKeyListener?.onKeyRemove(data) if (keyInfo != null) { keyInfo?.updateRouList(keyList.filter { item -> item.value != null }.map { item -> item.value!! }.toList()) keyInfo?.listChange = true addKeyListener?.onUpdateKey() } } } val layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) when (index) { 0 -> { layoutParams.marginEnd = SizeUtils.dp2px(4.75f) } 7 -> { layoutParams.marginStart = SizeUtils.dp2px(4.75f) } else -> { layoutParams.marginEnd = SizeUtils.dp2px(4.75f) layoutParams.marginStart = SizeUtils.dp2px(4.75f) } } dataBinding.layoutKey.addView(editKeyView, layoutParams) } // 编辑菜单隐藏/显示 dataBinding.btnEditFold.setOnClickListener { val selected = !dataBinding.btnEditFold.isSelected dataBinding.btnEditFold.isSelected = selected if (selected) { foldMenu() } else { unfoldMenu() } } } override fun onAttachedToWindow() { super.onAttachedToWindow() post { showBoard() } } fun showBoard() { isShow = true val animator = ObjectAnimator.ofFloat( dataBinding.root, "translationY", -dataBinding.root.height.toFloat(), 0.0f ) animator.duration = 500L animator.interpolator = AccelerateInterpolator() animator.addListener(object : AnimatorListenerImp() { override fun onAnimationStart(animation: Animator) { visibility = VISIBLE controllerStatus = ControllerStatus.Roulette } }) animator.start() } private fun hideLayout() { isShow = false val animator = ObjectAnimator.ofFloat( dataBinding.root, "translationY", 0.0f, -dataBinding.root.height.toFloat() ) animator.duration = 500L animator.interpolator = AccelerateInterpolator() animator.addListener(object : AnimatorListenerImp() { override fun onAnimationEnd(animation: Animator) { clear() onHideListener?.onHide() } }) animator.start() } private fun unfoldMenu() { val animator = ObjectAnimator.ofFloat( dataBinding.root, "translationY", -dataBinding.layoutBoard.height.toFloat(), 0.0f ) animator.duration = 500L animator.interpolator = AccelerateInterpolator() animator.start() } private fun foldMenu() { val animator = ObjectAnimator.ofFloat( dataBinding.root, "translationY", 0.0f, -dataBinding.layoutBoard.height.toFloat() ) animator.duration = 500L animator.interpolator = AccelerateInterpolator() animator.start() } fun addKey(keyInfo: KeyInfo) { if (full) { return } LogUtils.d("addKey:$keyInfo, keyList:$keyList") addKeyListener?.onKeyAdd(keyInfo) keyList.keys.forEach { if (keyList[it] == null) { keyList[it] = keyInfo val view = dataBinding.layoutKey[it] if (view is EditKeyView) { view.setData(keyInfo) if (it == dataBinding.layoutKey.childCount - 1) { full = true } } if ([email protected] != null) { [email protected]?.updateRouList(keyList.filter { item -> item.value != null }.map { item -> item.value!! }.toList() ) [email protected]?.listChange = true addKeyListener?.onUpdateKey() } return } } } private fun clear() { for (index in 0..<dataBinding.layoutKey.childCount) { val editKeyView = dataBinding.layoutKey[index] as EditKeyView keyList[index] = null editKeyView.setData(null) } full = false } private fun saveKey() { LogUtils.d("saveKey:$keyList") val newData: MutableList<KeyInfo> = mutableListOf() keyList.keys.forEach { val keyInfo = keyList[it] if (keyInfo != null) { newData.add(keyInfo) } } LogUtils.d("keyInfoList:$newData") if (newData.size < 4) { ToastUtils.showLong(R.string.save_at_least) return } if (keyInfo != null) { val oldData = keyInfo!!.rouArr val addList = oldData?.filter { info -> info !in newData } val removeList = newData.filter { info -> info !in (oldData ?: listOf()) } addKeyListener?.rouRemoveData(addList) addKeyListener?.rouAddData(removeList) keyInfo!!.updateRouList(newData) addKeyListener?.onUpdateKey() } else { addKeyListener?.onAddKey( KeyInfo( UUID.randomUUID(), AppSizeUtils.DESIGN_WIDTH / 2 - 45, AppSizeUtils.DESIGN_HEIGHT / 2 - 45, 144, 50, "轮盘", 0, KeyType.KEY_ROULETTE, 70, 0, 0, 144, rouArr = newData ) ) } hideLayout() } fun setRouletteKeyInfo(keyInfo: KeyInfo?) { this.keyInfo = keyInfo keyInfo?.let { val keyInfoList = it.rouArr tempList = keyInfoList if (!keyInfoList.isNullOrEmpty()) { for (index in keyInfoList.indices) { val info = keyInfoList[index] keyList[index] = info val view = dataBinding.layoutKey[index] if (view is EditKeyView) { view.setData(info) } } full = keyInfoList.size == 8 } } } }
0
Kotlin
0
0
4e7948674b303da093579c19fe6450355565020d
10,218
hm_cloud_flutter
MIT License
src/main/java/com/temelyan/pomoapp/util/UserUtil.kt
temaEmelyan
108,548,342
false
null
package com.temelyan.pomoapp.util import com.temelyan.pomoapp.model.User import com.temelyan.pomoapp.to.UserTo import org.springframework.security.crypto.password.PasswordEncoder object UserUtil { fun asTo(user: User): UserTo { return UserTo(user.getId(), user.email!!, user.password!!) } fun updateFromTo(user: User, userTo: UserTo): User { user.password = userTo.password return user } fun createNewFromTo(newUser: UserTo): User { return User(null, newUser.email!!.toLowerCase(), newUser.password!!) } fun prepareToSave(user: User, passwordEncoder: PasswordEncoder): User { user.password = PasswordUtil.encode(user.password!!, passwordEncoder) user.email = user.email!!.toLowerCase() return user } }
0
Kotlin
0
2
c9ced11ceecffbb9971d6f42adb855f69eb14d64
795
pomodoreApp
MIT License
fabrikk/src/main/kotlin/no/nav/helse/spekemat/fabrikk/Pølsefabrikk.kt
navikt
746,630,001
false
{"Kotlin": 92917, "PLpgSQL": 2010, "Dockerfile": 168}
package no.nav.helse.spekemat.fabrikk import java.util.* class Pølsefabrikk private constructor( private val pakken: MutableList<Pølserad> ) { constructor() : this(mutableListOf()) companion object { fun gjenopprett(rader: List<PølseradDto>) = Pølsefabrikk(rader.map { Pølserad.fraDto(it) }.toMutableList()) } fun nyPølse(pølse: Pølse) { if (håndtertFør(pølse)) return if (skalLageNyrad(pølse)) return lagNyRad(pølse) pakken[0] = pakken[0].nyPølse(pølse) } private fun håndtertFør(pølse: Pølse) = pakken.any { rad -> rad.pølser.any { it.generasjonId == pølse.generasjonId } } fun oppdaterPølse(vedtaksperiodeId: UUID, generasjonId: UUID, status: Pølsestatus): PølseDto { pakken[0] = pakken[0].oppdaterPølse(vedtaksperiodeId, generasjonId, status) return pakken[0].pølser.single { it.vedtaksperiodeId == vedtaksperiodeId }.dto() } private fun skalLageNyrad(pølse: Pølse) = pakken.isEmpty() || pakken[0].skalLageNyRad(pølse) private fun lagNyRad(pølse: Pølse) { if (pakken.isEmpty()) { pakken.add(Pølserad(listOf(pølse), pølse.kilde)) return } val pølserad = pakken[0].nyPølserad(pølse) pakken[0] = pakken[0].fjernPølserTilBehandling() pakken.add(0, pølserad) } fun pakke() = pakken.map { it.dto() } }
0
Kotlin
0
0
2653c7043a7957f0253e2cc7bdd2b78cd9cf7637
1,421
spekemat
MIT License
data/src/main/java/com/mreigosa/marvelapp/data/mapper/MarvelCharacterMapper.kt
mreigosa
420,424,467
false
null
package com.mreigosa.marvelapp.data.mapper import com.mreigosa.marvelapp.data.model.MarvelCharacterEntity import com.mreigosa.marvelapp.domain.model.MarvelCharacter object MarvelCharacterMapper { fun mapFromEntity(dataEntity: MarvelCharacterEntity): MarvelCharacter = with(dataEntity){ return MarvelCharacter(id, name, description, image) } }
0
Kotlin
0
0
cd5dd93bddcaf53c9f40c6da798c7c1be77cfe83
377
marvel-app-kotlin
MIT License
ios/src/main/kotlin/data/VotesManager.kt
monkeyer
109,773,132
true
{"Kotlin": 164097, "Objective-C": 159408, "CMake": 11965, "CSS": 5843, "JavaScript": 1694, "Ruby": 373, "HTML": 264}
import libs.* import kotlinx.cinterop.* import platform.Foundation.* import platform.CoreData.* class VotesManager { companion object { val EARLY_SUBMITTION_ERROR = NSError("VotesManager", code = 1, userInfo = null) val LATE_SUBMITTION_ERROR = NSError("VotesManager", code = 2, userInfo = null) } fun getRating(session: KSession): KSessionRating? { val moc = appDelegate.managedObjectContext val request = NSFetchRequest(entityName = "KVote") request.fetchLimit = 1 request.predicate = NSPredicate.predicateWithFormat( "sessionId == %@", argumentArray = nsArrayOf(session.id!!.toNSString())) return attempt(null) { moc.executeFetchRequest(request).firstObject?.uncheckedCast<KVote>() }?.sessionRating } fun setRating( session: KSession, rating: KSessionRating, errorHandler: (NSError) -> Unit, onComplete: (KSessionRating?) -> Unit ) { val currentRating = getRating(session) val service = KonfService(errorHandler) val newRating = if (currentRating == rating) null else rating log("rating: $rating, currentRating = $currentRating, newRating = $newRating") val completionHandler: (KonfService.VoteActionResult) -> Unit = handler@ { response -> assert(NSThread.isMainThread) when (response) { KonfService.VoteActionResult.TOO_EARLY -> errorHandler(EARLY_SUBMITTION_ERROR) KonfService.VoteActionResult.TOO_LATE -> errorHandler(LATE_SUBMITTION_ERROR) else -> attempt(errorHandler) { setLocalRating(session, rating = newRating) onComplete(newRating) } } } val uuid = appDelegate.userUuid if (newRating != null) { service.addVote(session, rating, uuid, onComplete = completionHandler) } else { service.deleteVote(session, uuid, onComplete = completionHandler) } } private fun setLocalRating(session: KSession, rating: KSessionRating?) { val moc = appDelegate.managedObjectContext // Delete old rating if exists val request = NSFetchRequest(entityName = "KVote") request.predicate = NSPredicate.predicateWithFormat("sessionId == %@", argumentArray = nsArrayOf(session.id!!.toNSString())) val votes: NSArray = moc.executeFetchRequest(request) votes.toList<KVote>().forEach { moc.deleteObject(it) } if (rating != null) { KVote(moc.entityDescription("KVote"), insertIntoManagedObjectContext = moc).apply { sessionId = session.id setRating(rating.rawValue) } } moc.save() } }
0
Kotlin
0
0
f137ed5c1dd5daaaa444fee0b1b2958476dd9976
2,828
kotlinconf-app
Apache License 2.0
plugin/src/main/kotlin/ru/astrainteractive/aspekt/command/CommandManager.kt
Astra-Interactive
588,890,842
false
{"Kotlin": 326561}
package ru.astrainteractive.aspekt.command import ru.astrainteractive.aspekt.command.di.CommandsDependencies class CommandManager( module: CommandsDependencies, ) : CommandsDependencies by module { init { reload() sit() entities() atemFrameTabCompleter() atemFrame() maxOnline() tellChat() rtp() rtpBypassed() } }
1
Kotlin
0
0
a742fee3843c3b60f4103c50e48228a98e937261
400
AspeKt
MIT License
backend/src/commonMain/kotlin/models/Token.kt
amasotti
694,508,899
false
{"Kotlin": 67429, "TypeScript": 9760, "JavaScript": 6362, "CSS": 1737, "HTML": 766, "Shell": 219}
package models import extensions.getConlluField typealias FeatureExtractor = (String) -> Map<String, String>? const val TOKEN_DELIMITER = "\t" data class Token( val id: Int, val form: String, val lemma: String, val upos: String, val xpos: String, val feats: Map<String, String>?, val head: Int, val deprel: String, val deps: String?, val misc: Map<String,String>? ) { companion object { /** * Create a token from a CoNLL-U line * * @param line The CoNLL-U line as a string * @param extractFeatures A function to extract features from a string building a map * @param handleHeadRelation A function to handle the head relation * @param debug A boolean to enable debugging * * @return A token instance * */ fun fromString( line: String, extractFeatures: FeatureExtractor, handleHeadRelation: (String) -> Int, debug: Boolean = false ): Token { val fields = line.split(TOKEN_DELIMITER) if (debug) debugLog(fields, extractFeatures, handleHeadRelation) validate(line, fields) return Token( id = fields.getConlluField(ConlluFieldsEnum.ID) { it.toInt() }, form = fields.getConlluField(ConlluFieldsEnum.FORM), lemma = fields.getConlluField(ConlluFieldsEnum.LEMMA), upos = fields.getConlluField(ConlluFieldsEnum.UPOS), xpos = fields.getConlluField(ConlluFieldsEnum.XPOS), feats = fields.getConlluField(ConlluFieldsEnum.FEATS) { extractFeatures(it) }, head = fields.getConlluField(ConlluFieldsEnum.HEAD) { handleHeadRelation(it) }, deprel = fields.getConlluField(ConlluFieldsEnum.DEPREL), deps = fields.getConlluField(ConlluFieldsEnum.DEPS), misc = fields.getConlluField(ConlluFieldsEnum.MISC) { extractFeatures(it) } ) } private fun validate(line: String, fields: List<String>) { require(fields.size == ConlluFieldsEnum.entries.size) { "Invalid CoNLL-U line: $line" } } /** * Debugging function to print out the fields of a token * * @param fields The fields of a token * @param extractFeatures A function to extract features from a string building a map * @param handleHeadRelation A function to handle the head relation * * @return Unit */ private fun debugLog( fields: List<String>, extractFeatures: FeatureExtractor, handleHeadRelation: (String) -> Int) { println("FieldSize: " + fields.size + "\n") println("ID: " + fields.getConlluField(ConlluFieldsEnum.ID) + "\n") println("Form: " + fields.getConlluField(ConlluFieldsEnum.FORM) + "\n") println("Lemma: " + fields.getConlluField(ConlluFieldsEnum.LEMMA) + "\n") println("UPOS: " + fields.getConlluField(ConlluFieldsEnum.UPOS) + "\n") println("XPOS: " + fields.getConlluField(ConlluFieldsEnum.XPOS) + "\n") println("Feats: " + fields.getConlluField(ConlluFieldsEnum.FEATS) { extractFeatures(it) } + "\n") println("Head: " + fields.getConlluField(ConlluFieldsEnum.HEAD) { handleHeadRelation(it) } + "\n") println("Deprel: " + fields.getConlluField(ConlluFieldsEnum.DEPREL) + "\n") println("Deps: " + fields.getConlluField(ConlluFieldsEnum.DEPS) + "\n") println("Misc: " + fields.getConlluField(ConlluFieldsEnum.MISC) { extractFeatures(it) } + "\n") } } }
0
Kotlin
0
0
bb092b7af804940e7115243abb0a0c69c3356d61
3,776
konllu-viewer
MIT License
app/src/main/java/com/chenfd/alphamovie/AlphaMovieView.kt
chenfd99
201,435,420
false
null
package com.chenfd.alphamovie import android.content.Context import android.graphics.SurfaceTexture import android.media.MediaPlayer import android.util.AttributeSet import android.util.Log import android.view.Surface import android.view.TextureView import java.io.File /** * * Created by chen on 2019/8/9 * Email: <EMAIL> */ class AlphaMovieView : TextureView, TextureView.SurfaceTextureListener { private val TAG = this::class.java.simpleName private var zipFile: File? = null private var mMediaPlayer: MediaPlayer constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { surfaceTextureListener = this alpha = 0.5f mMediaPlayer = MediaPlayer() } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) { } override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) { } override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean { try { if (mMediaPlayer.isPlaying) mMediaPlayer.stop() mMediaPlayer.release() } catch (e: Exception) { } return true } override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) { try { if (surface != null) mMediaPlayer.setSurface(Surface(surface)) } catch (e: Exception) { } } fun onResume() { try { if (zipFile?.exists() == true) mMediaPlayer.start() } catch (e: Exception) { } } fun onPause() { try { mMediaPlayer.pause() } catch (e: Exception) { } } fun stopPlayEffect() { try { mMediaPlayer.stop() } catch (e: Exception) { } } fun startPlay(videoUrl: String) { try { mMediaPlayer.setDataSource(videoUrl) mMediaPlayer.setOnPreparedListener { mMediaPlayer.start() } mMediaPlayer.setOnCompletionListener { it.start() } mMediaPlayer.setOnErrorListener { mp, what, extra -> false } mMediaPlayer.prepare() mMediaPlayer.start() } catch (e: Exception) { Log.e(TAG, e.message ?: "") } } }
0
Kotlin
1
1
02f691b26da46f3a8a6a93d2b63a0a46e46334cc
2,566
AlphaMovie
MIT License
app/src/main/java/cat/app/bicleaner/hook/handler/ModuleUtilsHooker.kt
Tile-X
848,343,766
false
{"Kotlin": 70528}
package cat.app.bicleaner.hook.handler import cat.app.bicleaner.BuildConfig import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedHelpers class ModuleUtilsHooker: HookHandler { private val moduleVersionName = BuildConfig.VERSION_NAME; private val moduleVersionCode = BuildConfig.VERSION_CODE; private val scopes = setOf("cat.app.bicleaner") override fun matchScope(packageName: String) = scopes.contains(packageName) override fun handleHook(classloader: ClassLoader) { XposedHelpers.findAndHookMethod( "cat.app.bicleaner.util.ModuleUtils\$Companion", classloader, "getModuleVersionName", object : XC_MethodHook() { override fun afterHookedMethod(param: MethodHookParam) { param.result = "$moduleVersionName($moduleVersionCode)" } }) } }
1
Kotlin
0
4
5e040c7873d4efb79613a467820f1e040d4aaf13
910
BiCleaner
MIT License
ktor-revfile-core/src/commonMain/kotlin/io/github/janmalch/ktor/revfile/RevisionedFile.kt
JanMalch
820,602,037
false
{"Kotlin": 32667, "JavaScript": 115}
package io.github.janmalch.ktor.revfile import io.ktor.http.* import io.ktor.http.content.* /** * Describes a revisioned file, meaning its [path] is unique based on its content. * * Revisioned files must be created by using one of the various extension functions on [WriteableRevFileRegistry]. * [create] is the most general function to create a revisioned file, * while [source] provides interop with `kotlinx.io`. * * Depending on your platform, convenient factories like [resource] or [file] are also available. * * ```kotlin * package com.example * * object AppAssets : RevFileRegistry("/assets/") { * val main: RevisionedFile = resource("main.js") * val styles: RevisionedFile = resource("styles.css") * } */ class RevisionedFile internal constructor( /** * The content type of this file, e.g. `text/javascript` * * Can be inferred or specified manually. */ val contentType: ContentType, /** * The full path of this file, e.g. `/assets/example.5c7ca8845f.js` */ val path: String, /** * The generated weak ETag for this file, e.g. `W/"XHyohF/kGOwoCv4RWnG0Epk/njHhmJdiOntPLZiMhQE="` */ internal val weakETag: String, /** * The computed integrity for this file, e.g. `sha256-XHyohF/kGOwoCv4RWnG0Epk/njHhmJdiOntPLZiMhQE=`. */ val integrity: String, /** * The content for this file, necessary for handling responses. */ internal val content: OutgoingContent.ReadChannelContent, ) { init { require(weakETag.startsWith("W/\"") && weakETag.endsWith('"') && weakETag.length > 4) { "Provided weak ETag is invalid: $weakETag" } require(integrity.startsWith("sha256-") && integrity.length > 7) { "Provided subresource integrity is invalid: $integrity" } } override fun toString(): String { return "RevisionedFile(path='$path', contentType=$contentType, integrity='$integrity')" } }
0
Kotlin
0
0
46262e64e84e008fe6e3a8daab9f84bac4c62453
1,982
ktor-revfile
Apache License 2.0