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
idea-plugin/src/main/kotlin/io/github/composegears/valkyrie/ui/screen/mode/iconpack/creation/common/packedit/model/InputChange.kt
ComposeGears
778,162,113
false
{"Kotlin": 777429}
package io.github.composegears.valkyrie.ui.screen.mode.iconpack.creation.common.packedit.model sealed interface InputChange { data class PackageName(val text: String) : InputChange data class IconPackName(val text: String) : InputChange data class NestedPackName(val id: String, val text: String) : InputChange }
27
Kotlin
6
321
f0647081b15b907ad92b38c33eb62179ffd0f969
326
Valkyrie
Apache License 2.0
domains/custom_tabs/src/main/java/com/sabufung/custom_tabs/CustomTabsDestinations.kt
sabufung30
552,990,093
false
null
package com.sabufung.custom_tabs import android.net.Uri import androidx.navigation.NavGraphBuilder import androidx.navigation.navArgument import androidx.navigation.navDeepLink import com.sabufung.custom_tabs.CustomTabsDestinations.ARG_URL import com.sabufung.custom_tabs.CustomTabsDestinations.CUSTOM_TABS fun NavGraphBuilder.customTabsNavigation() { customTabs( route = "$CUSTOM_TABS/{$ARG_URL}", arguments = listOf( navArgument(ARG_URL) {} ), customTabsIntentBuilder = { // TODO styling }, urlToLaunch = { args -> Uri.parse( requireNotNull(args?.getString(ARG_URL)) { "$ARG_URL argument is required but is not found." } ) } ) } object CustomTabsDestinations { const val CUSTOM_TABS = "customTabs" const val ARG_URL = "url" }
0
Kotlin
0
0
8676c8953db22c321b92c92881debb6e45c17c74
903
property-listing
Apache License 2.0
app/src/main/java/com/theupnextapp/ui/traktAccount/TraktAccountViewModel.kt
akitikkx
450,777,381
false
{"Kotlin": 588175}
/* * MIT License * * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.theupnextapp.ui.traktAccount import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import androidx.work.WorkManager import com.theupnextapp.repository.TraktRepository import com.theupnextapp.ui.common.BaseTraktViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TraktAccountViewModel @Inject constructor( private val traktRepository: TraktRepository, workManager: WorkManager ) : BaseTraktViewModel( traktRepository, workManager ) { val isLoading = traktRepository.isLoading val favoriteShows = traktRepository.traktFavoriteShows.asLiveData() private val _openCustomTab = MutableLiveData<Boolean>() val openCustomTab: LiveData<Boolean> = _openCustomTab private val _confirmDisconnectFromTrakt = MutableLiveData<Boolean>() val confirmDisconnectFromTrakt: LiveData<Boolean> = _confirmDisconnectFromTrakt val favoriteShowsEmpty = MediatorLiveData<Boolean>().apply { addSource(favoriteShows) { value = it.isNullOrEmpty() == true } } fun onConnectToTraktClick() { _openCustomTab.postValue(true) } fun onDisconnectFromTraktClick() { _confirmDisconnectFromTrakt.postValue(true) } fun onDisconnectFromTraktRefused() { _confirmDisconnectFromTrakt.postValue(false) } fun onDisconnectConfirm() { viewModelScope.launch(Dispatchers.IO) { traktRepository.clearFavorites() revokeTraktAccessToken() } _confirmDisconnectFromTrakt.postValue(false) } fun onCustomTabOpened() { _openCustomTab.postValue(false) } fun onCodeReceived(code: String?) { if (!code.isNullOrEmpty()) { viewModelScope.launch(Dispatchers.IO) { traktRepository.getTraktAccessToken(code) } } } }
19
Kotlin
8
56
1be1d597131481a9406bb53de77838c08fd3bde8
3,225
upnext
MIT License
app/src/main/java/com/test/restaurant/data/model/Pc.kt
Imranseu17
477,604,327
false
{"Kotlin": 48698}
package com.test.restaurant.data.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class Pc ( @JsonProperty("l" ) var l : String? , @JsonProperty("m" ) var m : String? , @JsonProperty("s" ) var s : String? ){ constructor():this("","","") override fun toString(): String { return "Pc(l=$l, m=$m, s=$s)" } }
0
Kotlin
0
0
fdb3b766622ee6116246ed8d6019f10923ac71ff
448
CleanArchitecture
Apache License 2.0
json/src/commonMain/kotlin/com/lhwdev/json/serialization/lazy.kt
lhwdev
322,430,175
false
null
package com.lhwdev.json.serialization import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.listSerialDescriptor import kotlinx.serialization.encoding.CompositeDecoder import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder class LazySequenceSerializer<T>(private val itemSerializer: KSerializer<T>) : KSerializer<Sequence<T>> { @OptIn(ExperimentalSerializationApi::class) override val descriptor = listSerialDescriptor(itemSerializer.descriptor) override fun deserialize(decoder: Decoder): Sequence<T> { require(decoder is JsonDecoder) val compositeDecoder = decoder.beginStructurePointed(descriptor) as JsonListDecoder return sequence { // this can be only applied to JsonArrayParser while(compositeDecoder.decodeElementIndex(descriptor) != CompositeDecoder.DECODE_DONE) yield( compositeDecoder.decodeSerializableElement( descriptor, compositeDecoder.currentIndex, itemSerializer ) ) } } override fun serialize(encoder: Encoder, value: Sequence<T>) { TODO() } }
0
Kotlin
0
0
7f1796bda22427c81cba00968c33489b22dbffce
1,151
MyNote
Apache License 2.0
feature/auth/domain/src/main/java/com/joelkanyi/auth/domain/entity/User.kt
joelkanyi
554,742,212
false
{"Kotlin": 563575, "Shell": 761, "Java": 595}
/* * Copyright 2023 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.joelkanyi.auth.domain.entity data class User( val id: String, val firstName: String, val lastName: String, val email: String, )
8
Kotlin
10
79
8da6fb74589e194c92e92a6ac1ebb27961219364
749
mealtime
Apache License 2.0
src/test/kotlin/com/mattmik/rapira/control/WhileLoopControllerTest.kt
rapira-book
519,693,099
true
{"Kotlin": 226030, "ANTLR": 7912}
package com.mattmik.rapira.control import com.mattmik.rapira.CONST_NO import com.mattmik.rapira.CONST_YES import com.mattmik.rapira.antlr.RapiraParser import com.mattmik.rapira.objects.RInteger import com.mattmik.rapira.objects.Text import com.mattmik.rapira.visitors.ExpressionVisitor import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.mockk.every import io.mockk.mockk import io.mockk.verify class WhileLoopControllerTest : WordSpec({ "isLoopActive" should { "return true until condition evaluates to no" { val mockCondition = mockk<RapiraParser.ExpressionContext>() val mockExpressionVisitor = mockk<ExpressionVisitor> { every { visit(mockCondition) } returnsMany listOf( CONST_YES, RInteger(123), Text("Hello, world!"), CONST_NO ) } val loopController = WhileLoopController(mockCondition, mockExpressionVisitor) loopController.run { isLoopActive().shouldBeTrue() isLoopActive().shouldBeTrue() isLoopActive().shouldBeTrue() isLoopActive().shouldBeFalse() } verify(exactly = 4) { mockExpressionVisitor.visit(mockCondition) } } } })
0
null
0
0
46f294e59c67747e1c00b5acf32b3cbe44281831
1,450
rapture
Apache License 2.0
app/src/main/java/com/fridaytech/demo/presentation/MainActivity.kt
5daytech
235,020,378
false
null
package com.fridaytech.demo.presentation import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import com.fridaytech.etomicswapkit.R import com.fridaytech.demo.presentation.swap.SwapFragment import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener { private lateinit var adapter: MainAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) adapter = MainAdapter(supportFragmentManager) mainViewPager.adapter = adapter mainNavigation.setOnNavigationItemSelectedListener(this) } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.navigation_balance -> mainViewPager.currentItem = 0 R.id.navigation_swap -> mainViewPager.currentItem = 1 } return true } private class MainAdapter(fm: FragmentManager): FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getItem(position: Int): Fragment = when(position) { 0 -> BalanceFragment() else -> SwapFragment() } override fun getCount(): Int = 2 } }
0
Kotlin
3
3
6f3c8f01e2ccc20714183494cd400a7ad8564a42
1,553
etomic-swap-kit-android
MIT License
iminling-core/src/main/kotlin/com/iminling/core/config/argument/DefaultRequestDataReader.kt
konghanghang
340,850,176
false
null
package com.iminling.core.config.argument import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory import org.springframework.http.HttpInputMessage import org.springframework.http.HttpMethod import org.springframework.http.HttpRequest import org.springframework.http.MediaType import org.springframework.web.method.HandlerMethod import java.io.IOException import java.io.InputStream import java.io.PushbackInputStream import javax.validation.constraints.NotNull /** * @author <EMAIL> * @since 2021/11/28 */ class DefaultRequestDataReader(val objectMapper: ObjectMapper) { private val logger = LoggerFactory.getLogger(DefaultRequestDataReader::class.java) private val suppotedMethod = setOf(HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH) fun canRead(message: @NotNull HttpInputMessage?): Boolean { val mediaType = message!!.headers.contentType if (!canRead(mediaType)) { return false } val httpMethod = if (message is HttpRequest) (message as HttpRequest).method else null return canRead(httpMethod) } private fun canRead(mediaType: @NotNull MediaType?): Boolean { if (mediaType == null) { return true } for (supportedMediaType in getSupportedMediaTypes()) { if (supportedMediaType.includes(mediaType)) { return true } } logger.info("Not support mediaType: {}", mediaType) return false } private fun canRead(httpMethod: @NotNull HttpMethod?): Boolean { if (httpMethod == null) { return true } if (suppotedMethod.contains(httpMethod)) { return true } logger.debug("Not support request method: {}", httpMethod) return false } @Throws(IOException::class) fun read(message: HttpInputMessage, handlerMethod: HandlerMethod?): JsonNode? { val inputStream = message.body val body: InputStream? if (inputStream.markSupported()) { inputStream.mark(1) body = if (inputStream.read() != -1) inputStream else null } else { val pushbackInputStream = PushbackInputStream(inputStream) val read = pushbackInputStream.read() if (read == -1) { body = null } else { body = pushbackInputStream pushbackInputStream.unread(read) } } return if (body != null) { objectMapper.readTree(body) } else null } fun getSupportedMediaTypes(): List<MediaType> { return listOf(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN) } }
0
Kotlin
0
1
9f2cb7d85ad7364ff3aa92bfd5eb15db9b23809a
2,767
base-iminling-core
MIT License
domain/src/main/kotlin/com/jvmhater/moduticket/repository/SeatRepository.kt
jvm-hater
587,725,795
false
null
package com.jvmhater.moduticket.repository import com.jvmhater.moduticket.model.Seat interface SeatRepository { suspend fun find(): List<Seat> suspend fun update(): Seat }
3
Kotlin
0
3
afbf566af54555c9933b2e4c4f6dce5a95b2927b
182
modu-ticket-backend
MIT License
app/src/main/java/com/devstromo/openaikotlin/chat/core/GtpControllerQualifiers.kt
devstromo
783,083,124
false
{"Kotlin": 26059}
package com.devstromo.openaikotlin.chat.core import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.BINARY) annotation class AndroidController @Qualifier @Retention(AnnotationRetention.BINARY) annotation class FakeController
0
Kotlin
0
0
e237ce79ba63eda75d539594559d3d7cdc0ab33d
244
android-kotlin-openai
MIT License
reflekt-plugin/src/main/kotlin/org/jetbrains/reflekt/plugin/generation/ir/IrBuilderExtension.kt
JetBrains-Research
293,503,377
false
null
package org.jetbrains.reflekt.plugin.generation.ir import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.IrBuiltIns import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrEnumEntry import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrAnonymousInitializerSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.kotlinFqName import org.jetbrains.kotlin.name.Name import org.jetbrains.reflekt.plugin.analysis.ir.makeTypeProjection import org.jetbrains.reflekt.plugin.analysis.processor.toReflektVisibility import org.jetbrains.reflekt.plugin.generation.ir.util.* import org.jetbrains.reflekt.plugin.generation.ir.util.irCall import org.jetbrains.reflekt.plugin.utils.getValueArguments /** * Provides utilities for IR generation and transformation: extensions to [IrClass], and to [IrBuilder]. */ interface IrBuilderExtension { val pluginContext: IrPluginContext val irBuiltIns: IrBuiltIns get() = pluginContext.irBuiltIns val generationSymbols: GenerationSymbols @OptIn(ObsoleteDescriptorBasedAPI::class) fun IrClass.contributeAnonymousInitializer(body: IrBlockBodyBuilder.() -> Unit) { factory.createAnonymousInitializer(startOffset, endOffset, origin, IrAnonymousInitializerSymbolImpl(descriptor)).also { it.parent = this declarations += it it.body = DeclarationIrBuilder(pluginContext, it.symbol, startOffset, endOffset).irBlockBody(startOffset, endOffset, body) } } fun IrBuilderWithScope.irCheckNotNull(value: IrExpression) = irCall( irBuiltIns.checkNotNullSymbol, typeArguments = listOf(value.type.makeNotNull()), valueArguments = listOf(value), ) fun IrBuilderWithScope.irMapGet(map: IrExpression, key: IrExpression) = irCall(generationSymbols.mapGet, dispatchReceiver = map, valueArguments = listOf(key)) fun IrBuilderWithScope.irTo(left: IrExpression, right: IrExpression) = irCall(generationSymbols.to, typeArguments = listOf(left.type, right.type), extensionReceiver = left, valueArguments = listOf(right)) fun IrBuilderWithScope.irHashMapOf(keyType: IrType, valueType: IrType, pairs: List<IrExpression>) = irCall( generationSymbols.hashMapOf, typeArguments = listOf(keyType, valueType), valueArguments = listOf( irVarargOut( generationSymbols.pairClass.createType( false, listOf(keyType.makeTypeProjection(), valueType.makeTypeProjection()), ), pairs, ), ), ) fun IrBuilderWithScope.irMutableSetAdd(mutableSet: IrExpression, element: IrExpression) = irCall(generationSymbols.mutableSetAdd, dispatchReceiver = mutableSet, valueArguments = listOf(element)) fun IrBuilderWithScope.irReflektClassImplConstructor(irClassSymbol: IrClassSymbol): IrFunctionAccessExpression { val irClass = irClassSymbol.owner return irCall( generationSymbols.reflektClassImplConstructor, typeArguments = listOf(irClassSymbol.defaultType), valueArguments = listOf( irClassReference(irClassSymbol), irCall( generationSymbols.hashSetOf, typeArguments = listOf(irBuiltIns.annotationType), valueArguments = listOf( irVarargOut(irBuiltIns.annotationType, irClass.annotations.map { irCall(it.symbol, valueArguments = it.getValueArguments()) }), ), ), irBoolean(irClass.modality == Modality.ABSTRACT), irBoolean(irClass.isCompanion), irBoolean(irClass.isData), irBoolean(irClass.modality == Modality.FINAL), irBoolean(irClass.isFun), irBoolean(irClass.isInner), irBoolean(irClass.modality == Modality.OPEN), irBoolean(irClass.modality == Modality.SEALED), irBoolean(irClass.isValue), irString(irClass.kotlinFqName.toString()), irCall(generationSymbols.hashSetConstructor), irCall(generationSymbols.hashSetConstructor), irString(irClass.kotlinFqName.shortName().toString()), irGetEnumValue( generationSymbols.reflektVisibilityClass.defaultType, generationSymbols.reflektVisibilityClass.owner.declarations.filterIsInstance<IrEnumEntry>() .first { it.name == Name.identifier(irClass.visibility.toReflektVisibility()!!.name) }.symbol, ), ), ) } }
13
null
9
318
438a20b05aed201a9139af344b00e7db17ac4479
5,210
reflekt
Apache License 2.0
domain/src/main/java/com/piotrek1543/android/boilerplate/domain/model/Pod.kt
piotrek1543
168,876,182
false
null
package com.piotrek1543.android.boilerplate.domain.model /** * Representation for a [Pod] fetched from an external layer data source */ data class Pod(var pod: String? = null, val listDt: Long?)
0
Kotlin
0
8
a5510a569d306660d03263f039ab02882c531e2c
198
sunshine_clean_architecture
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/spawns/spawns_14387.plugin.kts
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.areas.spawns spawn_npc(npc = 14140, x = 3597, z = 3317, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14140, x = 3598, z = 3322, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14143, x = 3598, z = 3318, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14146, x = 3598, z = 3323, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14149, x = 3598, z = 3319, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14152, x = 3597, z = 3320, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = 14152, x = 3598, z = 3324, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Captured Meiyerditch citizen spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4754, x = 3631, z = 3272, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4749, x = 3631, z = 3299, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4750, x = 3632, z = 3313, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD, x = 3639, z = 3267, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4751, x = 3639, z = 3287, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4749, x = 3641, z = 3279, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.A_MEIYERDITCH_CHILD_4750, x = 3642, z = 3287, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //A Meiyerditch child spawn_npc(npc = Npcs.CAT_4768, x = 3629, z = 3309, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Cat spawn_npc(npc = Npcs.CAT_4769, x = 3631, z = 3315, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Cat spawn_npc(npc = Npcs.CAT_4769, x = 3634, z = 3294, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Cat spawn_npc(npc = Npcs.CAT_4768, x = 3635, z = 3296, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Cat spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4745, x = 3595, z = 3264, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4741, x = 3596, z = 3265, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4734, x = 3599, z = 3285, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4724, x = 3600, z = 3280, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4735, x = 3601, z = 3284, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4739, x = 3602, z = 3275, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4742, x = 3603, z = 3266, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4736, x = 3603, z = 3285, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4725, x = 3605, z = 3268, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4737, x = 3605, z = 3284, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4738, x = 3607, z = 3285, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4720, x = 3610, z = 3272, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4740, x = 3611, z = 3285, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4719, x = 3615, z = 3283, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4722, x = 3616, z = 3273, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_14186, x = 3618, z = 3276, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_14188, x = 3620, z = 3301, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4745, x = 3620, z = 3321, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4722, x = 3621, z = 3284, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4741, x = 3621, z = 3319, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4729, x = 3621, z = 3325, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4730, x = 3622, z = 3325, height = 0, walkRadius = 5, direction = Direction.NORTH, static = true) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4723, x = 3623, z = 3283, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4737, x = 3624, z = 3271, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4724, x = 3624, z = 3281, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4725, x = 3627, z = 3281, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_14187, x = 3627, z = 3292, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4721, x = 3628, z = 3283, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4726, x = 3629, z = 3280, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4735, x = 3630, z = 3308, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4720, x = 3631, z = 3300, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4725, x = 3631, z = 3325, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4736, x = 3632, z = 3265, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4719, x = 3632, z = 3286, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4722, x = 3632, z = 3299, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4743, x = 3634, z = 3269, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4736, x = 3634, z = 3310, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4742, x = 3635, z = 3271, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4735, x = 3636, z = 3280, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN, x = 3637, z = 3275, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4742, x = 3638, z = 3296, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4723, x = 3638, z = 3317, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4743, x = 3638, z = 3319, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_14189, x = 3639, z = 3290, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4742, x = 3640, z = 3286, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4744, x = 3641, z = 3278, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.MEIYERDITCH_CITIZEN_4721, x = 3642, z = 3282, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Meiyerditch citizen spawn_npc(npc = Npcs.STRAY_DOG, x = 3605, z = 3282, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Stray dog spawn_npc(npc = Npcs.STRAY_DOG_4767, x = 3636, z = 3284, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Stray dog spawn_npc(npc = Npcs.STRAY_DOG, x = 3637, z = 3313, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Stray dog spawn_npc(npc = Npcs.STRAY_DOG_4767, x = 3641, z = 3301, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Stray dog spawn_npc(npc = Npcs.VYRELORD_14132, x = 3603, z = 3325, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Vyrelord spawn_npc(npc = Npcs.VYRELORD_14128, x = 3611, z = 3317, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Vyrelord spawn_npc(npc = Npcs.VYREWATCH_GUARD_14115, x = 3601, z = 3322, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Vyrewatch guard spawn_npc(npc = Npcs.VYREWATCH_GUARD_14116, x = 3603, z = 3322, height = 0, walkRadius = 5, direction = Direction.NORTH, static = false) //Vyrewatch guard
36
null
138
32
da66bb6d68ebae531ee325b909a6536e798b1144
11,487
game
Apache License 2.0
app/src/main/java/com/example/wanandroid/data/CategoryRepository.kt
vejei
282,851,214
false
null
package com.example.wanandroid.data import com.example.wanandroid.data.remote.CategoryService import com.example.wanandroid.utils.Transformers.processResponse import io.reactivex.Observable import javax.inject.Inject class CategoryRepository @Inject constructor(private val categoryService: CategoryService) { fun fetchCategories(): Observable<Result<MutableList<Category>>> { return categoryService.fetchCategories().compose(processResponse()) } fun fetchProjectCategories(): Observable<Result<MutableList<Category>>> { return categoryService.fetchProjectCategories().compose(processResponse()) } }
1
Kotlin
0
4
baaf7d298d030d1d9af2841736537d09c263bfff
635
android-mvvm-sample
MIT License
libs/mintycore/src/main/java/com/solanamobile/mintyfresh/mintycore/repository/MintTransactionRepository.kt
solana-mobile
586,997,383
false
{"Kotlin": 207429, "Shell": 1506}
package com.solanamobile.mintyfresh.mintycore.repository import com.metaplex.lib.drivers.solana.Connection import com.metaplex.lib.experimental.jen.tokenmetadata.Creator import com.metaplex.lib.modules.nfts.builders.CreateNftTransactionBuilder import com.metaplex.lib.modules.nfts.models.Metadata import com.solana.core.PublicKey import com.solanamobile.mintyfresh.networkinterface.pda.mintyFreshCreatorPubKey import javax.inject.Inject class MintTransactionRepository @Inject constructor(private val connectionDriver: Connection) { // not currently used, but shows how you could build the minting transaction suspend fun buildMintTransaction(title: String, metadataUrl: String, mint: PublicKey, payer: PublicKey) = CreateNftTransactionBuilder( newMint = mint, metadata = createNftMetadata(title, metadataUrl, payer), payer = payer, connection = connectionDriver ).build().getOrThrow().apply { feePayer = payer } private fun createNftMetadata(title: String, metadataUrl: String, creator: PublicKey) = Metadata( name = title.truncateBytes(NFT_NAME_BYTE_LIMIT), // uri must be < 204 bytes, not checked here because IPFS links will always be less uri = metadataUrl, sellerFeeBasisPoints = 0, creators = listOf( Creator(creator, true, 100.toUByte()), Creator(PublicKey(mintyFreshCreatorPubKey), false, 0.toUByte()) ), ) // truncates a string to a max number of bytes, preserving character boundaries private fun String.truncateBytes(maxBytes: Int): String { var count = 0 return this.takeWhile { count += if (it.code <= 0x007F) 1 else if (it.code <= 0x07FF) 2 else 3 count < maxBytes } } companion object { private const val NFT_NAME_BYTE_LIMIT = 32 } }
13
Kotlin
17
42
e06d6d3c4b45c5ed736e422ed622cac9cd330ce1
1,904
Minty-fresh
Apache License 2.0
WarehouseService/src/test/kotlin/server/RoutesTesterWrongConnection.kt
elisaalbertini
817,174,888
false
{"Kotlin": 49902, "HTML": 21778, "TypeScript": 5359, "Gherkin": 2660, "CSS": 80}
package server import ApiUtils import BaseTest import WarehouseMessage import application.UpdateQuantity import domain.Ingredient import io.kotest.matchers.shouldBe import io.vertx.core.Vertx import io.vertx.kotlin.coroutines.coAwait import kotlinx.coroutines.runBlocking import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json class RoutesTesterWrongConnection : BaseTest() { private val port = 8081 private val apiUtils = ApiUtils(port) init { runBlocking { Vertx.vertx().deployVerticle(Server(getWrongInfo(), port)).coAwait() } } @Test suspend fun createIngredientRouteTest() { val newIngredient = Json.encodeToString(coffee) val response = apiUtils.createIngredient("ingredient", newIngredient).send().coAwait() response.statusCode() shouldBe 500 response.statusMessage() shouldBe WarehouseMessage.ERROR_DB_NOT_AVAILABLE.toString() } @Ignore @Test suspend fun updateConsumedIngredientsQuantityRouteTest() { val decreaseMilk = 10 val decreaseTea = 4 val decreaseIngredients = Json.encodeToString(listOf(UpdateQuantity("milk", decreaseMilk), UpdateQuantity("tea", decreaseTea))) val response = apiUtils.updateConsumedIngredientsQuantity("quantity", decreaseIngredients).send().coAwait() response.statusCode() shouldBe 500 response.statusMessage() shouldBe WarehouseMessage.ERROR_DB_NOT_AVAILABLE.toString() } @Ignore @Test suspend fun restockRouteTest() { val quantity = Json.encodeToString(10) val response = apiUtils.restock("tea", "quantity", quantity).send().coAwait() response.statusCode() shouldBe 500 response.statusMessage() shouldBe WarehouseMessage.ERROR_DB_NOT_AVAILABLE.toString() } @Ignore @Test suspend fun getAllIngredientsRouteTest() { val response = apiUtils.getAllIngredients("").send().coAwait() response.statusCode() shouldBe 500 response.bodyAsString() shouldBe null response.statusMessage() shouldBe WarehouseMessage.ERROR_DB_NOT_AVAILABLE.toString() } @Ignore @Test suspend fun getAllAvailableIngredients() { collection.insertOne(Ingredient("coffee", 0)) val response = apiUtils.getAllIngredients("available").send().coAwait() response.statusCode() shouldBe 500 response.bodyAsString() shouldBe null response.statusMessage() shouldBe WarehouseMessage.ERROR_DB_NOT_AVAILABLE.toString() } }
0
Kotlin
0
0
8440bc02b82b918dd55e0ab1ada4e316608b5f06
2,572
paguroDbRepo
MIT License
src/main/kotlin/com/github/pushpavel/autocp/tester/TreeTestingProcessReporter.kt
Pushpavel
372,015,012
false
{"Kotlin": 167445, "HTML": 56159}
package com.github.pushpavel.autocp.tester import com.github.pushpavel.autocp.common.errors.NoReachErr import com.github.pushpavel.autocp.common.res.R import com.github.pushpavel.autocp.tester.base.BuildErr import com.github.pushpavel.autocp.tester.base.ProcessRunner import com.github.pushpavel.autocp.tester.tree.ResultNode import com.github.pushpavel.autocp.tester.tree.TestNode import com.github.pushpavel.autocp.tester.tree.TreeTestingProcess import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessOutputTypes import com.intellij.execution.testframework.sm.ServiceMessageBuilder import com.intellij.execution.testframework.sm.ServiceMessageBuilder.* /** * Class that abstracts formatting and sending output to the console and the TestRunner UI */ class TreeTestingProcessReporter(private val processHandler: ProcessHandler) : TreeTestingProcess.Listener { override fun leafStart(node: TestNode.Leaf) { testStarted(node.name).apply() testStdOut(node.name).addAttribute( "out", "${"___".repeat(5)}[ ${node.name} ]${"___".repeat(5)}\n" ).apply() } override fun leafFinish(node: ResultNode.Leaf) { val nodeName = node.sourceNode.name if (node.verdict is com.github.pushpavel.autocp.tester.errors.Verdict.CorrectAnswer) { testStdOut(nodeName).addAttribute( "out", node.verdict.output + '\n' + R.strings.verdictOneLine(node.verdict) + '\n' ).apply() testFinished(nodeName) .addAttribute("duration", node.verdict.executionTime.toString()) .apply() return } when (node.verdict) { is com.github.pushpavel.autocp.tester.errors.Verdict.WrongAnswer -> { testStdOut(nodeName).addAttribute("out", node.verdict.actualOutput + '\n').apply() testFailed(nodeName) .addAttribute("message", R.strings.verdictOneLine(node.verdict)) .addAttribute("type", "comparisonFailure") .addAttribute("actual", node.verdict.actualOutput) .addAttribute("expected", node.verdict.expectedOutput) .apply() testFinished(nodeName) .addAttribute("duration", node.verdict.executionTime.toString()) .apply() } is com.github.pushpavel.autocp.tester.errors.Verdict.RuntimeErr -> { testStdOut(nodeName) .addAttribute("out", node.verdict.output + '\n') .apply() testFailed(nodeName) .addAttribute("message", R.strings.verdictOneLine(node.verdict)) .addAttribute("details", node.verdict.errMsg) .apply() testFinished(nodeName) .apply() } is com.github.pushpavel.autocp.tester.errors.Verdict.TimeLimitErr -> { testFailed(nodeName) .addAttribute("message", R.strings.verdictOneLine(node.verdict)) .apply() testFinished(nodeName) .addAttribute("duration", node.verdict.timeLimit.toString()) .apply() } is com.github.pushpavel.autocp.tester.errors.Verdict.InternalErr -> { testFailed(nodeName) .addAttribute("message", R.strings.verdictOneLine(node.verdict)) .addAttribute("details", R.strings.defaultFileIssue(node.verdict.err)) .apply() testFinished(nodeName) .apply() } else -> throw NoReachErr } } override fun groupStart(node: TestNode.Group) { testSuiteStarted(node.name).apply() } override fun groupFinish(node: ResultNode.Group) { testSuiteFinished(node.sourceNode.name).apply() } override fun commandReady(configName: String) { processHandler.notifyTextAvailable( R.strings.commandReadyMsg(configName) + "\n", ProcessOutputTypes.STDOUT ) } override fun compileStart(configName: String) { processHandler.notifyTextAvailable( R.strings.startCompilingMsg(configName) + "\n", ProcessOutputTypes.STDOUT ) } override fun compileFinish(result: Result<ProcessRunner.CapturedResults>) { when { result.isSuccess -> { val r = result.getOrThrow() val msg = R.strings.compileSuccessMsg(r.output, r.executionTime) processHandler.notifyTextAvailable(msg + "\n", ProcessOutputTypes.STDOUT) } result.isFailure -> { val msg = when (val e = result.exceptionOrNull()!!) { is BuildErr -> R.strings.buildErrMsg(e) else -> throw e } processHandler.notifyTextAvailable(msg + "\n", ProcessOutputTypes.STDERR) } } } override fun testingProcessError(message: String) { processHandler.notifyTextAvailable(message + "\n", ProcessOutputTypes.STDERR) } private fun ServiceMessageBuilder.apply() { processHandler.notifyTextAvailable( this.toString() + "\n", ProcessOutputTypes.STDOUT ) } }
22
Kotlin
13
41
6324b29ecb1576b8bb8691586659f0f57415676b
5,477
AutoCp
MIT License
app/src/main/java/com/hermanowicz/pantry/data/repository/SettingsRepositoryImpl.kt
sirconceptz
615,655,539
false
null
package com.hermanowicz.pantry.data.repository import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.hermanowicz.pantry.data.settings.AppSettings import com.hermanowicz.pantry.di.repository.SettingsRepository import com.hermanowicz.pantry.utils.enums.CameraMode import com.hermanowicz.pantry.utils.enums.DatabaseMode import com.hermanowicz.pantry.utils.enums.QrCodeSize import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Singleton @Singleton class SettingsRepositoryImpl @Inject constructor( @ApplicationContext private val context: Context ) : SettingsRepository { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs") override val appSettings: Flow<AppSettings> get() = context.dataStore.data.map { preferences -> val databaseMode = preferences[DATABASE_MODE_KEY] ?: DatabaseMode.LOCAL.name val cameraMode = preferences[CAMERA_MODE_KEY] ?: CameraMode.REAR.name val scannerSoundMode = preferences[SCANNER_SOUND_MODE_KEY] ?: true val qrCodeSize = preferences[SIZE_PRINTED_QR_CODES_KEY] ?: QrCodeSize.BIG.name val daysToNotifyBeforeExpiration = preferences[DAYS_TO_NOTIFY_BEFORE_EXPIRATION] ?: 3 val emailForNotifications = preferences[EMAIL_ADDRESS_FOR_NOTIFICATIONS_KEY] ?: "" val pushNotifications = preferences[PUSH_NOTIFICATIONS_KEY] ?: true val emailNotifications = preferences[EMAIL_NOTIFICATIONS_KEY] ?: false AppSettings( databaseMode = databaseMode, cameraMode = cameraMode, scannerSound = scannerSoundMode, daysToNotifyBeforeExpiration = daysToNotifyBeforeExpiration.toFloat(), emailForNotifications = emailForNotifications, qrCodeSize = qrCodeSize, pushNotifications = pushNotifications, emailNotifications = emailNotifications ) } override suspend fun updateAppSettings(appSettings: AppSettings) { context.dataStore.edit { preferences -> preferences[DATABASE_MODE_KEY] = appSettings.databaseMode preferences[CAMERA_MODE_KEY] = appSettings.cameraMode preferences[SCANNER_SOUND_MODE_KEY] = appSettings.scannerSound preferences[SIZE_PRINTED_QR_CODES_KEY] = appSettings.qrCodeSize preferences[DAYS_TO_NOTIFY_BEFORE_EXPIRATION] = appSettings.daysToNotifyBeforeExpiration.toInt() preferences[EMAIL_ADDRESS_FOR_NOTIFICATIONS_KEY] = appSettings.emailForNotifications preferences[EMAIL_NOTIFICATIONS_KEY] = appSettings.emailNotifications preferences[PUSH_NOTIFICATIONS_KEY] = appSettings.pushNotifications } } override val databaseMode: Flow<String> get() = context.dataStore.data.map { preferences -> preferences[DATABASE_MODE_KEY] ?: DatabaseMode.LOCAL.name } override val qrCodeSize: Flow<String> get() = context.dataStore.data.map { preferences -> preferences[SIZE_PRINTED_QR_CODES_KEY] ?: QrCodeSize.BIG.name } override val daysBeforeNotification: Flow<Int> get() = context.dataStore.data.map { preferences -> preferences[DAYS_TO_NOTIFY_BEFORE_EXPIRATION] ?: 3 } override val isPushNotificationsEnabled: Flow<Boolean> get() = context.dataStore.data.map { preferences -> preferences[PUSH_NOTIFICATIONS_KEY] ?: true } override val isEmailNotificationsEnabled: Flow<Boolean> get() = context.dataStore.data.map { preferences -> preferences[EMAIL_NOTIFICATIONS_KEY] ?: false } override val emailAddressForNotifications: Flow<String> get() = context.dataStore.data.map { preferences -> preferences[EMAIL_ADDRESS_FOR_NOTIFICATIONS_KEY] ?: "" } companion object { val DATABASE_MODE_KEY = stringPreferencesKey("database_mode") val CAMERA_MODE_KEY = stringPreferencesKey("camera_mode") val EMAIL_ADDRESS_FOR_NOTIFICATIONS_KEY = stringPreferencesKey("email_for_notifications") val SCANNER_SOUND_MODE_KEY = booleanPreferencesKey("scanner_sound_mode") val DAYS_TO_NOTIFY_BEFORE_EXPIRATION = intPreferencesKey("days_to_notify_before_expiration") val SIZE_PRINTED_QR_CODES_KEY = stringPreferencesKey("size_printed_qr_codes") val PUSH_NOTIFICATIONS_KEY = booleanPreferencesKey("push_notifications") val EMAIL_NOTIFICATIONS_KEY = booleanPreferencesKey("email_notifications") } }
0
Kotlin
0
1
60dc91a7ff016bf636c07eb10f4606fea8998c08
5,357
MyPantry
Apache License 2.0
app/src/main/java/pl/gmat/designpatterns/abstractfactory/Gallery.kt
gmatyszczak
168,134,144
false
null
package pl.gmat.designpatterns.abstractfactory interface GalleryFactory { fun createGallery(): Gallery fun createRepository(): GalleryRepository fun createResult(): GalleryResult } interface Gallery interface GalleryRepository interface GalleryResult
0
Kotlin
0
0
dc9cebe095c5060722cc1df2837621aad9cd5330
267
design-patterns
Apache License 2.0
features/movie/presentation/src/main/java/com/movie/presentation/ui/screen/MovieListScreen.kt
john-us
640,201,719
false
null
package com.movie.presentation.ui.screen import CustomImage import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.movie.common.network.Result import com.movie.domain.model.MovieListDisplayModel import com.movie.presentation.R import com.movie.presentation.constant.FontSize import com.movie.presentation.navigation.Screen import com.movie.presentation.ui.customcomposable.MovieProgressBar import com.movie.presentation.ui.customcomposable.MovieText import com.movie.presentation.viewmodel.MovieListViewModel @Composable fun MovieListScreen( navController: NavController, ) { val context = LocalContext.current val viewModel: MovieListViewModel = hiltViewModel() val movieList by viewModel.movieList.collectAsState() LaunchedEffect(Unit) { viewModel.loadMovieList() } when (movieList) { is Result.Loading -> MovieProgressBar() is Result.Success -> MovieList( movieList = (movieList as Result.Success<List<MovieListDisplayModel>>).data, onItemClick = { movie -> navController.navigate("${Screen.MovieDetail.route}/${movie.id}") } ) is Result.Error -> Toast.makeText( context, context.getString(R.string.error_fetching_movie), Toast.LENGTH_LONG ).show() } } @Composable fun MovieList( movieList: List<MovieListDisplayModel>, onItemClick: (MovieListDisplayModel) -> Unit, ) { Box(modifier = Modifier.fillMaxSize()) { LazyColumn { items(movieList) { movie -> MovieListItem(movie = movie) { onItemClick(movie) } } } } } @Composable fun MovieListItem(movie: MovieListDisplayModel, onItemClick: (MovieListDisplayModel) -> Unit) { Row(modifier = Modifier .padding(all = dimensionResource(id = R.dimen.space_10)) .clickable { // callback for list item click onItemClick(movie) }) { CustomImage( modifier = Modifier .clip(shape = RoundedCornerShape(dimensionResource(id = R.dimen.space_5))) .size(dimensionResource(id = R.dimen.space_60)), url = movie.backdropPath, fallbackResId = R.drawable.ic_launcher_background, defaultResId = R.drawable.ic_launcher_background, contentDescription = stringResource(id = R.string.background_image) ) Spacer(modifier = Modifier.width(dimensionResource(id = R.dimen.space_8))) Column { MovieText( text = movie.title, fontSize = FontSize.fontSize_16 ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.space_8))) MovieText(text = movie.releaseDate) } } }
0
Kotlin
0
0
f51abc526317651ab13f966f0d702e89f9cf629b
3,967
MovieApp
MIT License
app/src/main/java/csdev/it/trustedwebactivitydemo/LaunchFromWebActivity.kt
schaeferchristian
259,953,595
false
null
package csdev.it.trustedwebactivitydemo import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import kotlinx.android.synthetic.main.activity_launch_from_web.* class LaunchFromWebActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_launch_from_web) supportActionBar.apply { this?.setHomeButtonEnabled(true) this?.setDisplayHomeAsUpEnabled(true) } handleIntent() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) this.intent = intent handleIntent() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item?.itemId){ android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } private fun handleIntent() { intent.data?.let { messageTextView.text = it.getQueryParameter("message") sourceTextView.text = it.getQueryParameter("source") param3TextView.text = it.getQueryParameter("param3") } } }
0
Kotlin
0
1
34ee793910f47fc23ee78545fba30abae482af7c
1,288
trustedwebactivitydemo
MIT License
extension-compose/src/main/java/com/mapbox/maps/extension/compose/style/layers/generated/SymbolLayer.kt
mapbox
330,365,289
false
{"Kotlin": 3982759, "Java": 98572, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2413, "CMake": 1201, "EJS": 1194}
// This file is generated. package com.mapbox.maps.extension.compose.style.layers.generated import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposeNode import androidx.compose.runtime.currentComposer import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import com.mapbox.maps.extension.compose.MapboxMapComposable import com.mapbox.maps.extension.compose.internal.MapApplier import com.mapbox.maps.extension.compose.style.IdGenerator.generateRandomLayerId import com.mapbox.maps.extension.compose.style.layers.internal.LayerNode import com.mapbox.maps.extension.compose.style.sources.SourceState /** * An icon or a text label. * * This composable function inserts a [SymbolLayer] to the map. For convenience, if there's * no need to hoist the [symbolLayerState], use `SymbolLayer(sourceState, layerId, init)` with trailing lambda instead. * * @see [The online documentation](https://docs.mapbox.com/style-spec/reference/layers#symbol) * * @param sourceState the source that drives this layer. * @param layerId the ID of the layer, by default, a random id will be generated with UUID. * @param symbolLayerState the state holder for [SymbolLayer]'s properties. */ @Composable @MapboxMapComposable public fun SymbolLayer( sourceState: SourceState, layerId: String = remember { generateRandomLayerId("symbol") }, symbolLayerState: SymbolLayerState = remember { SymbolLayerState() } ) { val mapApplier = currentComposer.applier as? MapApplier ?: throw IllegalStateException("Illegal use of SymbolLayer inside unsupported composable function") val coroutineScope = rememberCoroutineScope() val layerNode = remember { LayerNode( map = mapApplier.mapView.mapboxMap, layerType = "symbol", sourceState = sourceState, layerId = layerId, coroutineScope = coroutineScope ) } ComposeNode<LayerNode, MapApplier>( factory = { layerNode }, update = { update(sourceState) { updateSource(sourceState) } update(layerId) { updateLayerId(layerId) } } ) { key(symbolLayerState) { symbolLayerState.UpdateProperties(layerNode) } } sourceState.UpdateProperties() } /** * An icon or a text label. * * This composable function inserts a [SymbolLayer] to the map. * * @see [The online documentation](https://docs.mapbox.com/style-spec/reference/layers#symbol) * * @param sourceState the source that drives this layer. * @param layerId the ID of the layer, by default, a random id will be generated with UUID. * @param init the lambda that will be applied to the remembered [SymbolLayerState]. */ @Composable @MapboxMapComposable public inline fun SymbolLayer( sourceState: SourceState, layerId: String = remember { generateRandomLayerId("symbol") }, crossinline init: SymbolLayerState.() -> Unit ) { SymbolLayer(sourceState = sourceState, layerId = layerId, symbolLayerState = remember { SymbolLayerState() }.apply(init)) } // End of generated file.
225
Kotlin
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
3,105
mapbox-maps-android
Apache License 2.0
app/src/main/java/com/sample/android/tmdb/ui/paging/main/tvshow/OnTheAirTVShowFragment.kt
alirezaeiii
158,464,119
false
{"Kotlin": 228896, "Java": 7620}
package com.sample.android.tmdb.ui.paging.main.tvshow import com.sample.android.tmdb.domain.model.SortType.UPCOMING import javax.inject.Inject class OnTheAirTVShowFragment @Inject constructor() : TVShowFragment() { override val sortType = UPCOMING }
0
Kotlin
17
154
402c696e3748c184bad44aeec6fccb40bcdde0db
256
TMDb-Paging-Playground
The Unlicense
Android/app/src/main/java/com/example/emojisemanticsearch/startup/AppInitializer.kt
sunnyswag
650,670,940
false
null
package com.example.emojisemanticsearch.startup import android.content.Context import android.util.Log import androidx.startup.Initializer import com.example.emoji_data_reader.processor.ProcessorFactory import com.example.emoji_data_reader.processor.ProcessorFactory.EMOJI_EMBEDDING_SIZE import com.example.emoji_data_reader.processor.ProcessorFactory.emojiInfoData import com.example.emoji_data_reader.processor.ProcessorType import com.example.emojisemanticsearch.R import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlin.time.ExperimentalTime import kotlin.time.measureTime class AppInitializer : Initializer<Unit> { private val initializerScope = CoroutineScope(Dispatchers.Default) @OptIn(ExperimentalTime::class) override fun create(context: Context) { initializerScope.launch { val timeSpend = measureTime { readEmojiEmbeddings(context) } Log.d(TAG, "read emoji embeddings in $timeSpend") val emojiDataSize = emojiInfoData.filterNot { it.emoji.isEmpty() }.size if (emojiDataSize != EMOJI_EMBEDDING_SIZE) { Log.e(TAG, "the size of emojiInfoData is not correct, " + "emojiInfoData.size: $emojiDataSize") } } } override fun dependencies(): MutableList<Class<out Initializer<*>>> { return mutableListOf() } private suspend fun readEmojiEmbeddings(context: Context) { ProcessorFactory.doProcess( context, ProcessorType.PROTOBUF_PROCESSOR, listOf(R.raw.emoji_embeddings_proto) ) } companion object { const val TAG = "AppInitializer" } }
0
Kotlin
0
0
a478de3cafb5037a6378793ccaaa88014371695c
1,739
emoji-search
MIT License
lawnchair/src/app/lawnchair/util/FileExtensions.kt
LawnchairLauncher
83,799,439
false
null
package app.lawnchair.util import android.net.Uri import androidx.core.content.FileProvider import app.lawnchair.LawnchairApp import java.io.File import okio.FileMetadata import okio.FileSystem import okio.Path internal fun Path.list( fileSystem: FileSystem = FileSystem.SYSTEM, isShowHidden: Boolean = false, isRecursively: Boolean = false, ): Sequence<Path> { return runCatching { if (isRecursively) { fileSystem.listRecursively(this) } else { fileSystem.list(this).asSequence() } }.getOrDefault(emptySequence()).filter { if (isShowHidden) true else !it.isHidden } } internal fun Path.getMetadata(fileSystem: FileSystem = FileSystem.SYSTEM): FileMetadata? = fileSystem.metadataOrNull(this) internal fun Path.isDirectory(fileSystem: FileSystem = FileSystem.SYSTEM): Boolean = getMetadata(fileSystem)?.isDirectory == true internal fun Path.isFile(fileSystem: FileSystem = FileSystem.SYSTEM): Boolean = !isDirectory(fileSystem) internal fun Path.sizeOrEmpty(fileSystem: FileSystem = FileSystem.SYSTEM): Long = getMetadata(fileSystem)?.size ?: 0 internal fun Path.isRegularFile(fileSystem: FileSystem = FileSystem.SYSTEM): Boolean = getMetadata(fileSystem)?.isRegularFile == true internal val Path.isHidden: Boolean get() = toString().contains("/.") internal val Path.exists: Boolean get() = toFile().exists() internal val Path.extension: String? get() { val dotIndex = name.lastIndexOf(".") return if (dotIndex == -1) null else name.substring(dotIndex + 1) } internal val Path.nameWithoutExtension: String get() = name.substringBeforeLast(".") internal val Path.mimeType: String? get() = extension?.extension2MimeType() val fileProviderAuthority: String = "${LawnchairApp.instance.packageName}.fileprovider" fun String.path2Uri(): Uri? = File(this).file2Uri() fun File.file2Uri(): Uri? = try { FileProvider.getUriForFile(LawnchairApp.instance, fileProviderAuthority, this) } catch (e: Exception) { e.printStackTrace() null }
388
null
1200
9,200
d91399d2e4c6acbeef9c0704043f269115bb688b
2,075
lawnchair
Apache License 2.0
src/main/kotlin/com/stepanov/bbf/bugfinder/AbiComparator/src/main/kotlin/org/jetbrains/kotlin/abicmp/reports/ComparisonReport.kt
DaniilStepanov
228,623,440
false
null
package org.jetbrains.kotlin.abicmp.reports import java.io.PrintWriter interface ComparisonReport { fun isEmpty(): Boolean fun write(output: PrintWriter) } fun ComparisonReport.isNotEmpty() = !isEmpty()
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
213
bbfgradle
Apache License 2.0
app/src/androidTest/java/ie/noel/dunsceal/persistence/db/TestData.kt
noelmcloughlin
219,187,323
false
{"Gradle": 4, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Proguard": 1, "XML": 94, "Kotlin": 65, "Java": 3}
package ie.noel.dunsceal.persistence.db import ie.noel.dunsceal.models.entity.Dun import ie.noel.dunsceal.models.entity.InvestigationEntity import java.util.* /** * Utility class that holds values to be used for testing. */ object TestData { val DUN_ENTITY = Dun(1, "name", "desc", 3) val DUN_ENTITY2 = Dun(2, "name2", "desc2", 20) val DUNS = Arrays.asList(DUN_ENTITY, DUN_ENTITY2) val INVESTIGATION_ENTITY = InvestigationEntity(1, DUN_ENTITY.id, "desc", Date()) val INVESTIGATION_ENTITY2 = InvestigationEntity(2, DUN_ENTITY2.id, "desc2", Date()) val INVESTIGATIONS = Arrays.asList(INVESTIGATION_ENTITY, INVESTIGATION_ENTITY2) }
0
Kotlin
0
1
8e94bd299b25a4bd659586c293908a7feed58337
656
DunSceal
Apache License 2.0
profilers-ui/testSrc/com/android/tools/profilers/cpu/analysis/CpuThreadSummaryDetailsViewTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.profilers.cpu.analysis import com.android.testutils.MockitoKt.whenever import com.android.tools.adtui.TreeWalker import com.android.tools.adtui.model.DefaultTimeline import com.android.tools.adtui.model.FakeTimer import com.android.tools.adtui.model.MultiSelectionModel import com.android.tools.adtui.model.Range import com.android.tools.idea.transport.faketransport.FakeGrpcServer import com.android.tools.idea.transport.faketransport.FakeTransportService import com.android.tools.profilers.FakeIdeProfilerComponents import com.android.tools.profilers.FakeIdeProfilerServices import com.android.tools.profilers.ProfilerClient import com.android.tools.profilers.SessionProfilersView import com.android.tools.profilers.StudioProfilers import com.android.tools.profilers.StudioProfilersView import com.android.tools.profilers.Utils import com.android.tools.profilers.cpu.CpuCapture import com.android.tools.profilers.cpu.CpuThreadInfo import com.android.tools.profilers.cpu.CpuThreadTrackModel import com.android.tools.profilers.cpu.config.ProfilingConfiguration.TraceType import com.android.tools.profilers.cpu.systemtrace.CpuSystemTraceData import com.google.common.truth.Truth.assertThat import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import java.util.concurrent.TimeUnit import javax.swing.JTable class CpuThreadSummaryDetailsViewTest { companion object { private val CAPTURE_RANGE = Range(0.0, Double.MAX_VALUE) } @get:Rule val applicationRule = ApplicationRule() @get:Rule val disposableRule = DisposableRule() private val timer = FakeTimer() private val transportService = FakeTransportService(timer, false) @get:Rule var grpcServer = FakeGrpcServer.createFakeGrpcServer("CpuThreadSummaryDetailsViewTest", transportService) private lateinit var profilersView: StudioProfilersView @Before fun setUp() { val profilers = StudioProfilers(ProfilerClient(grpcServer.channel), FakeIdeProfilerServices()) profilersView = SessionProfilersView(profilers, FakeIdeProfilerComponents(), disposableRule.disposable) } @Test fun componentsArePopulated() { val timeline = DefaultTimeline().apply { viewRange.set(TimeUnit.MILLISECONDS.toMicros(100).toDouble(), TimeUnit.MILLISECONDS.toMicros(200).toDouble()) } val cpuThreadTrackModel = CpuThreadTrackModel( Mockito.mock(CpuCapture::class.java), CpuThreadInfo(123, "foo"), timeline, MultiSelectionModel(), Utils::runOnUi) val model = CpuThreadAnalysisSummaryTabModel(CAPTURE_RANGE, timeline.viewRange).apply { dataSeries.add(cpuThreadTrackModel) } val view = CpuThreadSummaryDetailsView(profilersView, model) assertThat(view.timeRangeLabel.text).isEqualTo("00:00.100 - 00:00.200") assertThat(view.durationLabel.text).isEqualTo("100 ms") assertThat(view.dataTypeLabel.text).isEqualTo("Thread") assertThat(view.threadIdLabel.text).isEqualTo("123") } @Test fun rangeChangeUpdatesLabels() { val timeline = DefaultTimeline().apply { viewRange.set(0.0, 0.0) } val cpuThreadTrackModel = CpuThreadTrackModel( Mockito.mock(CpuCapture::class.java), CpuThreadInfo(123, "foo"), timeline, MultiSelectionModel(), Utils::runOnUi) val model = CpuThreadAnalysisSummaryTabModel(CAPTURE_RANGE, timeline.viewRange).apply { dataSeries.add(cpuThreadTrackModel) } val view = CpuThreadSummaryDetailsView(profilersView, model) assertThat(view.timeRangeLabel.text).isEqualTo("00:00.000 - 00:00.000") assertThat(view.durationLabel.text).isEqualTo("0 μs") timeline.viewRange.set(TimeUnit.SECONDS.toMicros(1).toDouble(), TimeUnit.SECONDS.toMicros(2).toDouble()) assertThat(view.timeRangeLabel.text).isEqualTo("00:01.000 - 00:02.000") assertThat(view.durationLabel.text).isEqualTo("1 s") } @Test fun threadStatesArePopulatedForSysTrace() { val timeline = DefaultTimeline().apply { viewRange.set(0.0, 0.0) } val sysTraceData = Mockito.mock(CpuSystemTraceData::class.java).apply { whenever(getThreadStatesForThread(123)).thenReturn(listOf()) } val sysTrace = Mockito.mock(CpuCapture::class.java).apply { whenever(type).thenReturn(TraceType.PERFETTO) whenever(systemTraceData).thenReturn(sysTraceData) } val cpuThreadTrackModel = CpuThreadTrackModel( sysTrace, CpuThreadInfo(123, "foo"), timeline, MultiSelectionModel(), Utils::runOnUi) val model = CpuThreadAnalysisSummaryTabModel(CAPTURE_RANGE, timeline.viewRange).apply { dataSeries.add(cpuThreadTrackModel) } val view = CpuThreadSummaryDetailsView(profilersView, model) assertThat(TreeWalker(view).descendants().filterIsInstance<JTable>()).isNotEmpty() } @Test fun threadStatesNotPopulatedForNonSysTrace() { val timeline = DefaultTimeline().apply { viewRange.set(0.0, 0.0) } val sysTrace = Mockito.mock(CpuCapture::class.java).apply { whenever(type).thenReturn(TraceType.ART) } val cpuThreadTrackModel = CpuThreadTrackModel( sysTrace, CpuThreadInfo(123, "foo"), timeline, MultiSelectionModel(), Utils::runOnUi) val model = CpuThreadAnalysisSummaryTabModel(CAPTURE_RANGE, timeline.viewRange).apply { dataSeries.add(cpuThreadTrackModel) } val view = CpuThreadSummaryDetailsView(profilersView, model) assertThat(TreeWalker(view).descendants().filterIsInstance<JTable>()).isEmpty() } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
6,267
android
Apache License 2.0
ref_code/leetcode-main/kotlin/1905-count-sub-islands.kt
yennanliu
66,194,791
false
{"Java": 5396849, "Python": 4422387, "JavaScript": 490755, "Kotlin": 464977, "C++": 351516, "C": 246034, "C#": 177156, "Rust": 152545, "Jupyter Notebook": 152285, "TypeScript": 139873, "Go": 129930, "Swift": 102644, "Ruby": 41941, "Scala": 34913, "Dart": 9957, "Shell": 4032, "Dockerfile": 2000, "PLpgSQL": 1348}
class Solution { fun countSubIslands(grid1: Array<IntArray>, grid2: Array<IntArray>): Int { fun isValid(i: Int, j: Int) = i in (0 until grid2.size) && j in (0 until grid2[0].size) && grid2[i][j] == 1 val dir = arrayOf( intArrayOf(1,0), intArrayOf(-1,0), intArrayOf(0,1), intArrayOf(0,-1) ) fun dfs(i: Int, j: Int): Boolean { if(grid1[i][j] != 1) return false grid2[i][j] = 0 var found = true for((iD,jD) in dir){ val iN = i + iD val jN = j + jD if(isValid(iN, jN)) found = found and dfs(iN, jN) } return found } var count = 0 for(i in 0 until grid1.size){ for(j in 0 until grid1[0].size){ if(grid1[i][j] == 1 && grid2[i][j] == 1) if(dfs(i, j) == true) count++ } } return count } }
0
Java
42
98
209db7daa15718f54f32316831ae269326865f40
1,098
CS_basics
The Unlicense
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/runner/LocatorBuilder.kt
myunusov
51,206,212
false
null
package org.maxur.mserv.frame.runner import org.maxur.mserv.frame.LocatorConfig import org.maxur.mserv.frame.LocatorImpl import org.maxur.mserv.frame.kotlin.Locator import java.util.concurrent.atomic.AtomicInteger /** * The Service Locator Builder. * * @author <NAME> * @version 1.0 * @since <pre>26.08.2017</pre> */ abstract class LocatorBuilder() { companion object { private var nameCount = AtomicInteger() } protected val name get() = "locator ${nameCount.andIncrement}" /** * List of project service packages for service locator lookup. */ var packages: Set<String> = setOf() /** * Build service locator. */ fun build(init: LocatorConfig.() -> Unit): Locator = try { val locator = make() locator.configure { bind(org.maxur.mserv.frame.kotlin.Locator(locator)) bind(org.maxur.mserv.frame.java.Locator(locator)) } locator.registerAsSingleton() configure(locator) { init() } org.maxur.mserv.frame.kotlin.Locator(locator) } catch (e: Exception) { Locator.current.onConfigurationError(e) } protected abstract fun make(): LocatorImpl protected abstract fun configure(locator: LocatorImpl, function: LocatorConfig.() -> Unit): LocatorConfig }
11
Kotlin
1
3
be46ed681423be3f07177c35776df094da1952c8
1,326
maxur-mserv
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/ui/experimental/meetNewUi/ActivateMeetNewUIToolWindowAction.kt
theronl
92,464,055
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui.experimental.meetNewUi import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ActivateToolWindowAction import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindowId import com.intellij.ui.ExperimentalUI class ActivateMeetNewUIToolWindowAction : ActivateToolWindowAction(ToolWindowId.MEET_NEW_UI) { override fun update(e: AnActionEvent) { if (ExperimentalUI.isNewUI() && Registry.`is`("ide.experimental.ui.meetNewUi")) { super.update(e) e.presentation.text = IdeBundle.message("meetnewui.toolwindow.title", ApplicationNamesInfo.getInstance().getFullProductName()) e.presentation.isVisible = e.place == ActionPlaces.MAIN_MENU if (SystemInfoRt.isMac) { e.presentation.icon = null } } else { e.presentation.isEnabledAndVisible = false } } }
1
null
1
1
e235ff43a541382b009c1e79a6df7b7cc0064306
1,213
intellij-community
Apache License 2.0
NameStats/app/src/main/java/com/egenvall/namestats/base/presentation/BaseView.kt
egenvall
83,654,398
false
null
package com.egenvall.namestats.base.presentation interface BaseView
1
Kotlin
1
1
f08348c811034d9b0fc24463bfef5e025bc98965
68
NameStats
MIT License
jvm/datasource/src/main/kotlin/InMemoryDataSource.kt
andygrove
333,252,270
false
null
// Copyright 2020 <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 org.ballistacompute.datasource import org.ballistacompute.datatypes.RecordBatch import org.ballistacompute.datatypes.Schema class InMemoryDataSource(val schema: Schema, val data: List<RecordBatch>) : DataSource { override fun schema(): Schema { return schema } override fun scan(projection: List<String>): Sequence<RecordBatch> { val projectionIndices = projection.map { name -> schema.fields.indexOfFirst { it.name == name } } return data.asSequence().map { batch -> RecordBatch(schema, projectionIndices.map { i -> batch.field(i) }) } } }
3
null
12
72
9c27d475b62e3a4eccec4236e2fe60eb3f13e757
1,171
how-query-engines-work
Apache License 2.0
Sample/src/main/kotlin/sample/data/DataSource.kt
oneHamidreza
239,642,692
false
null
/* * Copyright (C) 2020 <NAME> & <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 sample.data import android.text.Spanned import meow.core.arch.DataSourceInterface import meow.core.data.MeowSharedPreferences import meow.ktx.ofPair import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.erased.instance import retrofit2.create import sample.App import sample.data.catbreed.CatBreed import sample.data.user.User import sample.di.AppApi import sample.widget.createMarkwon import sample.widget.githubRaw /** * The Data Source class. * * @author <NAME> * @version 1.0.0 * @since 2020-03-06 */ class DataSource(override var app: App) : DataSourceInterface, KodeinAware { override val kodein by closestKodein(app) private val api: AppApi by instance<AppApi>() private val spMain: MeowSharedPreferences by instance<MeowSharedPreferences>("spMain") private val spUpdate: MeowSharedPreferences by instance<MeowSharedPreferences>("spUpdate") suspend fun postLoginToApi(request: User.Api.RequestLogin) = api.createServiceByAdapter<User.Api>().login(request.username, request.password) suspend fun getCatBreedsFromApi() = api.createServiceByAdapter<CatBreed.Api>().getCatBreedIndex() suspend fun getCatBreedFromApi() = api.createServiceByAdapter<CatBreed.Api>().getCatBreedDetail() suspend fun postCatBreedToApi(request: CatBreed.Api.RequestCreate) = api.createServiceByAdapter<CatBreed.Api>().createCatBreed(request.name) suspend fun getMarkdownFromApi(path: String): Pair<String, Spanned> { val raw = api.createScalersService().create<GithubApi>().getFileAsString(path.githubRaw()) return ofPair(raw, app.createMarkwon().toMarkdown(raw)) } fun isLogin() = fetchApiToken().isNotEmpty() fun fetchUser() = spMain.get("user", User()) fun saveUser(it: User) = spMain.put("user", it) fun fetchApiToken() = spMain.get("apiToken", "") fun saveApiToken(it: String) = spMain.put("apiToken", it) fun fetchApiRefreshToken() = spMain.get("apiRefreshToken", "") fun saveApiRefreshToken(it: String) = spMain.put("apiRefreshToken", it) fun fetchMarkdownData(key: String) = spMain.get("markdown_$key", "") fun saveMarkdownData(key: String, it: String) = spMain.put("markdown_$key", it) }
0
Kotlin
18
124
deb3efbe8079d784d5850870b7b54ffc9721ffb4
2,880
Meow-Framework-MVVM
Apache License 2.0
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/github/autoversioning/GitHubPostProcessingSettingsExtensions.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.kdsl.spec.extension.github.autoversioning import net.nemerosa.ontrack.kdsl.spec.settings.SettingsInterface import net.nemerosa.ontrack.kdsl.spec.settings.SettingsMgt val SettingsMgt.gitHubPostProcessing: SettingsInterface<GitHubPostProcessingSettings> get() = SettingsInterface( connector = connector, id = "github-av-post-processing", type = GitHubPostProcessingSettings::class, )
57
null
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
445
ontrack
MIT License
src/app/src/test/kotlin/org/vaccineimpact/api/tests/logic/ResponsibilitiesLogicTests.kt
vimc
85,062,678
false
null
package org.vaccineimpact.api.tests.logic import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.vaccineimpact.api.app.controllers.helpers.ResponsibilityPath import org.vaccineimpact.api.app.errors.UnknownObjectError import org.vaccineimpact.api.app.logic.RepositoriesResponsibilitiesLogic import org.vaccineimpact.api.app.repositories.* import org.vaccineimpact.api.models.* import org.vaccineimpact.api.models.responsibilities.* import org.vaccineimpact.api.test_helpers.MontaguTests import java.time.Instant class ResponsibilitiesLogicTests : MontaguTests() { private val groupId = "group-1" private val touchstoneVersionId = "touchstone-1" private val scenarioId = "scenario-1" @Test fun `can validate Responsibility Path`() { val path = ResponsibilityPath(groupId, touchstoneVersionId, scenarioId) val statusList = mutableListOf(TouchstoneStatus.OPEN, TouchstoneStatus.FINISHED) val groupRepo = mock<ModellingGroupRepository>() val touchstoneVersion = TouchstoneVersion(touchstoneVersionId, "touchstone", 1, "description", TouchstoneStatus.OPEN) val mockTouchstoneVersions = mock<SimpleDataSet<TouchstoneVersion, String>> { on { get(touchstoneVersionId) } doReturn touchstoneVersion } val scenarioRepo = mock<ScenarioRepository>() val touchstoneRepo = mock<TouchstoneRepository> { on { touchstoneVersions } doReturn mockTouchstoneVersions } val sut = RepositoriesResponsibilitiesLogic(groupRepo, scenarioRepo, touchstoneRepo, mock(), mock()) sut.validateResponsibilityPath(path, statusList) verify(groupRepo).getModellingGroup(groupId) verify(touchstoneRepo).touchstoneVersions verify(mockTouchstoneVersions).get(touchstoneVersionId) verify(scenarioRepo).checkScenarioDescriptionExists(scenarioId) } @Test fun `throws UnknownObjectError when validating Responsibility Path if touchstone status is not in allowable list`() { val path = ResponsibilityPath(groupId, touchstoneVersionId, scenarioId) val statusList = mutableListOf(TouchstoneStatus.OPEN, TouchstoneStatus.FINISHED) val touchstoneVersion = TouchstoneVersion(touchstoneVersionId, "touchstone", 1, "description", TouchstoneStatus.IN_PREPARATION) val mockTouchstoneVersions = mock<SimpleDataSet<TouchstoneVersion, String>> { on { get(touchstoneVersionId) } doReturn touchstoneVersion } val touchstoneRepo = mock<TouchstoneRepository> { on { touchstoneVersions } doReturn mockTouchstoneVersions } val sut = RepositoriesResponsibilitiesLogic(mock(), mock(), touchstoneRepo, mock(), mock()) Assertions.assertThatThrownBy { sut.validateResponsibilityPath(path, statusList) }.isInstanceOf(UnknownObjectError::class.java).hasMessageContaining("Unknown touchstone-version with id 'touchstone-1'") } @Test fun `can get data`() { val oldUploadedOn = Instant.now() val uploadedOn = Instant.now() val commentedOn = uploadedOn.minusMillis(1) val testResponsibilitiesWithComments = listOf( ResponsibilityWithComment(scenarioId, ResponsibilityComment("Note for VIMC, Campaign, Cholera for 202002rfp-1", "test.user2", commentedOn)) ) val responsibilitiesRepo = mock<ResponsibilitiesRepository> { on { getResponsibilitiesWithCommentsForTouchstone(touchstoneVersionId) } doReturn listOf( ResponsibilitySetWithComments(touchstoneVersionId, groupId, ResponsibilityComment("Note for VIMC for 202002rfp-1", "test.user", uploadedOn), testResponsibilitiesWithComments) ) // Declare that this touchstone has a single responsibility set containing a single responsibility // Let current burden estimate set be null because these are retrieved with a separate call on { getResponsibilitiesForTouchstone(touchstoneVersionId) } doReturn listOf( ResponsibilitySet(touchstoneVersionId, groupId, ResponsibilitySetStatus.INCOMPLETE, listOf( Responsibility( Scenario(scenarioId, "Default - Campaign", "Cholera", listOf("202002rfp")), ResponsibilityStatus.EMPTY, emptyList(), null ) )) ) } val burdenEstimateRepository = mock<BurdenEstimateRepository> { on { getBurdenEstimateSets(groupId, touchstoneVersionId, scenarioId) } doReturn listOf( BurdenEstimateSet( 2, uploadedOn, "test.user", BurdenEstimateSetType(BurdenEstimateSetTypeCode.CENTRAL_SINGLE_RUN, "time varying CFR"), BurdenEstimateSetStatus.PARTIAL, listOf("Data is corrupt", "Results are meaningless"), null), BurdenEstimateSet( 1, oldUploadedOn, "another.test.user", BurdenEstimateSetType(BurdenEstimateSetTypeCode.CENTRAL_AVERAGED, "averaged"), BurdenEstimateSetStatus.COMPLETE, listOf(), "originalFile.csv")) } val sut = RepositoriesResponsibilitiesLogic(mock(), mock(), mock(), responsibilitiesRepo, burdenEstimateRepository) val result = sut.getTouchstoneResponsibilitiesData(touchstoneVersionId) assertThat(result).isEqualTo(listOf( ResponsibilityRow( touchstoneVersionId, groupId, 1, "Note for VIMC for 202002rfp-1", uploadedOn, "test.user", "Default - Campaign", "Cholera", 2, uploadedOn, "test.user", BurdenEstimateSetTypeCode.CENTRAL_SINGLE_RUN, "time varying CFR", BurdenEstimateSetStatus.PARTIAL, "Data is corrupt, Results are meaningless", "Note for VIMC, Campaign, Cholera for 202002rfp-1", commentedOn, "test.user2" ), ResponsibilityRow( touchstoneVersionId, groupId, 1, "Note for VIMC for 202002rfp-1", uploadedOn, "test.user", "Default - Campaign", "Cholera", 1, oldUploadedOn, "another.test.user", BurdenEstimateSetTypeCode.CENTRAL_AVERAGED, "averaged", BurdenEstimateSetStatus.COMPLETE, "", "Note for VIMC, Campaign, Cholera for 202002rfp-1", commentedOn, "test.user2" ) )) } }
1
null
1
2
0b3acb5f22b71300d6c260c5ecb252b0bddbe6ea
7,835
montagu-api
MIT License
cli/src/commonMain/me/strangepan/tasks/cli/feature/init/InitCommand.kt
StrangePan
231,948,379
false
null
package me.strangepan.tasks.cli.feature.init import me.strangepan.tasks.cli.command.Command import omnia.data.cache.Memoized import omnia.data.structure.immutable.ImmutableList /** Canonical definition for the Init command. */ object InitCommand { fun registration() : Command { return COMMAND.value } private val COMMAND: Memoized<Command> = Memoized.memoize { Command.builder() .canonicalName("init") .aliases() .parameters(ImmutableList.empty()) .options(ImmutableList.empty()) .helpDocumentation("Initializes a new task store in the current directory if one does not " + "already exist.") } }
0
Kotlin
0
3
2fa1fab9a48ed66668c5e58410488f9f0b5d0083
695
tasks
The Unlicense
app/src/main/java/com/movieapp/kotlin/domain/usecases/core/UseCasePrimary.kt
MustafaKhaled
215,221,089
false
null
package com.movieapp.kotlin.domain.usecases.core import android.content.IntentSender import android.hardware.camera2.CaptureFailure import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.internal.operators.single.SingleDoOnSuccess import io.reactivex.schedulers.Schedulers abstract class UseCasePrimary<T> : UseCaseDisposables() { internal abstract fun buildUseCasePrimary() : Single<T> fun execute( onSuccess: ((t: T) -> Unit), onFailure: ((t: Throwable) -> Unit), onFinished: () -> Unit = {} ){ disposeLast() lastDisposable = buildUseCasePrimary().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate(onFinished) .subscribe(onSuccess, onFailure) lastDisposable?.let { compositeDisposable.add(it) } } }
0
Kotlin
0
1
55b09c817da5d0733058d7aec1b508e2c78963de
914
MovieApp
MIT License
compiler/testData/codegen/box/wasm-new-exception-handling/finally10.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // TARGET_BACKEND: WASM // USE_NEW_EXCEPTION_HANDLING_PROPOSAL // TODO: remove the test when KT-66906 will be resolved import kotlin.test.* val sb = StringBuilder() fun box(): String { while (true) { try { continue } finally { sb.appendLine("Finally") break } } sb.appendLine("After") assertEquals(""" Finally After """.trimIndent(), sb.toString()) return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
483
kotlin
Apache License 2.0
core_view/src/main/java/com/turtleteam/core_view/navigation/BottomNavigationBar.kt
Egor-Liadsky
711,194,733
false
{"Kotlin": 188247}
package com.turtleteam.core_view.navigation import androidx.annotation.DrawableRes import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.turtleteam.core_view.theme.TurtleTheme data class NavigationItem( val route: String, @DrawableRes val icon: Int ) @Composable fun BottomNavigationBar( currentRoute: String?, routes: List<NavigationItem>, onClick: (route: String) -> Unit ) { var lastSelectedBtn by rememberSaveable { mutableStateOf(currentRoute) } BottomNavigation( modifier = Modifier .fillMaxWidth() .background(TurtleTheme.color.bottomNavBarGradient), backgroundColor = Color.Transparent, elevation = 0.dp ) { routes.forEach { item -> BottomNavigationItem( selected = lastSelectedBtn == item.route, onClick = { if (routes.map { it.route }.contains(currentRoute)) onClick(item.route) }, icon = { Icon( painter = painterResource(id = item.icon), contentDescription = "", tint = if (lastSelectedBtn == item.route) TurtleTheme.color.bottomNavMenuColors.getColor(true) else TurtleTheme.color.bottomNavMenuColors.getColor(false) , modifier = Modifier.size(24.dp) ) }) } } LaunchedEffect(key1 = currentRoute, block = { if (routes.map { it.route }.contains(currentRoute)) lastSelectedBtn = currentRoute }) }
0
Kotlin
0
0
bbf8d1a4220fd781fb2ca007b7b7774e7bbb725d
2,313
TurtleAppAndroid
Apache License 2.0
sample-compose/src/main/java/com/mmolosay/sample/compose/custom/CustomArgumentsExt.kt
mmolosay
519,758,730
false
null
package com.mmolosay.sample.compose.custom import com.mmolosay.stringannotations.args.Arguments import com.mmolosay.stringannotations.args.emptyArguments import com.mmolosay.stringannotations.compose.ComposeArguments /** * Assembles [Arguments] with [CustomArguments] in declarative style. */ fun CustomArguments( base: ComposeArguments = emptyArguments(), scope: CustomArgumentsBuilder.() -> Unit ): CustomArguments = CustomArgumentsBuilder().apply(scope).build(base)
0
Kotlin
0
1
8b07132f0e923768bee413a3815914043f852ea8
485
StringAnnotations
Apache License 2.0
composeApp/src/desktopMain/kotlin/Gobblet.desktop.kt
joaomanaia
700,458,525
false
{"Kotlin": 103059, "HTML": 373, "Shell": 228}
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.runtime.* import androidx.compose.ui.window.ApplicationScope import androidx.compose.ui.window.Window import presentation.App @Composable @OptIn(ExperimentalMaterial3Api::class) fun ApplicationScope.GobbletDesktop() { Window(onCloseRequest = ::exitApplication, title = "Gobblet") { App() } }
0
Kotlin
0
1
db8658ed90dd7fc55df2041d9e23f44d9c213293
392
compose-gobblet
Apache License 2.0
app/src/main/java/teka/android/chamaaapp/data/remote/services/LoanRetrofitService.kt
samAricha
759,726,734
false
{"Kotlin": 368851}
package teka.android.chamaaapp.data.remote.services import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import teka.android.chamaaapp.data.models.MemberRequest import teka.android.chamaaapp.data.remote.dtos.ApiResponseHandler import teka.android.chamaaapp.data.remote.dtos.LoanDTO import teka.android.chamaaapp.data.room_remote_sync.models.FetchMembersResponse import teka.android.chamaaapp.data.room_remote_sync.models.UploadDataResponse interface LoanRetrofitService { @GET("api/loans") suspend fun getLoans():ApiResponseHandler<List<LoanDTO>> @POST("api/loans") suspend fun backupLoanEntity(@Body loanDTO: LoanDTO): ApiResponseHandler<LoanDTO> }
0
Kotlin
0
1
72c9892e0bec64f082d0c237da58be9cc6822194
700
ChamaYetu
The Unlicense
src/main/kotlin/com/github/cucapra/ide/completion/ProvideSymbol.kt
oovm
512,684,025
false
{"Kotlin": 55640, "SystemVerilog": 37944, "Lex": 2137, "HTML": 62}
package com.github.cucapra.ide.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.util.ProcessingContext class ProvideSymbol : CompletionProvider<CompletionParameters>() { override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, resultSet: CompletionResultSet ) { resultSet.addElement( LookupElementBuilder.create("@include") .withInsertHandler { ctx, _ -> EditorModificationUtil.moveCaretRelatively(ctx.editor, -1) } ) resultSet.addElement( LookupElementBuilder.create("@inherit") .withInsertHandler { ctx, _ -> EditorModificationUtil.moveCaretRelatively(ctx.editor, -1) } ) } }
0
Kotlin
0
0
e3d6c6d5299886775fc0e594de0abd768e67b17b
1,098
calyx-intellij
Apache License 2.0
app/src/main/java/com/kumcompany/uptime/MainActivity.kt
pluzarev-nemanja
769,557,772
false
{"Kotlin": 106416}
package com.kumcompany.uptime import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Surface import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.lifecycle.lifecycleScope import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.kumcompany.uptime.domain.use_cases.UseCases import com.kumcompany.uptime.navigation.routes.Graphs import com.kumcompany.uptime.navigation.graphs.RootNavGraph import com.kumcompany.uptime.ui.theme.UpTimeTheme import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { private lateinit var navController: NavHostController @Inject lateinit var useCases: UseCases private var completed = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() setContent { UpTimeTheme { Surface { navController = rememberNavController() RootNavGraph( navController = navController, startDestination = if (completed) Graphs.MAIN.route else Graphs.WELCOME.route ) } } } lifecycleScope.launch(Dispatchers.IO) { useCases.readOnBoardingUseCase().collect { completed = it } } } }
0
Kotlin
0
0
3f623c7f1bc334327b461e1af7026d454efe62dd
1,664
UpTime
MIT License
app/src/main/java/de/leonsuv/stundenplan/screen/SettingsScreen.kt
leonsuv
582,297,692
false
null
package de.leonsuv.stundenplan.screen import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import com.example.stundenplan.R @Composable fun SettingsScreen(padding: PaddingValues) { Box( modifier = Modifier .fillMaxSize() .padding(padding) ) { Icon( painter = painterResource(id = R.drawable.logo_phwt), contentDescription = null ) } }
0
Kotlin
0
0
679929c479d01036bfa004c50c31858e33c27745
738
stundenplan
Apache License 2.0
src/commonTest/kotlin/baaahs/gl/shader/dialect/IsfShaderDialectSpec.kt
baaahs
174,897,412
false
{"Kotlin": 3355751, "C": 1529197, "C++": 661364, "GLSL": 412680, "JavaScript": 62186, "HTML": 55088, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.gl.shader.dialect import baaahs.describe import baaahs.gl.glsl.GlslError import baaahs.gl.glsl.GlslType import baaahs.gl.override import baaahs.gl.patch.ContentType import baaahs.gl.shader.InputPort import baaahs.gl.shader.OutputPort import baaahs.gl.testToolchain import baaahs.plugin.PluginRef import baaahs.toBeSpecified import baaahs.toEqual import ch.tutteli.atrium.api.fluent.en_GB.contains import ch.tutteli.atrium.api.fluent.en_GB.containsExactly import ch.tutteli.atrium.api.fluent.en_GB.toBe import ch.tutteli.atrium.api.verbs.expect import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import org.spekframework.spek2.Spek @Suppress("unused") object IsfShaderDialectSpec : Spek({ describe<IsfShaderDialect> { val fileName by value<String?> { null } val src by value<String> { toBeSpecified() } val dialect by value { IsfShaderDialect } val glslCode by value { testToolchain.parse(src, fileName) } val analyzer by value { dialect.match(glslCode, testToolchain.plugins) } val matchLevel by value { analyzer.matchLevel } val shaderAnalysis by value { analyzer.analyze() } val openShader by value { testToolchain.openShader(shaderAnalysis) } context("a shader having an ISF block at the top") { override(fileName) { "Float Input.fs" } override(src) { """ /*{ "DESCRIPTION": "Demonstrates a float input", "CREDIT": "by VIDVOX", "ISFVSN": "2.0", "CATEGORIES": [ "TEST-GLSL" ], "INPUTS": [ { "NAME": "level", "TYPE": "float", "LABEL": "Gray Level", "DEFAULT": 0.5, "MIN": 0.0, "MAX": 1.0 } ] }*/ void main() { gl_FragColor = vec4(level,level,level,1.0); } """.trimIndent() } it("is an excellent match") { expect(matchLevel).toEqual(MatchLevel.Excellent) } it("gets its title from the file name") { expect(openShader.title).toEqual("Float Input") } it("finds the input port") { expect(openShader.inputPorts).containsExactly( InputPort( "level", ContentType.Float, GlslType.Float, "Gray Level", pluginRef = PluginRef("baaahs.Core", "Slider"), pluginConfig = buildJsonObject { put("min", JsonPrimitive(0f)) put("max", JsonPrimitive(1f)) put("default", JsonPrimitive(.5f)) }, isImplicit = true ) ) } it("finds the output port") { expect(shaderAnalysis.outputPorts).containsExactly( OutputPort(ContentType.Color, description = "Output Color", id = "gl_FragColor") ) } context("when a shader refers to gl_FragCoord") { override(src) { """ /*{}*/ void main() { gl_FragColor = vec4(gl_FragCoord.xy, 0., 1.); } """.trimIndent() } it("includes it as an input port") { expect(openShader.inputPorts).containsExactly( InputPort( "gl_FragCoord", ContentType.UvCoordinate, GlslType.Vec4, "Coordinates", isImplicit = true ) ) } } context("when a shader refers to isf_FragNormCoord") { override(src) { """ /*{ }*/ void main() { gl_FragColor = vec4(isf_FragNormCoord.xy, 0., 1.); } """.trimIndent() } it("includes it as an input port") { expect(openShader.inputPorts).containsExactly( InputPort( "isf_FragNormCoord", ContentType.UvCoordinate, GlslType.Vec2, "U/V Coordinate", isImplicit = true ) ) } } context("using TIME") { override(src) { """ /*{ }*/ void main() { gl_FragColor = vec4(TIME, TIME, TIME, 0.); } """.trimIndent() } it("includes it as an input port") { expect(openShader.inputPorts).containsExactly( InputPort("TIME", ContentType.Time, GlslType.Float, "Time", isImplicit = true) ) } context("from the right hand side of a global variable") { override(src) { """ /*{ }*/ float theTime = TIME; """.trimIndent() } it("includes it as an input port") { expect(openShader.inputPorts).containsExactly( InputPort("TIME", ContentType.Time, GlslType.Float, "Time", isImplicit = true) ) } } } context("with multiple out parameters") { override(src) { "void main(in vec2 fragCoord, out vec4 fragColor, out float other) { gl_FragColor = vec4(gl_FragCoord, 0., 1.); };" } it("fails to validate") { expect(shaderAnalysis.isValid).toBe(false) expect(shaderAnalysis.errors).contains( GlslError("Too many output ports found: [fragColor, gl_FragColor, other].", row = 1) ) } } context("which isn't valid JSON") { override(src) { """ /*{ "DESC }*/ void main() { gl_FragColor = vec4(level,level,level,1.0); } """.trimIndent() } it("fails to validate") { expect(shaderAnalysis.isValid).toBe(false) expect(shaderAnalysis.errors).containsExactly( GlslError("Unexpected JSON token at offset 2: Expected quotation mark '\"', but had '\"' instead at path: \$\n" + "JSON input: { \"DESC }", 1) ) } } } context("a shader without an ISF block at the top") { override(src) { "void main() {\n gl_FragColor = vec4(level,level,level,1.0);\n}" } it("is not a match") { expect(matchLevel).toEqual(MatchLevel.NoMatch) } } } })
88
Kotlin
6
40
4dd92e5859d743ed7186caa55409f676d6408c95
7,655
sparklemotion
MIT License
src/integrationTest/kotlin/com/malinskiy/adam/integration/TestRunnerE2ETest.kt
fkorotkov
264,860,000
true
{"Kotlin": 150912, "Shell": 1466}
/* * Copyright (C) 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.malinskiy.adam.integration import com.malinskiy.adam.request.sync.InstallRemotePackageRequest import com.malinskiy.adam.request.sync.PushFileRequest import com.malinskiy.adam.request.testrunner.InstrumentOptions import com.malinskiy.adam.request.testrunner.TestRunnerRequest import com.malinskiy.adam.rule.AdbDeviceRule import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.Test import java.io.File import kotlin.math.roundToInt class TestRunnerE2ETest { @get:Rule @JvmField val rule = AdbDeviceRule() @Test fun test1() { val apk = File(javaClass.getResource("/app-debug.apk").toURI()) val testApk = File(javaClass.getResource("/app-debug-androidTest.apk").toURI()) val apkFileName = apk.name val testApkFileName = testApk.name runBlocking { installApk(apk, apkFileName) installApk(testApk, testApkFileName) val channel = rule.adb.execute( TestRunnerRequest( "com.example.test", InstrumentOptions( clazz = listOf("com.example.AbstractFailingTest") ) ), serial = rule.deviceSerial, scope = GlobalScope ) var logPart: String? = null do { logPart?.let { print(it) } logPart = channel.receiveOrNull() } while (logPart != null) println() } } private suspend fun installApk(apk: File, apkFileName: String) { val channel = rule.adb.execute(PushFileRequest(apk, "/data/local/tmp/$apkFileName"), GlobalScope, serial = rule.deviceSerial) var percentage = 0 while (!channel.isClosedForReceive) { val percentageDouble = channel.receiveOrNull() ?: break val newPercentage = (percentageDouble * 100).roundToInt() if (newPercentage != percentage) { print('.') percentage = newPercentage } } println() val result = rule.adb.execute( InstallRemotePackageRequest("/data/local/tmp/$apkFileName", true), serial = rule.deviceSerial ) } }
0
null
0
0
4bab3148192036abdd6a8a9be076cc6aed3a3cef
2,908
adam
Apache License 2.0
utbot-framework-test/src/test/kotlin/org/utbot/examples/casts/GenericCastExampleTest.kt
UnitTestBot
480,810,501
false
null
package org.utbot.examples.casts import org.junit.jupiter.api.Test import org.utbot.testcheckers.eq import org.utbot.testing.DoNotCalculate import org.utbot.testing.UtValueTestCaseChecker import org.utbot.testing.between // TODO failed Kotlin compilation SAT-1332 internal class GenericCastExampleTest : UtValueTestCaseChecker( testClass = GenericCastExample::class, testCodeGeneration = true, configurations = ignoreKotlinCompilationConfigurations, ) { @Test fun testCompareTwoNumbers() { check( GenericCastExample::compareTwoNumbers, eq(5), { a, _, _ -> a == null }, { _, b, _ -> b == null }, { _, b, _ -> b.comparableGenericField == null }, { a, b, r -> a >= b.comparableGenericField && r == 1 }, { a, b, r -> a < b.comparableGenericField && r == -1 }, coverage = DoNotCalculate ) } @Test fun testGetGenericFieldValue() { check( GenericCastExample::getGenericFieldValue, eq(3), { g, _ -> g == null }, { g, _ -> g.genericField == null }, { g, r -> g?.genericField != null && r == g.genericField }, ) } @Test fun testCompareGenericField() { check( GenericCastExample::compareGenericField, between(4..5), { g, _, _ -> g == null }, { g, v, _ -> g != null && v == null }, { g, v, r -> v != null && v != g.comparableGenericField && r == -1 }, { g, v, r -> g.comparableGenericField is Int && v != null && v == g.comparableGenericField && r == 1 }, coverage = DoNotCalculate // TODO because of kryo exception: Buffer underflow. ) } @Test fun testCreateNewGenericObject() { check( GenericCastExample::createNewGenericObject, eq(1), { r -> r is Int && r == 10 }, ) } @Test fun testSumFromArrayOfGenerics() { check( GenericCastExample::sumFromArrayOfGenerics, eq(7), { g, _ -> g == null }, { g, _ -> g.genericArray == null }, { g, _ -> g.genericArray.isEmpty() }, { g, _ -> g.genericArray.size == 1 }, { g, _ -> g.genericArray[0] == null }, { g, _ -> g.genericArray[0] != null && g.genericArray[1] == null }, { g, r -> g.genericArray[0] != null && g.genericArray[1] != null && r == g.genericArray[0] + g.genericArray[1] }, ) } }
398
Kotlin
32
91
abb62682c70d7d2ecc4ad610851d304f7ad716e4
2,562
UTBotJava
Apache License 2.0
data/src/test/java/com/bottlerocketstudios/brarchitecture/data/model/FeatureToggleTest.kt
BottleRocketStudios
323,985,026
false
null
package com.bottlerocketstudios.brarchitecture.data.model import com.bottlerocketstudios.brarchitecture.data.test.BaseTest import com.bottlerocketstudios.brarchitecture.domain.models.FeatureToggle import com.bottlerocketstudios.brarchitecture.domain.models.isValueOverridden import com.google.common.truth.Truth.assertThat import org.junit.Test class FeatureToggleTest : BaseTest() { @Test fun featureToggle_defaultFields_whenDefaultConstructor() { val featureToggle = FeatureToggle.ToggleValueBoolean(name = "SHOW_PULL_REQUESTS", value = true, defaultValue = true, requireRestart = false) assertThat(featureToggle.name).isNotNull() assertThat(featureToggle.value).isNotNull() assertThat(featureToggle.defaultValue).isNotNull() assertThat(featureToggle.requireRestart).isNotNull() } @Test fun featureToggle_toggleOverridden_false() { val featureToggle = FeatureToggle.ToggleValueBoolean(name = "SHOW_PULL_REQUESTS", value = true, defaultValue = true, requireRestart = true) assertThat(featureToggle.isValueOverridden()).isFalse() } @Test fun featureToggle_toggleOverridden_true() { val featureToggle = FeatureToggle.ToggleValueBoolean(name = "SHOW_PULL_REQUESTS", value = false, defaultValue = true, requireRestart = true) assertThat(featureToggle.isValueOverridden()).isTrue() } }
1
Kotlin
1
9
e8541ccaa52782c5c2440b8a4fe861ef9178111e
1,395
Android-ArchitectureDemo
Apache License 2.0
app/src/main/java/com/example/weathermvvm/data/provider/LocationProviderImpl.kt
dlt96
182,993,941
false
null
package com.example.weathermvvm.data.provider import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.location.Location import androidx.core.content.ContextCompat import com.example.weathermvvm.data.db.entity.WeatherLocation import com.example.weathermvvm.internal.LocationPermissionNotGrantedException import com.example.weathermvvm.internal.asDeferred import com.google.android.gms.location.FusedLocationProviderClient import kotlinx.coroutines.Deferred const val USE_DEVICE_LOCATION = "USE_DEVICE_LOCATION" const val CUSTOM_LOCATION = "CUSTOM_LOCATION" class LocationProviderImpl( private val fusedLocationProviderClient: FusedLocationProviderClient, context: Context ) : PreferencesProvider(context), LocationProvider { private val appContext = context.applicationContext override suspend fun hasLocationChanged(lastWeatherLocation: WeatherLocation): Boolean { val deviceLocationChanged = try { hasDeviceLocationChanged(lastWeatherLocation) } catch (e: LocationPermissionNotGrantedException) { false } return deviceLocationChanged || hasCustomLocationChanged(lastWeatherLocation) } override suspend fun getPreferredLocationsString(): String { if (isUsingDeviceLocation()) { try { val deviceLocation = getLastDeviceLocation().await() ?: return "${getCustomLocationName()}" return "${deviceLocation.latitude},${deviceLocation.longitude}" } catch (e: LocationPermissionNotGrantedException) { return "${getCustomLocationName()}" } } else return "${getCustomLocationName()}" } private suspend fun hasDeviceLocationChanged(lastWeatherLocation: WeatherLocation): Boolean { if (!isUsingDeviceLocation()) return false val deviceLocation = getLastDeviceLocation().await() ?: return false val comparisonThreshold = 0.03 return Math.abs(deviceLocation.latitude - lastWeatherLocation.lat) > comparisonThreshold && Math.abs(deviceLocation.longitude - lastWeatherLocation.lon) > comparisonThreshold } private fun hasCustomLocationChanged(lastWeatherLocation: WeatherLocation): Boolean { if (!isUsingDeviceLocation()) { val customLocationName = getCustomLocationName() return customLocationName != lastWeatherLocation.name } return false } private fun getCustomLocationName(): String? { return preferences.getString(CUSTOM_LOCATION, null) } private fun isUsingDeviceLocation(): Boolean { return preferences.getBoolean(USE_DEVICE_LOCATION, true) } @SuppressLint("MissingPermission") private fun getLastDeviceLocation(): Deferred<Location?> { return if (hasLocationPermission()) fusedLocationProviderClient.lastLocation.asDeferred() else throw LocationPermissionNotGrantedException() } private fun hasLocationPermission(): Boolean { return ContextCompat.checkSelfPermission( appContext, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED } }
0
Kotlin
0
0
aad2bb137a4ab7361894ce1ce231c6eba5058cf2
3,354
CoroutinesArchitectureComponents
Apache License 2.0
app/src/main/java/com/example/gamebuddy/presentation/main/joincommunity/JoinCommunityViewModel.kt
GameBuddyDevs
609,491,782
false
null
package com.example.gamebuddy.presentation.main.joincommunity import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.gamebuddy.domain.usecase.community.GetCommunitiesUseCase import com.example.gamebuddy.domain.usecase.community.JoinCommunityUseCase import com.example.gamebuddy.domain.usecase.community.LeaveCommunityUseCase import com.example.gamebuddy.util.StateMessage import com.example.gamebuddy.util.UIComponentType import com.example.gamebuddy.util.doesMessageAlreadyExistInQueue import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import timber.log.Timber import javax.inject.Inject @HiltViewModel class JoinCommunityViewModel @Inject constructor( private val getCommunitiesUseCase: GetCommunitiesUseCase, private val joinCommunityUseCase: JoinCommunityUseCase ): ViewModel() { private val _uiState: MutableLiveData<JoinCommunityState> = MutableLiveData(JoinCommunityState()) val uiState: MutableLiveData<JoinCommunityState> get() = _uiState init { onTriggerEvent(JoinCommunityEvent.GetCommunities) } fun onTriggerEvent(event: JoinCommunityEvent){ when (event) { is JoinCommunityEvent.GetCommunities -> getCommunities() is JoinCommunityEvent.JoinCommunity -> joinCommunityUseCase(event.communityId) JoinCommunityEvent.OnRemoveHeadFromQueue -> onRemoveHeadFromQueue() } } private fun joinCommunityUseCase(communityId: String) { _uiState.value?.let { state -> joinCommunityUseCase.execute(communityId).onEach { dataState -> _uiState.value = state.copy(isLoading = dataState.isLoading) // dataState.data?.let { isFollowing -> // _uiState.value = state.copy(isFollowing = isFollowing) // } dataState.stateMessage?.let { stateMessage -> appendToMessageQueue(stateMessage) } }.launchIn(viewModelScope) } } private fun getCommunities() { _uiState.value?.let { state -> getCommunitiesUseCase.execute().onEach { dataState -> _uiState.value = state.copy(isLoading = dataState.isLoading) dataState.data?.let { communities -> _uiState.value = state.copy(communities = communities) } dataState.stateMessage?.let { stateMessage -> appendToMessageQueue(stateMessage) } }.launchIn(viewModelScope) } } private fun onRemoveHeadFromQueue() { _uiState.value?.let { state -> try { val queue = state.queue queue.remove() // can throw exception if empty _uiState.value = state.copy(queue = queue) } catch (e: Exception) { Timber.d("removeHeadFromQueue: Nothing to remove from DialogQueue") } } } private fun appendToMessageQueue(stateMessage: StateMessage) { _uiState.value?.let { state -> val queue = state.queue if (!stateMessage.doesMessageAlreadyExistInQueue(queue = queue)) { if (stateMessage.response.uiComponentType !is UIComponentType.None) { queue.add(stateMessage) _uiState.value = state.copy(queue = queue) } } } } }
0
Kotlin
1
3
0a767229f5505e6a68e167aece41c10abb282e1b
3,568
GameBuddy-Android
MIT License
gradle-dsl-declarative/src/com/android/tools/idea/gradle/dsl/parser/declarative/DeclarativeDslTransformerFactory.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.dsl.parser.declarative import com.android.tools.idea.gradle.dsl.model.BuildModelContext import com.android.tools.idea.gradle.dsl.parser.GradleDslTransformerFactory import com.android.tools.idea.gradle.dsl.parser.files.GradleDslFile import com.android.tools.idea.gradle.dcl.lang.psi.DeclarativeFile import com.intellij.psi.PsiFile class DeclarativeDslTransformerFactory : GradleDslTransformerFactory { override fun canTransform(psiFile: PsiFile) = psiFile is DeclarativeFile override fun createParser(psiFile: PsiFile, context: BuildModelContext, dslFile: GradleDslFile) = DeclarativeDslParser(psiFile as DeclarativeFile, context, dslFile) override fun createWriter(context: BuildModelContext) = DeclarativeDslWriter(context) }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,398
android
Apache License 2.0
app/src/main/java/com/thedefiapp/usecases/utils/UtilsUseCases.kt
saulmaos
459,017,062
false
null
package com.thedefiapp.usecases.utils import com.thedefiapp.data.repositories.NumberFormatterRepository import com.thedefiapp.utils.NumberFormatter.Builder.Companion.DO_NOT_CHANGE_AMOUNT_OF_DECIMALS import javax.inject.Inject class ConvertToFormattedNumberUseCase @Inject constructor(private val numberFormatterRepository: NumberFormatterRepository) { operator fun invoke( number: Double, isCrypto: Boolean = false, amountOfDecimals: Int = DO_NOT_CHANGE_AMOUNT_OF_DECIMALS, decideAmountDecimalsBasedOnNumberLength: Boolean = false ): String = numberFormatterRepository .changeNumber(number) .setIsCrypto(isCrypto) .changeAmountOfDecimals(amountOfDecimals) .decideAmountDecimalsBasedOnNumberLength(decideAmountDecimalsBasedOnNumberLength) .build() }
0
Kotlin
1
0
b58abbc9cc98d9534a876fba4400121acb222586
859
thedefiapp
MIT License
analysis/analysis-api/testData/components/scopeProvider/scopeContextForPosition/superTypeConstructor_nestedClasses.kt
JetBrains
3,432,266
false
null
package test interface BaseInterface { class NestedFromInterface } open class Base(any: Any): BaseInterface { class NestedFromClass inner class InnerFromClass } class Child : Base(<expr>Base.NestedFromClass()</expr>)
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
231
kotlin
Apache License 2.0
pandora/src/main/java/com/lodz/android/pandora/widget/rv/tree/RvTreeGroup.kt
LZ9
137,967,291
false
{"Kotlin": 2174504}
package com.lodz.android.pandora.widget.rv.tree /** * RV树结构组 * @author zhouL * @date 2022/7/15 */ interface RvTreeGroup : RvTreeItem { /** 子节点列表 */ fun fetchTreeItems(): List<RvTreeItem> /** 当前是否展开子节点 */ fun isExpandItem(): Boolean /** 当前是否展开子节点 */ fun onExpandChanged(isExpand: Boolean) /** 是否允许展开 */ fun expandEnable(): Boolean }
0
Kotlin
3
11
926b9f968a984c42ade94371714ef4caf3ffbccf
372
AgileDevKt
Apache License 2.0
src/main/kotlin/com/nmincuzzi/ipweather/infrastructure/WeatherResponse.kt
NicoMincuzzi
266,125,569
false
null
package com.nmincuzzi.ipweather.infrastructure data class WeatherResponse( val forecast: String, val temp: String, val feels_like: String, val temp_min: String, val temp_max: String, val humidity: String )
1
Kotlin
1
2
261ce5be9e62a61d54530b63bba3f8f698cedd8b
230
ipweather
Apache License 2.0
app/src/main/java/org/wikipedia/readinglist/ReadingListFragment.kt
zstartw
113,543,166
true
{"Java": 2573612, "JavaScript": 246120, "Kotlin": 121339, "CSS": 101539, "Python": 18751, "HTML": 3489, "Shell": 3316, "Makefile": 531}
package org.wikipedia.readinglist import android.content.DialogInterface import android.graphics.Color import android.os.Bundle import android.support.annotation.PluralsRes import android.support.design.widget.AppBarLayout import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.view.ActionMode import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.support.v7.widget.helper.ItemTouchHelper import android.text.Spanned import android.text.TextUtils 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.widget.TextView import android.widget.Toast import com.squareup.otto.Subscribe import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.ReadingListsFunnel import org.wikipedia.concurrency.CallbackTask import org.wikipedia.history.HistoryEntry import org.wikipedia.history.SearchActionModeCallback import org.wikipedia.main.MainActivity import org.wikipedia.page.ExclusiveBottomSheetPresenter import org.wikipedia.page.PageActivity import org.wikipedia.page.PageTitle import org.wikipedia.readinglist.page.ReadingListPage import org.wikipedia.readinglist.page.database.ReadingListDaoProxy import org.wikipedia.readinglist.page.database.ReadingListPageDao import org.wikipedia.readinglist.sync.ReadingListSyncEvent import org.wikipedia.readinglist.sync.ReadingListSynchronizer import org.wikipedia.settings.Prefs import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.ShareUtil import org.wikipedia.util.StringUtil import org.wikipedia.views.DefaultViewHolder import org.wikipedia.views.DrawableItemDecoration import org.wikipedia.views.MultiSelectActionModeCallback import org.wikipedia.views.PageItemView import org.wikipedia.views.SearchEmptyView import org.wikipedia.views.SwipeableItemTouchHelperCallback import org.wikipedia.views.TextInputDialog import java.util.ArrayList import java.util.Collections import java.util.Locale import butterknife.BindView import butterknife.ButterKnife import butterknife.Unbinder import org.wikipedia.readinglist.ReadingListActivity.EXTRA_READING_LIST_TITLE import org.wikipedia.readinglist.ReadingLists.SORT_BY_NAME_ASC class ReadingListFragment : Fragment(), ReadingListItemActionsDialog.Callback { @BindView(R.id.reading_list_toolbar) @JvmField var toolbar: Toolbar? = null @BindView(R.id.reading_list_toolbar_container) @JvmField var toolBarLayout: CollapsingToolbarLayout? = null @BindView(R.id.reading_list_app_bar) @JvmField var appBarLayout: AppBarLayout? = null @BindView(R.id.reading_list_header) @JvmField var headerImageView: ReadingListHeaderView? = null @BindView(R.id.reading_list_contents) @JvmField var recyclerView: RecyclerView? = null @BindView(R.id.reading_list_empty_text) @JvmField var emptyView: TextView? = null @BindView(R.id.search_empty_view) @JvmField var searchEmptyView: SearchEmptyView? = null private var unbinder: Unbinder? = null private val eventBusMethods = EventBusMethods() private var readingList: ReadingList? = null private var readingListTitle: String? = null private val adapter = ReadingListPageItemAdapter() private var headerView: ReadingListItemView? = null private var actionMode: ActionMode? = null private val appBarListener = AppBarListener() private var showOverflowMenu: Boolean = false private val readingLists = ReadingLists() private val funnel = ReadingListsFunnel() private val headerCallback = HeaderCallback() private val itemCallback = ItemCallback() private val searchActionModeCallback = SearchCallback() private val multiSelectActionModeCallback = MultiSelectCallback() private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() private val displayedPages = ArrayList<ReadingListPage>() private var currentSearchQuery: String? = null private val appCompatActivity: AppCompatActivity get() = activity as AppCompatActivity private val selectedPageCount: Int get() { var selectedCount = 0 for (page in displayedPages) { if (page.isSelected) { selectedCount++ } } return selectedCount } private val selectedPages: List<ReadingListPage> get() { val result = ArrayList<ReadingListPage>() if (readingList == null) { return result } for (page in displayedPages) { if (page.isSelected) { result.add(page) page.isSelected = false } } return result } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater!!.inflate(R.layout.fragment_reading_list, container, false) unbinder = ButterKnife.bind(this, view) appCompatActivity.setSupportActionBar(toolbar) appCompatActivity.supportActionBar!!.setDisplayHomeAsUpEnabled(true) appCompatActivity.supportActionBar!!.title = "" appBarLayout!!.addOnOffsetChangedListener(appBarListener) toolBarLayout!!.setCollapsedTitleTextColor(Color.WHITE) val touchCallback = SwipeableItemTouchHelperCallback(context) val itemTouchHelper = ItemTouchHelper(touchCallback) itemTouchHelper.attachToRecyclerView(recyclerView) recyclerView!!.layoutManager = LinearLayoutManager(context) recyclerView!!.adapter = adapter recyclerView!!.addItemDecoration(DrawableItemDecoration(context, R.attr.list_separator_drawable)) headerView = ReadingListItemView(context) headerView!!.setCallback(headerCallback) headerView!!.isClickable = false headerView!!.setThumbnailVisible(false) headerView!!.setShowDescriptionEmptyHint(true) headerView!!.setTitleTextAppearance(R.style.ReadingListTitleTextAppearance) readingListTitle = arguments.getString(EXTRA_READING_LIST_TITLE) WikipediaApp.instance.bus!!.register(eventBusMethods) return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onResume() { super.onResume() updateReadingListData() } override fun onDestroyView() { WikipediaApp.instance.bus!!.unregister(eventBusMethods) readingList = null readingLists.set(emptyList()) recyclerView!!.adapter = null appBarLayout!!.removeOnOffsetChangedListener(appBarListener) unbinder!!.unbind() unbinder = null super.onDestroyView() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater!!.inflate(R.menu.menu_reading_lists, menu) if (showOverflowMenu) { inflater.inflate(R.menu.menu_reading_list_item, menu) } } override fun onPrepareOptionsMenu(menu: Menu?) { super.onPrepareOptionsMenu(menu) val sortByNameItem = menu!!.findItem(R.id.menu_sort_by_name) val sortByRecentItem = menu.findItem(R.id.menu_sort_by_recent) val sortMode = Prefs.getReadingListPageSortMode(ReadingLists.SORT_BY_NAME_ASC) sortByNameItem.setTitle(if (sortMode == ReadingLists.SORT_BY_NAME_ASC) R.string.reading_list_sort_by_name_desc else R.string.reading_list_sort_by_name) sortByRecentItem.setTitle(if (sortMode == ReadingLists.SORT_BY_RECENT_DESC) R.string.reading_list_sort_by_recent_desc else R.string.reading_list_sort_by_recent) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.menu_search_lists -> { appCompatActivity.startSupportActionMode(searchActionModeCallback) return true } R.id.menu_sort_by_name -> { setSortMode(ReadingLists.SORT_BY_NAME_ASC, ReadingLists.SORT_BY_NAME_DESC) return true } R.id.menu_sort_by_recent -> { setSortMode(ReadingLists.SORT_BY_RECENT_DESC, ReadingLists.SORT_BY_RECENT_ASC) return true } R.id.menu_reading_list_rename -> { rename() return true } R.id.menu_reading_list_edit_description -> { editDescription() return true } R.id.menu_reading_list_delete -> { delete() return true } R.id.menu_reading_list_save_all_offline -> { readingList?.let { saveSelectedPagesForOffline(it.pages) } return true } R.id.menu_reading_list_remove_all_offline -> { if (readingList != null) { removeSelectedPagesFromOffline(readingList!!.pages) } return true } else -> return super.onOptionsItemSelected(item) } } private fun update() { if (readingList == null) { return } emptyView!!.visibility = if (readingList!!.pages.isEmpty()) View.VISIBLE else View.GONE headerView!!.setReadingList(readingList!!, ReadingListItemView.Description.DETAIL) headerImageView!!.setReadingList(readingList!!) readingList!!.sort(Prefs.getReadingListPageSortMode(SORT_BY_NAME_ASC)) setSearchQuery(currentSearchQuery) updateListDetailsAsync(readingList!!) } private fun updateListDetailsAsync(list: ReadingList) { ReadingListPageDetailFetcher.updateInfo(list, object : ReadingListPageDetailFetcher.Callback { override fun success() { if (!isAdded) { return } adapter.notifyDataSetChanged() } override fun failure(e: Throwable) {} }) } private fun updateReadingListData() { ReadingList.DAO.queryMruLists(null, object : CallbackTask.DefaultCallback<List<ReadingList>>() { override fun success(lists: List<ReadingList>) { if (activity == null) { return } readingLists.set(lists) readingList = readingLists.get(readingListTitle) if (readingList != null) { searchEmptyView!!.setEmptyText(getString(R.string.search_reading_list_no_results, readingList!!.title)) } update() } }) } private fun setSearchQuery(query: String?) { var query = query if (readingList == null) { return } currentSearchQuery = query displayedPages.clear() if (TextUtils.isEmpty(query)) { displayedPages.addAll(readingList!!.pages) } else { query = query!!.toUpperCase(Locale.getDefault()) for (page in readingList!!.pages) { if (page.title().toUpperCase(Locale.getDefault()) .contains(query.toUpperCase(Locale.getDefault()))) { displayedPages.add(page) } } } adapter.notifyDataSetChanged() updateEmptyState(query) } private fun updateEmptyState(searchQuery: String?) { if (TextUtils.isEmpty(searchQuery)) { searchEmptyView!!.visibility = View.GONE recyclerView!!.visibility = View.VISIBLE emptyView!!.visibility = if (displayedPages.isEmpty()) View.VISIBLE else View.GONE } else { recyclerView!!.visibility = if (displayedPages.isEmpty()) View.GONE else View.VISIBLE searchEmptyView!!.visibility = if (displayedPages.isEmpty()) View.VISIBLE else View.GONE emptyView!!.visibility = View.GONE } } private fun setSortMode(sortModeAsc: Int, sortModeDesc: Int) { var sortMode = Prefs.getReadingListPageSortMode(ReadingLists.SORT_BY_NAME_ASC) if (sortMode != sortModeAsc) { sortMode = sortModeAsc } else { sortMode = sortModeDesc } Prefs.setReadingListPageSortMode(sortMode) activity.invalidateOptionsMenu() update() } private fun showMultiSelectOfflineStateChangeSnackbar(pages: List<ReadingListPage>, offline: Boolean) { val message = if (offline) getQuantityString(R.plurals.reading_list_article_offline_message, pages.size) else getQuantityString(R.plurals.reading_list_article_not_offline_message, pages.size) FeedbackUtil.showMessage(activity, message) } private fun showDeleteItemsUndoSnackbar(readingList: ReadingList, pages: List<ReadingListPage>) { val message = if (pages.size == 1) String.format(getString(R.string.reading_list_item_deleted), pages[0].title()) else String.format(getString(R.string.reading_list_items_deleted), pages.size) val snackbar = FeedbackUtil.makeSnackbar(activity, message, FeedbackUtil.LENGTH_DEFAULT) snackbar.setAction(R.string.reading_list_item_delete_undo) { for (page in pages) { ReadingList.DAO.addTitleToList(readingList, page, true) ReadingListSynchronizer.instance().bumpRevAndSync() ReadingListPageDao.instance().markOutdated(page) } update() } snackbar.show() } private fun rename() { if (readingList == null) { return } ReadingListTitleDialog.readingListTitleDialog(context, readingList!!.title, readingLists.getTitlesExcept(readingList!!.title) ) { text -> readingListTitle = text.toString() ReadingList.DAO.renameAndSaveListInfo(readingList!!, readingListTitle) ReadingListSynchronizer.instance().bumpRevAndSync() update() funnel.logModifyList(readingList, readingLists.size()) }.show() } private fun editDescription() { if (readingList == null) { return } TextInputDialog.newInstance(context, object : TextInputDialog.DefaultCallback() { override fun onShow(dialog: TextInputDialog) { dialog.setHint(R.string.reading_list_description_hint) dialog.setText(readingList!!.description) } override fun onSuccess(text: CharSequence) { readingList!!.setDescription(text.toString()) ReadingList.DAO.saveListInfo(readingList!!) ReadingListSynchronizer.instance().bumpRevAndSync() update() funnel.logModifyList(readingList, readingLists.size()) } }).show() } private fun finishActionMode() { if (actionMode != null) { actionMode!!.finish() } } private fun beginMultiSelect() { if (SearchActionModeCallback.isMode(actionMode)) { finishActionMode() } if (!MultiSelectActionModeCallback.isMode(actionMode)) { appCompatActivity.startSupportActionMode(multiSelectActionModeCallback) } } private fun toggleSelectPage(page: ReadingListPage?) { if (page == null) { return } page.isSelected = !page.isSelected val selectedCount = selectedPageCount if (selectedCount == 0) { finishActionMode() } else if (actionMode != null) { actionMode!!.title = getString(R.string.multi_select_items_selected, selectedCount) } adapter.notifyDataSetChanged() } private fun unselectAllPages() { if (readingList == null) { return } for (page in readingList!!.pages) { page.isSelected = false } adapter.notifyDataSetChanged() } private fun deleteSelectedPages() { val selectedPages = selectedPages if (!selectedPages.isEmpty()) { for (page in selectedPages) { ReadingList.DAO.removeTitleFromList(readingList!!, page) } ReadingListSynchronizer.instance().bumpRevAndSync() funnel.logDeleteItem(readingList, readingLists.size()) readingList?.let { showDeleteItemsUndoSnackbar(it, selectedPages) } update() } } private fun removeSelectedPagesFromOffline(selectedPages: List<ReadingListPage>) { if (!selectedPages.isEmpty()) { selectedPages .filter { it.isOffline } .forEach { ReadingListData.instance().setPageOffline(it, false) } ReadingListSynchronizer.instance().sync() showMultiSelectOfflineStateChangeSnackbar(selectedPages, false) adapter.notifyDataSetChanged() update() } } private fun saveSelectedPagesForOffline(selectedPages: List<ReadingListPage>) { if (!selectedPages.isEmpty()) { selectedPages .filterNot { it.isOffline } .forEach { ReadingListData.instance().setPageOffline(it, true) } ReadingListSynchronizer.instance().sync() showMultiSelectOfflineStateChangeSnackbar(selectedPages, true) adapter.notifyDataSetChanged() update() } } private fun addSelectedPagesToList() { val selectedPages = selectedPages if (!selectedPages.isEmpty()) { val titles = ArrayList<PageTitle>() for (page in selectedPages) { titles.add(ReadingListDaoProxy.pageTitle(page)) } bottomSheetPresenter.show(childFragmentManager, AddToReadingListDialog.newInstance(titles, AddToReadingListDialog.InvokeSource.READING_LIST_ACTIVITY)) update() } } private fun deleteSinglePage(page: ReadingListPage?) { if (readingList == null || page == null) { return } readingList?.let { showDeleteItemsUndoSnackbar(it, listOf(page)) } ReadingList.DAO.removeTitleFromList(readingList!!, page) ReadingListSynchronizer.instance().bumpRevAndSync() funnel.logDeleteItem(readingList, readingLists.size()) update() } private fun delete() { if (readingList != null) { startActivity(MainActivity.newIntent(context) .putExtra(Constants.INTENT_EXTRA_DELETE_READING_LIST, readingList!!.title)) activity.finish() } } override fun onToggleItemOffline(pageIndex: Int) { val page = (if (readingList == null) null else readingList!!.get(pageIndex)) ?: return if (page.isOffline) { ReadingList.DAO.anyListContainsTitleAsync(page.key(), PageListCountCallback(page)) } else { toggleOffline(page) } } override fun onShareItem(pageIndex: Int) { val page = if (readingList == null) null else readingList!!.get(pageIndex) if (page != null) { ShareUtil.shareText(context, ReadingListDaoProxy.pageTitle(page)) } } override fun onAddItemToOther(pageIndex: Int) { val page = if (readingList == null) null else readingList!!.get(pageIndex) if (page != null) { bottomSheetPresenter.show(childFragmentManager, AddToReadingListDialog.newInstance(ReadingListDaoProxy.pageTitle(page), AddToReadingListDialog.InvokeSource.READING_LIST_ACTIVITY)) } } override fun onDeleteItem(pageIndex: Int) { val page = if (readingList == null) null else readingList!!.get(pageIndex) deleteSinglePage(page) } private fun toggleOffline(page: ReadingListPage) { ReadingListData.instance().setPageOffline(page, !page.isOffline) if (activity != null) { FeedbackUtil.showMessage(activity, if (page.isOffline) getQuantityString(R.plurals.reading_list_article_offline_message, 1) else getQuantityString(R.plurals.reading_list_article_not_offline_message, 1)) adapter.notifyDataSetChanged() ReadingListSynchronizer.instance().syncSavedPages() } } private fun showMultiListPageConfirmToggleDialog(page: ReadingListPage) { if (activity == null) { return } val dialog = AlertDialog.Builder(context) .setTitle(R.string.reading_list_confirm_remove_article_from_offline_title) .setMessage(getConfirmToggleOfflineMessage(page)) .setPositiveButton(R.string.reading_list_confirm_remove_article_from_offline, ConfirmRemoveFromOfflineListener(page)) .setNegativeButton(android.R.string.cancel, null) .create() dialog.show() val text = dialog.findViewById<TextView>(android.R.id.message) text!!.setLineSpacing(0f, 1.3f) } private fun getConfirmToggleOfflineMessage(page: ReadingListPage): Spanned { var result = getString(R.string.reading_list_confirm_remove_article_from_offline_message, "<b>" + page.title() + "</b>") for (key in page.listKeys()) { result += "<br>&nbsp;&nbsp;<b>&#8226; " + ReadingListDaoProxy.listName(key) + "</b>" } return StringUtil.fromHtml(result) } private fun getQuantityString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): String { return resources.getQuantityString(id, quantity, *formatArgs) } private inner class AppBarListener : AppBarLayout.OnOffsetChangedListener { override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { if (verticalOffset > -appBarLayout.totalScrollRange && showOverflowMenu) { showOverflowMenu = false toolBarLayout!!.title = "" appCompatActivity.supportInvalidateOptionsMenu() } else if (verticalOffset <= -appBarLayout.totalScrollRange && !showOverflowMenu) { showOverflowMenu = true toolBarLayout!!.title = if (readingList != null) readingList!!.title else null appCompatActivity.supportInvalidateOptionsMenu() } } } private inner class HeaderCallback : ReadingListItemView.Callback { override fun onClick(readingList: ReadingList) {} override fun onRename(readingList: ReadingList) { rename() } override fun onEditDescription(readingList: ReadingList) { editDescription() } override fun onDelete(readingList: ReadingList) { delete() } override fun onSaveAllOffline(readingList: ReadingList) { saveSelectedPagesForOffline(readingList.pages) } override fun onRemoveAllOffline(readingList: ReadingList) { removeSelectedPagesFromOffline(readingList.pages) } } private inner class ReadingListPageItemHolder internal constructor(itemView: PageItemView<ReadingListPage>) : DefaultViewHolder<PageItemView<ReadingListPage>>(itemView), SwipeableItemTouchHelperCallback.Callback { private var page: ReadingListPage? = null internal fun bindItem(page: ReadingListPage) { this.page = page view.setItem(page) view.setTitle(page.title()) view.setDescription(page.description()) view.setImageUrl(page.thumbnailUrl()) view.isSelected = page.isSelected view.setActionIcon(R.drawable.ic_more_vert_white_24dp) view.setActionHint(R.string.abc_action_menu_overflow_description) view.setSecondaryActionIcon(if (page.isSaving) R.drawable.ic_download_started else R.drawable.ic_download_circle_gray_24dp, !page.isOffline || page.isSaving) view.setSecondaryActionHint(R.string.reading_list_article_make_offline) } override fun onSwipe() { deleteSinglePage(page) } } private inner class ReadingListHeaderHolder internal constructor(itemView: View?) : RecyclerView.ViewHolder(itemView) private inner class ReadingListPageItemAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemCount(): Int { return 1 + displayedPages.size } override fun onCreateViewHolder(parent: ViewGroup, type: Int): RecyclerView.ViewHolder { return if (type == TYPE_HEADER) { ReadingListHeaderHolder(headerView) } else ReadingListPageItemHolder(PageItemView(context)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, pos: Int) { if (readingList != null && holder is ReadingListPageItemHolder) { holder.bindItem(displayedPages[pos - 1]) } } override fun getItemViewType(position: Int): Int { return if (position == 0) TYPE_HEADER else TYPE_ITEM } override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder?) { super.onViewAttachedToWindow(holder) (holder as? ReadingListPageItemHolder)?.view?.setCallback(itemCallback) } override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder?) { (holder as? ReadingListPageItemHolder)?.view?.setCallback(null) super.onViewDetachedFromWindow(holder) } } private inner class ItemCallback : PageItemView.Callback<ReadingListPage> { override fun onClick(page: ReadingListPage?) { if (MultiSelectActionModeCallback.isMode(actionMode)) { toggleSelectPage(page) } else if (page != null && readingList != null) { val title = ReadingListDaoProxy.pageTitle(page) val entry = HistoryEntry(title, HistoryEntry.SOURCE_READING_LIST) ReadingList.DAO.makeListMostRecent(readingList!!) startActivity(PageActivity.newIntentForNewTab(context, entry, entry.title)) } } override fun onLongClick(item: ReadingListPage?): Boolean { beginMultiSelect() toggleSelectPage(item) return true } override fun onThumbClick(item: ReadingListPage?) { onClick(item) } override fun onActionClick(page: ReadingListPage?, view: View) { if (page == null || readingList == null) { return } bottomSheetPresenter.show(childFragmentManager, ReadingListItemActionsDialog.newInstance(page, readingList!!)) } override fun onSecondaryActionClick(page: ReadingListPage?, view: View) { if (page != null) { if (page.isSaving) { Toast.makeText(context, R.string.reading_list_article_save_in_progress, Toast.LENGTH_LONG).show() } else { toggleOffline(page) } } } } private inner class SearchCallback : SearchActionModeCallback() { override val searchHintString: String get() = getString(R.string.search_hint_search_reading_list) override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { actionMode = mode recyclerView!!.stopScroll() appBarLayout!!.setExpanded(false, false) return super.onCreateActionMode(mode, menu) } override fun onQueryChange(s: String) { setSearchQuery(s.trim { it <= ' ' }) } override fun onDestroyActionMode(mode: ActionMode) { super.onDestroyActionMode(mode) actionMode = null setSearchQuery(null) } } private inner class MultiSelectCallback : MultiSelectActionModeCallback() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { super.onCreateActionMode(mode, menu) mode.menuInflater.inflate(R.menu.menu_action_mode_reading_list, menu) actionMode = mode return true } override fun onActionItemClicked(mode: ActionMode, menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.menu_delete_selected -> { onDeleteSelected() finishActionMode() return true } R.id.menu_remove_from_offline -> { removeSelectedPagesFromOffline(selectedPages) finishActionMode() return true } R.id.menu_save_for_offline -> { saveSelectedPagesForOffline(selectedPages) finishActionMode() return true } R.id.menu_add_to_another_list -> { addSelectedPagesToList() finishActionMode() return true } } return false } override fun onDeleteSelected() { deleteSelectedPages() } override fun onDestroyActionMode(mode: ActionMode) { unselectAllPages() actionMode = null super.onDestroyActionMode(mode) } } private inner class PageListCountCallback (private val page: ReadingListPage) : CallbackTask.DefaultCallback<ReadingListPage>() { override fun success(fromDb: ReadingListPage) { if (fromDb.listKeys().size > 1) { showMultiListPageConfirmToggleDialog(page) } else { toggleOffline(page) } } } private inner class ConfirmRemoveFromOfflineListener (private val page: ReadingListPage) : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, which: Int) { toggleOffline(page) } } private inner class EventBusMethods { @Subscribe fun on(event: ReadingListSyncEvent) { if (isAdded) { updateReadingListData() } } } companion object { private val TYPE_HEADER = 0 private val TYPE_ITEM = 1 fun newInstance(listTitle: String): ReadingListFragment { val instance = ReadingListFragment() val args = Bundle() args.putString(EXTRA_READING_LIST_TITLE, listTitle) instance.arguments = args return instance } } }
0
Java
0
0
4f5b2eceeba97ade87ba62cb5e651132d6a3fd46
31,637
apps-android-wikipedia
Apache License 2.0
ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt
YMalakov
171,684,193
true
{"Kotlin": 907808, "Java": 693579, "Shell": 39021, "Python": 18489, "Dockerfile": 2736, "Groovy": 2304, "PLSQL": 2262}
/* * Copyright © 2017-2018 AT&T Intellectual Property. * * 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.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import io.swagger.annotations.ApiOperation import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType import org.springframework.http.codec.multipart.FilePart 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.RequestMethod import org.springframework.web.bind.annotation.RequestPart import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono @RestController @RequestMapping("/api/v1/execution-service") class ExecutionServiceController { @Autowired lateinit var executionServiceHandler: ExecutionServiceHandler @RequestMapping(path = ["/ping"], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]) @ResponseBody fun ping(): Mono<String> { return Mono.just("Success") } @PostMapping(path = ["/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @ApiOperation(value = "Upload CBA", notes = "Takes a File and load it in the runtime database") @ResponseBody fun upload(@RequestPart("file") parts: Mono<FilePart>): Mono<String> { return parts .filter { it is FilePart } .ofType(FilePart::class.java) .flatMap(executionServiceHandler::upload) } @RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) @ApiOperation(value = "Resolve Resource Mappings", notes = "Takes the blueprint information and process as per the payload") @ResponseBody fun process(@RequestBody executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { return executionServiceHandler.process(executionServiceInput) } }
0
Kotlin
0
0
01eff6bc81499a9e41395f6b384a5e893b366505
2,799
ccsdk-apps
Apache License 2.0
src/main/kotlin/me/alejandrorm/klosure/sparql/algebra/aggregates/Min.kt
alejandrorm
512,041,126
false
{"Kotlin": 196720, "Ruby": 28544, "HTML": 25737}
package me.alejandrorm.klosure.sparql.algebra.aggregates import me.alejandrorm.klosure.model.Graph import me.alejandrorm.klosure.model.Graphs import me.alejandrorm.klosure.model.NodeId import me.alejandrorm.klosure.sparql.SolutionMapping import me.alejandrorm.klosure.sparql.algebra.filters.Expression class Min(val expression: Expression) : AggregateExpression { override fun toString(): String { return "MIN($expression)" } override fun eval(solution: SolutionMapping, activeGraph: Graph, graphs: Graphs): NodeId { throw IllegalStateException("MIN should not be evaluated") } override fun evalGroup( solution: SolutionMapping, group: Sequence<SolutionMapping>, activeGraph: Graph, graphs: Graphs ): NodeId? { var min: NodeId? = null group.forEach { solution -> val value = expression.eval(solution, activeGraph, graphs) ?: return null if (min == null) { min = value } else { if (value < min!!) { min = value } } } return min } }
0
Kotlin
0
0
14abf426f3cad162c021ffae750038e25b8cb271
1,159
klosure
Apache License 2.0
duplicates-android/app/src/main/java/com/github/duplicates/DuplicateFindTask.kt
pnemonic78
74,286,607
false
{"Git Config": 1, "YAML": 1, "HTML": 1, "Text": 1, "Ignore List": 3, "Markdown": 2, "Gradle Kotlin DSL": 4, "Shell": 2, "Java Properties": 3, "Batchfile": 1, "Proguard": 1, "Java": 6, "XML": 80, "Kotlin": 87}
/* * Copyright 2016, Moshe Waisberg * * 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.github.duplicates import android.content.Context import com.github.duplicates.DuplicateComparator.Companion.MATCH_SAME import com.github.duplicates.db.DuplicateItemPairEntity import com.github.duplicates.db.DuplicatesDatabase import java.util.* import java.util.concurrent.* import kotlin.math.abs /** * Task to find duplicates. * * @author moshe.w */ abstract class DuplicateFindTask<I : DuplicateItem, VH : DuplicateViewHolder<I>, L : DuplicateFindTaskListener<I, VH>>( private val itemType: DuplicateItemType, context: Context, listener: L ) : DuplicateTask<I, Any, Any, List<I>, L>(context, listener) { private var comparator: DuplicateComparator<I>? = null private val items = ArrayList<I>() private val itemsCached = mutableMapOf<Long, I>() abstract fun createAdapter(): DuplicateAdapter<I, VH> abstract fun createComparator(): DuplicateComparator<I> override fun onPreExecute() { super.onPreExecute() items.clear() itemsCached.clear() this.comparator = createComparator() } override fun doInBackground(vararg params: Any): List<I> { db = DuplicatesDatabase.getDatabase(context) if (params.isNotEmpty()) { val param0 = params[0] if ((param0 is Boolean) && param0) { doFindDatabase(db) return items } } doFind(db) return items } private fun doFind(db: DuplicatesDatabase) { clearDatabaseTable(db) try { provider.fetchItems(this) } catch (ignore: CancellationException) { } } private fun doFindDatabase(db: DuplicatesDatabase) { val dao = db.pairDao() val entities = dao.queryAll(itemType) val comparator = this.comparator ?: return try { for (entity in entities) { val item1 = fetchItem(entity.id1) ?: continue item1.isChecked = entity.isChecked1 val item2 = fetchItem(entity.id2) ?: continue item2.isChecked = entity.isChecked2 val difference = comparator.difference(item1, item2) val match = comparator.match(item1, item2, difference) // Did the data change in the interim? if ((abs(match - entity.match) >= 0.01f)) continue listener.onDuplicateTaskMatch(this, item1, item2, match, difference) if (items.add(item1) && items.add(item2)) { publishProgress(items.size) } if (isCancelled) { break } } } catch (ignore: CancellationException) { } } override fun onItemFetched(provider: DuplicateProvider<I>, count: Int, item: I) { val size = items.size val isChecked2 = item.isChecked // Maybe the item already exists in the list? var item1: I for (i in size - 1 downTo 0) { item1 = items[i] if (item === item1) { return } } // Is it a duplicate? var bestMatch = 0f var bestItem: I? = null var bestDifference: BooleanArray? = null var difference: BooleanArray var match: Float val comparator = this.comparator ?: return // Most likely that a matching item is a neighbour, so count backwards. for (i in size - 1 downTo 0) { item1 = items[i] // Are both items already paired? if (item1.isChecked && isChecked2) { continue } difference = comparator.difference(item1, item) match = comparator.match(item1, item, difference) if (match >= MATCH_GOOD && match > bestMatch) { bestMatch = match bestDifference = difference bestItem = item1 if (match == MATCH_SAME) { break } } } if (bestItem != null) { item1 = bestItem match = bestMatch difference = bestDifference!! listener.onDuplicateTaskMatch(this, item1, item, match, difference) insertDatabase(item1, item, match) } if (items.add(item)) { publishProgress(size + 1) } } override fun onItemDeleted(provider: DuplicateProvider<I>, count: Int, item: I) { // Nothing to do. } override fun onPairDeleted( provider: DuplicateProvider<I>, count: Int, pair: DuplicateItemPair<I> ) { // Nothing to do. } override fun getPermissions(): Array<String>? { return provider.getReadPermissions() } private fun clearDatabaseTable(db: DuplicatesDatabase) { val dao = db.pairDao() dao.deleteAll(itemType) } private fun insertDatabase(item1: I, item2: I, match: Float) { val isChecked2 = item2.isChecked or (match >= DuplicateItemPair.MATCH_GREAT) val dao = db.pairDao() val entity = DuplicateItemPairEntity( type = itemType, match = match, id1 = item1.id, isChecked1 = item1.isChecked, id2 = item2.id, isChecked2 = isChecked2 ) dao.insert(entity) } private fun fetchItem(id: Long): I? { var item = itemsCached[id] if (item == null) { item = provider.fetchItem(id) if (item != null) { itemsCached[id] = item } } return item } companion object { /** * Percentage for two items to be considered a good match. */ const val MATCH_GOOD = 0.7f } }
3
null
1
1
38a11ad1b3f6dde7224fed6203cea0e0a2792a92
6,438
RemoveDuplicates
Apache License 2.0
app/src/main/java/com/prosabdev/fluidmusic/utils/InjectorUtils.kt
4kpros
555,755,264
false
{"Kotlin": 948923, "Java": 1923}
package com.prosabdev.fluidmusic.utils import android.app.Application import android.content.Context import com.prosabdev.fluidmusic.media.MediaEventsListener import com.prosabdev.fluidmusic.viewmodels.activities.EqualizerActivityViewModel import com.prosabdev.fluidmusic.viewmodels.activities.MainActivityViewModel import com.prosabdev.fluidmusic.viewmodels.fragments.PlayingNowFragmentViewModel import com.prosabdev.fluidmusic.viewmodels.mediacontroller.MediaControllerViewModel /** * Static methods used to inject classes needed for various Activities and Fragments. */ object InjectorUtils { fun provideMediaControllerViewModel(listener: MediaEventsListener): MediaControllerViewModel.Factory { return MediaControllerViewModel.Factory(listener) } fun provideMainActivityViewModel(app: Application): MainActivityViewModel.Factory { return MainActivityViewModel.Factory(app) } fun provideEqualizerActivityViewModel(app: Application): EqualizerActivityViewModel.Factory { return EqualizerActivityViewModel.Factory(app) } fun provideNowPlayingFragmentViewModel(ctx: Context): PlayingNowFragmentViewModel.Factory { val applicationContext = ctx.applicationContext return PlayingNowFragmentViewModel.Factory( applicationContext as Application ) } }
0
Kotlin
0
2
c9363fa150d1cd34b0fac119c825bfe75e2f96e1
1,346
FluidMusic
Apache License 2.0
blockframework/src/main/java/com/bytedance/blockframework/framework/config/BlockInit.kt
bytedance
870,149,624
false
{"Kotlin": 121952}
/* * Copyright (C) 2024 Bytedance Ltd. and/or its affiliates * * 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.bytedance.blockframework.framework.config import com.bytedance.blockframework.framework.monitor.BlockLogger /** * * @author: Created by zhoujunjie on 2023/8/9 * @mail <EMAIL> **/ object BlockInit { private var config: IBlockInitConfig = IBlockInitConfig.DefaultInitConfig() fun useTreeMessageCenterEnable(): Boolean { return config.useTreeMessageCenterEnable() } fun allTaskMustRunOnMain(): Boolean { return config.allTaskMustRunOnMain() } fun recordEnable(): Boolean { return config.recordEnable() } fun logOptEnable(): Boolean { return config.logOptEnable() } fun enableDebugDependencyCheck(): Boolean { return config.enableDebugDependencyCheck() } fun init(config: IBlockInitConfig) { this.config = config BlockLogger.setLogger(config.getBlockLogger()) } fun recordException(e: Throwable?) { config.recordException(e) } }
0
Kotlin
0
9
3b89d3a0c4ea80679637bfe0feb2260250181fe5
1,599
BlockFramework
Apache License 2.0
meta/src/main/kotlin/net/dean/jraw/meta/EndpointMeta.kt
mattbdean
19,762,540
false
null
package net.dean.jraw.meta import java.lang.reflect.Method data class EndpointMeta( /** HTTP request method ("GET", "POST", etc.) */ val method: String, /** Endpoint path, such as `/api/comment` */ val path: String, /** * If [subredditPrefix], includes the text `[/s/{subreddit}]` to signify that the client may optionally specify a * subreddit prefix. */ val displayPath: String = path, /** The OAuth scope required to send a successful request to this endpoint */ val oauthScope: String, /** * The URL to reddit's documentation at https://www.saidit.net/dev/api/oauth. For example, the doc link for * `POST /api/comment` is `https://www.saidit.net/dev/api/oauth#POST_api_comment`. */ val redditDocLink: String, /** * True if the original path was prefixed with "[/s/subreddit]", indicating that a request can be made either to * `/foo` or `/s/{subreddit}/foo` */ val subredditPrefix: Boolean, /** Where the endpoint is implemented, if any */ val implementation: Method? = null, /** A URL that links to the source code for the method that implements this endpoint */ val sourceUrl: String? = null, /** Current implementation status */ val status: ImplementationStatus = ImplementationStatus.PLANNED )
38
null
126
352
fa1efa33729d42c6d2fc52f4cf67eabcb75e3be9
1,330
JRAW
MIT License
usvm-dataflow/src/main/kotlin/org/usvm/dataflow/ifds/Summary.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2885124, "Java": 492428}
/* * Copyright 2022 UnitTestBot contributors (utbot.org) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.usvm.dataflow.ifds import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import org.jacodb.api.common.CommonMethod import org.jacodb.api.common.cfg.CommonInst import java.util.concurrent.ConcurrentHashMap /** * A common interface for anything that should be remembered * and used after the analysis of some unit is completed. */ interface Summary<out Method : CommonMethod> { val method: Method } interface SummaryEdge<out Fact, out Statement : CommonInst> : Summary<CommonMethod> { val edge: Edge<Fact, Statement> override val method: CommonMethod get() = edge.method } interface Vulnerability<out Fact, out Statement : CommonInst> : Summary<CommonMethod> { val message: String val sink: Vertex<Fact, Statement> override val method: CommonMethod get() = sink.method } /** * Contains summaries for many methods and allows to update them and subscribe for them. */ interface SummaryStorage<T : Summary<*>> { /** * A list of all methods for which summaries are not empty. */ val knownMethods: List<CommonMethod> /** * Adds [summary] the summaries storage of its method. */ fun add(summary: T) /** * @return a flow with all facts summarized for the given [method]. * Already received facts, along with the facts that will be sent to this storage later, * will be emitted to the returned flow. */ fun getFacts(method: CommonMethod): Flow<T> /** * @return a list will all facts summarized for the given [method] so far. */ fun getCurrentFacts(method: CommonMethod): List<T> } class SummaryStorageImpl<T : Summary<*>> : SummaryStorage<T> { private val summaries = ConcurrentHashMap<CommonMethod, MutableSet<T>>() private val outFlows = ConcurrentHashMap<CommonMethod, MutableSharedFlow<T>>() override val knownMethods: List<CommonMethod> get() = summaries.keys.toList() private fun getFlow(method: CommonMethod): MutableSharedFlow<T> { return outFlows.computeIfAbsent(method) { MutableSharedFlow(replay = Int.MAX_VALUE) } } override fun add(summary: T) { val isNew = summaries.computeIfAbsent(summary.method) { ConcurrentHashMap.newKeySet() }.add(summary) if (isNew) { val flow = getFlow(summary.method) check(flow.tryEmit(summary)) } } override fun getFacts(method: CommonMethod): SharedFlow<T> { return getFlow(method) } override fun getCurrentFacts(method: CommonMethod): List<T> { return getFacts(method).replayCache } }
36
Kotlin
9
9
6e48625b0b353b35e2bf6ce271812d012cabedd6
3,353
usvm
Apache License 2.0
composeApp/src/desktopMain/kotlin/com/mean/traclock/Main.kt
MeanZhang
445,493,173
false
{"Kotlin": 304219, "Python": 1288, "Shell": 82}
package com.mean.traclock import androidx.compose.material.MaterialTheme import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.window.Tray import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import androidx.compose.ui.window.rememberTrayState import com.mean.traclock.data.database.getAppDatabase import com.mean.traclock.data.repository.DATA_STORE_FILE_NAME import com.mean.traclock.data.repository.DatastoreRepository import com.mean.traclock.data.repository.NotificationRepository import com.mean.traclock.data.repository.ProjectsRepository import com.mean.traclock.data.repository.RecordsRepository import com.mean.traclock.data.repository.TimerRepository import com.mean.traclock.data.repository.getDataStore import com.mean.traclock.ui.TraclockApp import com.mean.traclock.utils.initLogger import kotlinx.coroutines.launch import okio.Path.Companion.toPath import org.jetbrains.compose.resources.painterResource import org.jetbrains.compose.resources.stringResource import traclock.composeapp.generated.resources.Res import traclock.composeapp.generated.resources.app_name import traclock.composeapp.generated.resources.exit import traclock.composeapp.generated.resources.logo import traclock.composeapp.generated.resources.start import traclock.composeapp.generated.resources.stop fun main() = application { initLogger() val scope = rememberCoroutineScope() val database = getAppDatabase() val recordsRepo = RecordsRepository(database.recordDao()) val projectsRepo = ProjectsRepository(database.projectDao(), database.recordDao()) val dataStore = getDataStore { (System.getProperty("user.home").toPath() / ".traclock" / DATA_STORE_FILE_NAME).toString() } val datastoreRepo = DatastoreRepository(dataStore) val trayState = rememberTrayState() val notificationRepo = NotificationRepository() notificationRepo.init(trayState) val timerRepo = TimerRepository( notificationRepo = notificationRepo, projectsRepo = projectsRepo, recordsRepo = recordsRepo, datastoreRepo = datastoreRepo, ) var isVisible by remember { mutableStateOf(true) } val isTiming by timerRepo.isTiming.collectAsState() Window( onCloseRequest = { isVisible = false }, visible = isVisible, title = stringResource(Res.string.app_name), icon = painterResource(Res.drawable.logo), ) { MaterialTheme { TraclockApp( recordsRepo = recordsRepo, projectsRepo = projectsRepo, timerRepo = timerRepo, ) } } Tray( state = trayState, icon = painterResource(Res.drawable.logo), tooltip = stringResource(Res.string.app_name), onAction = { isVisible = true }, menu = { Item( text = stringResource(Res.string.start), enabled = !isTiming, onClick = { scope.launch { timerRepo.start() } }, ) Item(stringResource(Res.string.stop), enabled = isTiming, onClick = { scope.launch { timerRepo.stop() } }) Item(stringResource(Res.string.exit), onClick = ::exitApplication) }, ) }
1
Kotlin
2
7
51efcaeac5f61a70edeee2554adc651fcf0b82f5
3,721
Traclock
Apache License 2.0
app/src/main/java/ticketchain/mobile/worker/views/screens/LoadingScreen.kt
gh-jsoares
460,914,237
false
null
package ticketchain.mobile.user.views.screens import android.annotation.SuppressLint import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.ScaffoldState import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavController import kotlinx.coroutines.delay import ticketchain.mobile.user.controllers.SnackbarController import ticketchain.mobile.user.errors.TicketChainApiException import ticketchain.mobile.user.services.AccountService import ticketchain.mobile.user.state.AppState import ticketchain.mobile.user.views.partials.LoadingProgressIndicator @ExperimentalAnimationApi object LoadingScreen : ApplicationScreen { override val route = "loading" @Composable override fun Header(scaffoldState: ScaffoldState) { // Empty } @SuppressLint("RestrictedApi") @Composable override fun Body( navController: NavController, snackbarController: SnackbarController, accountService: AccountService, state: AppState, ) { val (loading, setLoading) = remember { mutableStateOf(true) } var attempt by remember { mutableStateOf(0) } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { if (loading) { LaunchedEffect(loading) { try { accountService.loadData() while (!state.loaded) { attempt++ delay(1000) if (attempt >= 3) { throw TicketChainApiException("Cannot load data") } } navController.backQueue.clear() if (accountService.isFirstSetup()) { navController.navigate(InitialScreen.route) } else { navController.navigate(DashboardScreen.route) } } catch (e: TicketChainApiException) { snackbarController.showDismissibleSnackbar(e.message) setLoading(false) } } LoadingProgressIndicator( progressColor = MaterialTheme.colors.primary, backgroundColor = MaterialTheme.colors.surface ) Text( modifier = Modifier.padding(top = 10.dp), text = "Loading" ) } else { Button(onClick = { setLoading(true) }) { Text("Try again") } } } } }
0
Kotlin
0
0
a9a2713d49a5cdfb9a687aefd94c2036f5a49ff3
3,287
TicketChain-Worker
MIT License
ProgrammingFundamentals/Ep4.Ext/DigitsPowerSum/src/Task.kt
The-Streamliners
784,466,451
false
{"Kotlin": 6592}
fun getDigitsPowerSum(num: Int): Int { TODO() } fun main() { println( getDigitsPowerSum(123) ) }
0
Kotlin
14
0
71d564729b2458d4faa2d27c8af2528367b138be
117
KTP-Course
MIT License
app/src/main/java/pl/sienczykm/templbn/webservice/model/air/AirIndexQuality.kt
mat-sienczyk
193,071,707
false
null
package pl.sienczykm.templbn.webservice.model.air import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class AirIndexQuality { @SerializedName("id") @Expose var id: Int? = null @SerializedName("stCalcDate") @Expose var stCalcDate: String? = null @SerializedName("stIndexLevel") @Expose var stIndexLevel: StIndexLevel? = null @SerializedName("stSourceDataDate") @Expose var stSourceDataDate: String? = null @SerializedName("so2CalcDate") @Expose var so2CalcDate: String? = null @SerializedName("so2IndexLevel") @Expose var so2IndexLevel: So2IndexLevel? = null @SerializedName("so2SourceDataDate") @Expose var so2SourceDataDate: String? = null @SerializedName("no2CalcDate") @Expose var no2CalcDate: String? = null @SerializedName("no2IndexLevel") @Expose var no2IndexLevel: No2IndexLevel? = null @SerializedName("no2SourceDataDate") @Expose var no2SourceDataDate: String? = null @SerializedName("coCalcDate") @Expose var coCalcDate: String? = null @SerializedName("coIndexLevel") @Expose var coIndexLevel: CoIndexLevel? = null @SerializedName("coSourceDataDate") @Expose var coSourceDataDate: String? = null @SerializedName("pm10CalcDate") @Expose var pm10CalcDate: String? = null @SerializedName("pm10IndexLevel") @Expose var pm10IndexLevel: Pm10IndexLevel? = null @SerializedName("pm10SourceDataDate") @Expose var pm10SourceDataDate: String? = null @SerializedName("pm25CalcDate") @Expose var pm25CalcDate: String? = null @SerializedName("pm25IndexLevel") @Expose var pm25IndexLevel: Pm25IndexLevel? = null @SerializedName("pm25SourceDataDate") @Expose var pm25SourceDataDate: String? = null @SerializedName("o3CalcDate") @Expose var o3CalcDate: String? = null @SerializedName("o3IndexLevel") @Expose var o3IndexLevel: O3IndexLevel? = null @SerializedName("o3SourceDataDate") @Expose var o3SourceDataDate: String? = null @SerializedName("c6h6CalcDate") @Expose var c6h6CalcDate: String? = null @SerializedName("c6h6IndexLevel") @Expose var c6h6IndexLevel: C6h6IndexLevel? = null @SerializedName("c6h6SourceDataDate") @Expose var c6h6SourceDataDate: String? = null @SerializedName("stIndexStatus") @Expose var stIndexStatus: Boolean? = null @SerializedName("stIndexCrParam") @Expose var stIndexCrParam: String? = null } class C6h6IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class CoIndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class No2IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class Pm10IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class Pm25IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class So2IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class StIndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null } class O3IndexLevel { @SerializedName("id") @Expose var id: Int? = null @SerializedName("indexLevelName") @Expose var indexLevelName: String? = null }
0
Kotlin
1
2
9c87e40d685d62a4e523708428c2f8ec44494948
3,994
LubelskieStacjePogodowe
Apache License 2.0
src/main/kotlin/com/github/locxter/bkndmvrgnzr/backend/genre/api/GenreCreateDto.kt
locxter
625,164,400
false
null
package com.github.locxter.bkndmvrgnzr.backend.genre.api data class GenreCreateDto( val name: String = "" )
0
Kotlin
0
1
eb3969c9be51196670788c43683b739aa0ce5083
113
bkndmvrgnzr-backend
MIT License
app/src/main/java/com/raturu/pertaminanow/data/source/remote/response/GetKtpVerifySpbuCode.kt
Raturu
128,503,967
false
{"Kotlin": 126787}
package com.raturu.pertaminanow.data.source.remote.response import com.google.gson.annotations.SerializedName /** * Created on : April 21, 2018 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ data class GetKtpVerifySpbuCode( @SerializedName("status") val status: Boolean, @SerializedName("code") val code: String )
0
Kotlin
0
0
66281540936887bf628d9789bbca077d67fa7c0a
382
pertamina-now-android
Apache License 2.0
core/src/main/java/io/freshdroid/vinyl/core/rx/operators/ApiErrorOperator.kt
gm4s
175,840,667
false
null
package io.freshdroid.vinyl.core.rx.operators import com.squareup.moshi.Moshi import io.freshdroid.vinyl.core.network.envelopes.ErrorEnvelope import io.freshdroid.vinyl.core.network.exceptions.ApiException import io.freshdroid.vinyl.core.network.exceptions.ResponseException import io.reactivex.ObservableOperator import io.reactivex.Observer import io.reactivex.disposables.Disposable import retrofit2.Response class ApiErrorOperator<T>( private val moshi: Moshi ) : ObservableOperator<T, Response<T>> { override fun apply(observer: Observer<in T>): Observer<in Response<T>> { return object : Observer<Response<T>> { override fun onComplete() { observer.onComplete() } override fun onSubscribe(d: Disposable) { observer.onSubscribe(d) } override fun onNext(response: Response<T>) { if (!response.isSuccessful) { try { val adapter = moshi.adapter(ErrorEnvelope::class.java) val envelope = adapter.fromJson(response.errorBody()?.string() ?: "{}") if (envelope != null) { val envelopeWithCodeError = envelope.copy(code = response.code()) observer.onError(ApiException(envelopeWithCodeError, response)) } else { observer.onError(ResponseException(response)) } } catch (e: Exception) { observer.onError(ResponseException(response)) } } else { observer.onNext(response.body()!!) observer.onComplete() } } override fun onError(e: Throwable) { observer.onError(e) } } } }
1
Kotlin
1
1
36e6d69aa15b7eff1981fe549bb8606df06a0410
1,926
Vinyl
Apache License 2.0
library/saga/messaging/headers/src/main/kotlin/io/github/ustudiocompany/uframework/saga/message/header/StatusHeader.kt
uStudioCompany
745,407,841
false
{"Kotlin": 184532}
package io.github.ustudiocompany.uframework.saga.message.header import io.github.ustudiocompany.uframework.messaging.message.header.Header import io.github.ustudiocompany.uframework.messaging.message.header.Headers import io.github.ustudiocompany.uframework.saga.message.header.type.Status import kotlin.text.Charsets.UTF_8 public fun Header.Companion.status(value: Status): Header = Header(STATUS_HEADER_NAME, value.key.toByteArray(UTF_8)) public fun Headers.status(): Header? = this.last(STATUS_HEADER_NAME) public const val STATUS_HEADER_NAME: String = "status"
0
Kotlin
0
0
fef87788699bf76908a739a9326ef2df92de778d
573
u-framework
Apache License 2.0
lib/src/main/kotlin/io/github/ccjhr/number/short/Is.kt
cc-jhr
484,712,081
false
null
package io.github.ccjhr.number.short import io.github.ccjhr.AssertionContext import io.github.ccjhr.any.AnyAssertionAdjective.* import io.github.ccjhr.expectNotNull import io.github.ccjhr.number.NumberAssertionAdjectives import io.github.ccjhr.number.NumberAssertionAdjectives.* import kotlin.test.fail /** * Verifies that the [Short] under test applies to a given [NumberAssertionAdjectives]. * @since 2.0.0 * @param adjective The [NumberAssertionAdjectives] that applies to the object under test. * @throws AssertionError In case the assertion fails. * @receiver Any nullable or non-nullable [Short]. * @see isNot * @sample io.github.ccjhr.samples.number.short.isOdd * @sample io.github.ccjhr.samples.number.short.isEven * @sample io.github.ccjhr.samples.number.short.isPositive * @sample io.github.ccjhr.samples.number.short.isNegative */ inline infix fun <reified T: Short?> AssertionContext<T>.`is`(adjective: NumberAssertionAdjectives) { expectNotNull(this.content) when(adjective) { Odd -> if(this.content.mod(2.toShort()) == 0.toShort()) fail("Expecting <${this.content}> to be odd, but it's even.") Even -> if(this.content.mod(2.toShort()) != 0.toShort()) fail("Expecting <${this.content}> to be even, but it's odd.") Positive -> if (this.content < 0.toShort()) fail("Expecting <${this.content}> to be positive, but it's negative.") Negative -> if (this.content > 0.toShort()) fail("Expecting <${this.content}> to be negative, but it's positive.") } }
0
Kotlin
0
1
d2da30455d8d212303eccc0e096f9aceeaf38eda
1,518
nagare
Apache License 2.0
src/main/kotlin/ru/jmorozov/prodkalendar/ProdKalendarApplication.kt
jmorozov
145,248,149
false
null
package ru.jmorozov.prodkalendar import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class ProdKalendarApplication fun main(args: Array<String>) { @Suppress("SpreadOperator") runApplication<ProdKalendarApplication>(*args) }
1
Kotlin
0
3
725e7a68b7b5417488021a617ff27b252534782c
321
productive-kalendar
MIT License
module-domain/src/test/kotlin/io/klaytn/finder/service/auth/AccessKeyGenerator.kt
klaytn
678,353,482
false
{"Kotlin": 1783784, "Solidity": 71874, "Shell": 4003}
package io.klaytn.finder.service.auth import java.util.* import org.junit.jupiter.api.Test import org.springframework.security.crypto.keygen.Base64StringKeyGenerator class AccessKeyGenerator { @Test fun generate() { val generator = Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 32) println("generator.generateKey().lowercase()") println(generator.generateKey().lowercase()) } }
7
Kotlin
0
0
19229490436cf5c0096f25310959286645dc3914
436
finder-api
MIT License
ReviewerMobile/app/src/main/java/com/forzz/android/reviewermobile/presentation/authorization/Login.kt
Forzz
594,475,346
false
null
package com.forzz.android.reviewermobile.presentation.authorization import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.viewModels import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import com.forzz.android.reviewermobile.databinding.ActivityLoginBinding import com.forzz.android.reviewermobile.presentation.main_screen.MainActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class Login : AppCompatActivity() { private lateinit var activityLoginBinding: ActivityLoginBinding private val viewModel: LoginViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityLoginBinding = ActivityLoginBinding.inflate(layoutInflater) if (viewModel.isTokenExists()) { Log.d("TOKEN", "Token exists") } else { Log.d("TOKEN", "Token not exists") } activityLoginBinding.buttonSignIn.setOnClickListener { Log.d("BTN", "Clicked SIGN IN") doLogin() } viewModel.isError.observe(this, Observer { isError -> if (isError) { Toast.makeText(this, "Invalid login or password", Toast.LENGTH_LONG).show() } }) viewModel.isLoad.observe(this, Observer { isLoad -> if (isLoad) { startActivity(Intent(this, MainActivity::class.java)) } }) viewModel.tokenFromResponse.observe(this, Observer { token -> if (token != null) { viewModel.saveTokenToPreferences(token) } }) if (viewModel.getTokenFromPreferences() == null) { setContentView(activityLoginBinding.root) } else { startActivity(Intent(this, MainActivity::class.java)) } } private fun doLogin() { val login = activityLoginBinding.edittextPersonName.text.toString() val password = activityLoginBinding.passwordEdittext.text.toString() viewModel.saveData(login, password) viewModel.performLogin(login, password) } }
0
Kotlin
0
0
60fa59b577d15f04168908cb03c03cb4e7ee5cb7
2,294
Reviewer
MIT License
app/src/main/java/com/costular/atomtasks/ui/features/settings/SettingsModule.kt
costular
379,913,052
false
null
package com.costular.atomtasks.ui.features.settings import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import com.costular.atomtasks.domain.repository.SettingsRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class SettingsModule { @Singleton @Provides fun provideSettingsLocalDataSource( dataStore: DataStore<Preferences>, ): SettingsLocalDataSource = SettingsLocalDataSourceImpl(dataStore) @Singleton @Provides fun provideSettingsRepository( settingsLocalDataSource: SettingsLocalDataSource, ): SettingsRepository = SettingsRepositoryImpl(settingsLocalDataSource) }
2
Kotlin
0
2
f97f316b14f4b3664b385b880924f24f98a0a407
824
atom-habits
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/job/SafeJobRunnerTest.kt
ministryofjustice
533,838,017
false
{"Kotlin": 2936266, "Shell": 11326, "Dockerfile": 1490}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.job import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.within import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.times import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.Job import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.JobType import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.JobRepository import java.time.LocalDateTime import java.time.temporal.ChronoUnit class SafeJobRunnerTest { private val jobRepository: JobRepository = mock() private val runner = SafeJobRunner(jobRepository) private val jobEntityCaptor = argumentCaptor<Job>() @Test fun `runs job without error`() { runner.runJob(JobDefinition(JobType.ATTENDANCE_CREATE) {}) verify(jobRepository).saveAndFlush(jobEntityCaptor.capture()) with(jobEntityCaptor.firstValue) { assertThat(jobType).isEqualTo(JobType.ATTENDANCE_CREATE) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isTrue } } @Test fun `runs all dependent jobs without error`() { runner.runDependentJobs( JobDefinition(JobType.ATTENDANCE_CREATE) {}, JobDefinition(JobType.DEALLOCATE_ENDING) {}, ) verify(jobRepository, times(2)).saveAndFlush(jobEntityCaptor.capture()) with(jobEntityCaptor.firstValue) { assertThat(jobType).isEqualTo(JobType.ATTENDANCE_CREATE) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isTrue() } with(jobEntityCaptor.secondValue) { assertThat(jobType).isEqualTo(JobType.DEALLOCATE_ENDING) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isTrue() } } @Test fun `runs job with error`() { runner.runJob(JobDefinition(JobType.ATTENDANCE_CREATE) { throw RuntimeException("it failed") }) verify(jobRepository).saveAndFlush(jobEntityCaptor.capture()) with(jobEntityCaptor.firstValue) { assertThat(jobType).isEqualTo(JobType.ATTENDANCE_CREATE) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isFalse } } @Test fun `runs dependent jobs with error on first job`() { runner.runDependentJobs( JobDefinition(JobType.ATTENDANCE_CREATE) { throw RuntimeException("first job failed") }, JobDefinition(JobType.DEALLOCATE_ENDING) {}, ) verify(jobRepository, times(2)).saveAndFlush(jobEntityCaptor.capture()) with(jobEntityCaptor.firstValue) { assertThat(jobType).isEqualTo(JobType.ATTENDANCE_CREATE) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isFalse } with(jobEntityCaptor.secondValue) { assertThat(jobType).isEqualTo(JobType.DEALLOCATE_ENDING) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isFalse } } @Test fun `runs dependent jobs with error on second job`() { runner.runDependentJobs( JobDefinition(JobType.ATTENDANCE_CREATE) { }, JobDefinition(JobType.DEALLOCATE_ENDING) { throw RuntimeException("first job failed") }, ) verify(jobRepository, times(2)).saveAndFlush(jobEntityCaptor.capture()) with(jobEntityCaptor.firstValue) { assertThat(jobType).isEqualTo(JobType.ATTENDANCE_CREATE) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isTrue } with(jobEntityCaptor.secondValue) { assertThat(jobType).isEqualTo(JobType.DEALLOCATE_ENDING) assertThat(endedAt).isCloseTo(LocalDateTime.now(), within(2, ChronoUnit.SECONDS)) assertThat(successful).isFalse } } }
5
Kotlin
0
1
736daa905f8dd18778d827a6ec42dd794a65e3d8
4,039
hmpps-activities-management-api
MIT License
core/model/src/main/java/com/niyaj/model/EmployeeEnums.kt
skniyajali
644,752,474
false
{"Kotlin": 4169076, "Shell": 4123, "Java": 232}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.niyaj.model enum class EmployeeSalaryType { Daily, Monthly, Weekly, } enum class EmployeeType { PartTime, FullTime, } enum class PaymentType { Salary, Advanced, } enum class PaymentMode { Cash, Online, Both, }
39
Kotlin
0
1
a64f2043b4de365f05edc06344393083e0fed4d3
861
PoposRoom
Apache License 2.0
app/src/main/java/com/recep/technologynews/binding/BindingAdapter.kt
recfr
434,942,783
false
{"Kotlin": 24898}
package com.recep.technologynews.binding import android.widget.ImageView import androidx.databinding.BindingAdapter @BindingAdapter("thumbnail") fun bindThumbnails(view: ImageView, mediaResource: Int) { view.setImageResource(mediaResource) }
0
Kotlin
0
1
e06e69315c1de5f10dfa33651057ff3efb393ee9
247
TechNews
MIT License
device-server/src/main/kotlin/com/badoo/automation/deviceserver/ios/simulator/SimulatorProcess.kt
badoo
133,063,088
false
null
package com.badoo.automation.deviceserver.ios.simulator import com.badoo.automation.deviceserver.LogMarkers import com.badoo.automation.deviceserver.data.DeviceRef import com.badoo.automation.deviceserver.data.UDID import com.badoo.automation.deviceserver.host.IRemote import net.logstash.logback.marker.MapEntriesAppendingMarker import org.slf4j.LoggerFactory import org.slf4j.Marker import java.util.* class SimulatorProcess( private val remote: IRemote, private val udid: UDID, private val deviceRef: DeviceRef ) { private val logger = LoggerFactory.getLogger(javaClass.simpleName) private val commonLogMarkerDetails = mapOf( LogMarkers.DEVICE_REF to deviceRef, LogMarkers.UDID to udid, LogMarkers.HOSTNAME to remote.publicHostName ) private val logMarker: Marker = MapEntriesAppendingMarker(commonLogMarkerDetails) fun terminateChildProcess(processName: String) { val mainProcessPid = getSimulatorMainProcessPid() // Sends SIGKILL to all processes that: // 1. have parent pid $mainProcessPid // 2. and full command line contains substring $processName remote.execIgnoringErrors(listOf("/usr/bin/pkill", "-9", "-P", "$mainProcessPid", "-f", processName)) } fun getSimulatorMainProcessPid(): Int { val result = remote.execIgnoringErrors(listOf("/usr/bin/pgrep", "-fl", "launchd_sim")) if (result.isSuccess) { return parseSimulatorPid(result.stdOut) } val errorMessage = if (result.exitCode == 1) { "No launchd_sim processes found on ${remote.publicHostName}. Result: $result" } else { "Failed to get process list for simulators at $deviceRef. StdErr: ${result.stdErr}" } logger.error(logMarker, errorMessage) throw IllegalStateException(errorMessage) } private fun parseSimulatorPid(result: String): Int { val simulatorProcess = result.lineSequence().firstOrNull { it.contains(udid) && !it.contains("pgrep") } if (simulatorProcess != null) { return Scanner(simulatorProcess).nextInt() } val errorMessage = "No launchd_sim process for $udid found on ${remote.publicHostName}. Result: $result" logger.error(logMarker, errorMessage) throw IllegalStateException(errorMessage) } }
2
null
11
39
2569119e7d074356a320f5440470f74e1f41e4f3
2,366
ios-device-server
MIT License
device-server/src/main/kotlin/com/badoo/automation/deviceserver/ios/simulator/SimulatorProcess.kt
badoo
133,063,088
false
null
package com.badoo.automation.deviceserver.ios.simulator import com.badoo.automation.deviceserver.LogMarkers import com.badoo.automation.deviceserver.data.DeviceRef import com.badoo.automation.deviceserver.data.UDID import com.badoo.automation.deviceserver.host.IRemote import net.logstash.logback.marker.MapEntriesAppendingMarker import org.slf4j.LoggerFactory import org.slf4j.Marker import java.util.* class SimulatorProcess( private val remote: IRemote, private val udid: UDID, private val deviceRef: DeviceRef ) { private val logger = LoggerFactory.getLogger(javaClass.simpleName) private val commonLogMarkerDetails = mapOf( LogMarkers.DEVICE_REF to deviceRef, LogMarkers.UDID to udid, LogMarkers.HOSTNAME to remote.publicHostName ) private val logMarker: Marker = MapEntriesAppendingMarker(commonLogMarkerDetails) fun terminateChildProcess(processName: String) { val mainProcessPid = getSimulatorMainProcessPid() // Sends SIGKILL to all processes that: // 1. have parent pid $mainProcessPid // 2. and full command line contains substring $processName remote.execIgnoringErrors(listOf("/usr/bin/pkill", "-9", "-P", "$mainProcessPid", "-f", processName)) } fun getSimulatorMainProcessPid(): Int { val result = remote.execIgnoringErrors(listOf("/usr/bin/pgrep", "-fl", "launchd_sim")) if (result.isSuccess) { return parseSimulatorPid(result.stdOut) } val errorMessage = if (result.exitCode == 1) { "No launchd_sim processes found on ${remote.publicHostName}. Result: $result" } else { "Failed to get process list for simulators at $deviceRef. StdErr: ${result.stdErr}" } logger.error(logMarker, errorMessage) throw IllegalStateException(errorMessage) } private fun parseSimulatorPid(result: String): Int { val simulatorProcess = result.lineSequence().firstOrNull { it.contains(udid) && !it.contains("pgrep") } if (simulatorProcess != null) { return Scanner(simulatorProcess).nextInt() } val errorMessage = "No launchd_sim process for $udid found on ${remote.publicHostName}. Result: $result" logger.error(logMarker, errorMessage) throw IllegalStateException(errorMessage) } }
2
null
11
39
2569119e7d074356a320f5440470f74e1f41e4f3
2,366
ios-device-server
MIT License
app/src/main/java/com/example/jettrips/flights/model/FlightDatabase.kt
sampuran-singh
861,719,344
false
{"Kotlin": 146120}
package com.example.jettrips.flights.model import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [Flight::class, OperatingCity::class], version = 1) abstract class FlightDatabase() : RoomDatabase() { abstract fun get(): FlightDao }
0
Kotlin
0
1
f9b858fc874a68ed2f1f23e171b1fbc2480aeaae
271
JetTrips
Apache License 2.0
classroom/src/main/kotlin/com/radix2/algorithms/extras/InsertionSort.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.extras import java.util.* fun insertionSort2(n: Int, arr: Array<Int>): Unit { for (i in arr.lastIndex downTo 0) { val key = arr[i] var j: Int = i - 1 while (j >= 0) { if (arr[j] > key) { arr[j + 1] = arr[j] j-- } else { break } } arr[j + 1] = key println(arr.joinToString(" ")) } } fun insertionSort1(n: Int, arr: Array<Int>): Unit { val key = arr[arr.lastIndex] var i: Int = arr.lastIndex - 1 while (i >= 0) { if (arr[i] > key) { arr[i + 1] = arr[i] println(arr.joinToString(" ")) i-- } else { break } } arr[i + 1] = key println(arr.joinToString(" ")) } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray() insertionSort2(n, arr) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,058
coursera-algorithms-part1
Apache License 2.0
app/src/main/java/me/lazy_assedninja/demo/ui/documents_provider/di/DocumentsProviderModule.kt
henryhuang1219
357,838,778
false
null
package me.lazy_assedninja.demo.ui.documents_provider.di import androidx.lifecycle.ViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import me.lazy_assedninja.demo.di.ViewModelKey import me.lazy_assedninja.demo.ui.documents_provider.DocumentsProviderViewModel /** * Definition of dependencies, tell Dagger how to provide classes. */ @Suppress("unused") @Module abstract class DocumentsProviderModule { @Binds @IntoMap @ViewModelKey(DocumentsProviderViewModel::class) abstract fun bindDocumentsProviderViewModel( documentsProviderViewModel: DocumentsProviderViewModel ): ViewModel }
0
Kotlin
1
2
2f5a79974f8d6b6af516a8959824558324bab8ce
651
Android-Demo
Apache License 2.0
model/src/test/kotlin/io/sparkled/model/util/IdUtilsTest.kt
sparkled
53,776,686
false
{"Kotlin": 321814, "TypeScript": 141619, "JavaScript": 133004, "CSS": 5012, "HTML": 353}
package io.sparkled.model.util import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.longs.shouldBeLessThan import io.kotest.matchers.shouldBe import io.sparkled.model.util.IdUtils.uniqueId import kotlin.system.measureTimeMillis class IdUtilsTest : StringSpec() { init { "can generate random identifiers" { measureTimeMillis { repeat(1000) { val id = uniqueId() id.length shouldBe 12 } } shouldBeLessThan 100 } } }
20
Kotlin
21
71
681240d1a17bfffbd22da75d00ae1188f26c6a76
555
sparkled
MIT License
fontawesome/src/de/msrd0/fontawesome/icons/FA_MICROSCOPE.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID object FA_MICROSCOPE: Icon { override val name get() = "Microscope" override val unicode get() = "f610" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M160 320h12v16c0 8.84 7.16 16 16 16h40c8.84 0 16-7.16 16-16v-16h12c17.67 0 32-14.33 32-32V64c0-17.67-14.33-32-32-32V16c0-8.84-7.16-16-16-16h-64c-8.84 0-16 7.16-16 16v16c-17.67 0-32 14.33-32 32v224c0 17.67 14.33 32 32 32zm304 128h-1.29C493.24 413.99 512 369.2 512 320c0-105.88-86.12-192-192-192v64c70.58 0 128 57.42 128 128s-57.42 128-128 128H48c-26.51 0-48 21.49-48 48 0 8.84 7.16 16 16 16h480c8.84 0 16-7.16 16-16 0-26.51-21.49-48-48-48zm-360-32h208c4.42 0 8-3.58 8-8v-16c0-4.42-3.58-8-8-8H104c-4.42 0-8 3.58-8 8v16c0 4.42 3.58 8 8 8z"/></svg>""" else -> null } }
0
Kotlin
0
0
2fc4755051325e730e9d012c9dfe94f5ea800fdd
1,738
fontawesome-kt
Apache License 2.0
app/presentation/src/main/java/com/wiensmit/rmapp/presentation/components/compose/theme/Type.kt
wiensmit
672,520,737
false
null
package com.wiensmit.rmapp.presentation.components.compose.theme import android.content.res.Configuration.UI_MODE_NIGHT_NO import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.wiensmit.rmapp.presentation.R internal object TypographyToken { private val ChaletNewYork60 = FontFamily(Font(R.font.chalet_new_york_sixty)) private val ChaletLondon60 = FontFamily(Font(R.font.chalet_london_sixty)) val header = TextStyle( fontFamily = ChaletNewYork60, fontSize = 30.sp ) val subtitle = TextStyle( fontFamily = ChaletNewYork60, fontSize = 20.sp ) val body = TextStyle( fontFamily = ChaletLondon60, fontSize = 16.sp, lineHeight = 26.sp ) val bodyBold = TextStyle( fontFamily = ChaletNewYork60, fontSize = 16.sp, lineHeight = 26.sp ) val button = TextStyle( fontFamily = ChaletNewYork60, fontSize = 16.sp ) } @Preview(showBackground = true, uiMode = UI_MODE_NIGHT_NO) @Composable private fun PreviewTypographyLight() = Typography() @Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES) @Composable private fun PreviewTypographyDark() = Typography() @Composable private fun Typography() { AppTheme { Surface(modifier = Modifier.fillMaxSize(), color = AppTheme.color.background) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(15.dp) ) { Text("Heading", color = AppTheme.color.onBackground, style = AppTheme.typography.heading) Text("Subtitle", color = AppTheme.color.onBackground, style = AppTheme.typography.subtitle) Text("Body", color = AppTheme.color.onBackground, style = AppTheme.typography.body) Text("Body Bold", color = AppTheme.color.onBackground, style = AppTheme.typography.bodyBold) Text("Button", color = AppTheme.color.onBackground, style = AppTheme.typography.button) } } } }
0
Kotlin
0
0
1b3d022dd9d49ac07345e271ad5da82638909045
2,694
rm-app
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/iottwinmaker/StatusPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.iottwinmaker import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.iottwinmaker.CfnEntity @Generated public fun buildStatusProperty(initializer: @AwsCdkDsl CfnEntity.StatusProperty.Builder.() -> Unit): CfnEntity.StatusProperty = CfnEntity.StatusProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
423
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/example/baobuzz/interfaces/FootballApi.kt
muchaisam
709,855,143
false
{"Kotlin": 110371}
package com.example.baobuzz.interfaces import com.example.baobuzz.models.ApiResponse import com.example.baobuzz.models.Coach import com.example.baobuzz.models.FixturesResponse import com.example.baobuzz.models.StandingsResponse import com.example.baobuzz.models.TransfersResponse import retrofit2.http.GET import retrofit2.http.Query interface FootballApi { @GET("fixtures") suspend fun getUpcomingFixtures( @Query("league") leagueId: Int, @Query("next") next: Int, @Query("timezone") timezone: String, ): FixturesResponse @GET("transfers") suspend fun getTransfers(@Query("team") teamId: Int): TransfersResponse @GET("standings") suspend fun getStandings( @Query("league") league: Int, @Query("season") season: Int ): StandingsResponse @GET("coachs") suspend fun getCoach(@Query("id") id: Int): ApiResponse<Coach> }
0
Kotlin
0
2
71cb36fecfc9a6a52b85c4136b046e413730899f
903
BaoBuzz
MIT License
app/src/main/java/id/davidpratama/todoapp/model/Model.kt
daviddprtma
481,209,970
false
{"Kotlin": 23530}
package id.davidpratama.todoapp.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class ToDo( @ColumnInfo(name = "title") var title: String, @ColumnInfo(name = "notes") var notes: String, @ColumnInfo(name = "priority") var priority: Int, @ColumnInfo(name = "is_done") var is_done : Int = 0, @ColumnInfo(name = "todo_date") var todo_date : Int ){ @PrimaryKey(autoGenerate = true) var uuid: Int=0 }
0
Kotlin
0
1
1558cdeff94417aadd8df608f4dd672608664180
507
160419103-ToDo-App
Apache License 2.0
src/main/java/org/openwilma/kotlin/utils/SessionUtils.kt
OpenWilma
533,496,981
false
{"Kotlin": 129825}
package org.openwilma.kotlin.utils import com.google.gson.reflect.TypeToken import org.openwilma.kotlin.OpenWilma import org.openwilma.kotlin.classes.errors.ExpiredSessionError import org.openwilma.kotlin.classes.responses.JSONErrorResponse import org.openwilma.kotlin.config.Config import org.openwilma.kotlin.parsers.WilmaJSONParser import java.lang.Exception import java.util.regex.Pattern object SessionUtils { private val invalidSessionErrorCodes = listOf("common-20", "common-18", "common-15") fun parseSessionCookie(cookieValue: String?): String? { val sessionPattern = Pattern.compile(Config.sessionRegex) val valueMatcher = sessionPattern.matcher(cookieValue) return if (valueMatcher.find()) { valueMatcher.group(2) } else null } fun checkSessionExpiration(response: String) { var containsError = false try { val error = WilmaJSONParser.gson.fromJson<JSONErrorResponse>(response, object: TypeToken<JSONErrorResponse>() {}.type) error.wilmaError?.let { containsError = invalidSessionErrorCodes.contains(it.errorID) } } catch (ignored: Exception) {} if (containsError && OpenWilma.checkSessionErrors) { throw ExpiredSessionError() } } }
0
Kotlin
1
5
52066c9cc2ba77ea37c52c8c0c724e56c1ce7ff2
1,315
openwilma.kotlin
Apache License 2.0
encoder/src/main/java/com/pedro/encoder/input/video/facedetector/Face.kt
pedroSG94
79,667,969
false
null
/* * Copyright (C) 2024 pedroSG94. * * 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.pedro.encoder.input.video.facedetector import android.graphics.Point import android.graphics.Rect /** * Created by pedro on 10/10/23. */ data class Face( val id: Int?, //depend if device support it, if not supported the value could be -1 val leftEye: Point?, //depend if device support it val rightEye: Point?, //depend if device support it val mouth: Point?, //depend if device support it val rect: Rect, val score: Int //range 1 to 100 )
87
null
772
2,545
eca59948009d5a7b564f9a838c149b850898d089
1,063
RootEncoder
Apache License 2.0
framework666/src/main/java/studio/attect/framework666/extensions/Gson.kt
Attect
192,833,321
false
null
package studio.attect.framework666.extensions import com.google.gson.Gson import com.google.gson.JsonIOException import com.google.gson.JsonSyntaxException import com.google.gson.reflect.TypeToken /** * 相当方便的Gson字符串转对象 * 解决了嵌套范型麻烦的问题 * 做了异常捕获,防止太多意外崩溃影响体验 * * 内联函数(为了解决泛型) * 只能在Kotlin中使用 * * @param T 期望结果类型 * @param json JSON格式的字符串 * @return 解析JSON后得到的对象,可能为null */ inline fun <reified T> Gson.fromJson(json: String?): T? { try { return fromJson<T>(json, object : TypeToken<T>() {}.type) } catch (e: JsonSyntaxException) { e.printStackTrace() } catch (e: JsonIOException) { e.printStackTrace() } return null }
0
null
1
6
22285ee7026abf6fd00150af6a96d12287154336
667
Android-Framework666
Apache License 2.0
MapboxSearch/base/src/androidTest/java/com/mapbox/search/base/SdkInitializationTest.kt
mapbox
438,355,708
false
{"Kotlin": 2244061, "Java": 41736, "Python": 18980, "Shell": 17499}
package com.mapbox.search.base import androidx.test.ext.junit.runners.AndroidJUnit4 import com.mapbox.common.SdkInfoRegistryFactory import com.mapbox.search.base.utils.UserAgentProvider import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) internal class SdkInitializationTest { @Test fun testSdkInformationProvided() { val sdkInformation = SdkInfoRegistryFactory.getInstance().sdkInformation.find { it.packageName == UserAgentProvider.sdkPackageName } assertNotNull(sdkInformation) assertEquals(UserAgentProvider.sdkName, sdkInformation!!.name) assertEquals(UserAgentProvider.sdkVersionName, sdkInformation.version) assertEquals(UserAgentProvider.sdkPackageName, sdkInformation.packageName) } }
17
Kotlin
7
33
369bc63bb10a7da7f2b3e57839ba47b762c87b99
878
mapbox-search-android
Apache License 2.0
mobile_app1/module407/src/main/java/module407packageKt0/Foo9.kt
uber-common
294,831,672
false
null
package module407packageKt0; annotation class Foo9Fancy @Foo9Fancy class Foo9 { fun foo0(){ module407packageKt0.Foo8().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
229
android-build-eval
Apache License 2.0
analysis/low-level-api-fir/testData/getOrBuildFirBinary/simpleFunction.kt
JetBrains
3,432,266
false
null
// DECLARATION_TYPE: org.jetbrains.kotlin.psi.KtNamedFunction object FooBar { fun doSmth() {} }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
100
kotlin
Apache License 2.0
app/src/main/java/net/mm2d/timer/delegate/StopwatchViewModel.kt
ohmae
482,237,183
false
{"Kotlin": 102562}
/* * Copyright (c) 2022 大前良介 (<NAME>) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.timer.delegate import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import net.mm2d.timer.settings.Mode import net.mm2d.timer.settings.SettingsRepository import net.mm2d.timer.settings.StopwatchRunningState import net.mm2d.timer.settings.StopwatchRunningStateRepository import net.mm2d.timer.sound.SoundEffect import javax.inject.Inject @HiltViewModel class StopwatchViewModel @Inject constructor( settingsRepository: SettingsRepository, private val stateRepository: StopwatchRunningStateRepository, private val soundEffect: SoundEffect, ) : ViewModel() { val uiStateLiveData: LiveData<UiState> = settingsRepository.flow .map { UiState( mode = it.mode, hourEnabled = it.hourEnabled, ) } .distinctUntilChanged() .asLiveData() data class UiState( val mode: Mode, val hourEnabled: Boolean, ) val runningStateLiveData: LiveData<StopwatchRunningState> = stateRepository.flow.asLiveData() fun updateState(state: StopwatchRunningState) { viewModelScope.launch { stateRepository.updateState(state) } } fun playSound() { soundEffect.play() } }
0
Kotlin
0
3
2d1dfcb9d178d63ddb3a25ae184657a0187f62f9
1,646
fullscreen-timer
MIT License