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
lib/agency/src/main/kotlin/org/kkris/osmgtfs/agency/Util.kt
kkris
273,951,336
false
null
package org.kkris.osmgtfs.agency import de.jollyday.HolidayManager import de.jollyday.ManagerParameters import java.time.LocalDate import java.util.* object Util { internal fun getHolidays(locale: Locale, start: LocalDate, end: LocalDate): List<LocalDate> { val holidays = (start.year..end.year).flatMap { year -> getHolidaysInYear(locale, year) } return holidays .filter { it in start..end } .sorted() } private fun getHolidaysInYear(locale: Locale, year: Int): List<LocalDate> { val parameter = ManagerParameters.create(locale) return HolidayManager.getInstance(parameter).getHolidays(year) .map { it.date } } }
0
Kotlin
0
2
263d25158c2741dd00d639d1b17a95080f761db7
723
osm-gtfs
MIT License
app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/view/adapter/ArticleListAdapter.kt
mizukami2005
72,331,822
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 15, "Kotlin": 24}
package com.mizukami2005.mizukamitakamasa.qiitaclient.view.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import com.mizukami2005.mizukamitakamasa.qiitaclient.model.Article import com.mizukami2005.mizukamitakamasa.qiitaclient.view.ArticleView import java.util.* /** * Created by mizukamitakamasa on 2016/09/25. */ class ArticleListAdapter(private val context: Context) : BaseAdapter() { internal var articles = emptyArray<Article>() override fun getCount(): Int = articles.size override fun getItem(position: Int): Any? = articles[position] override fun getItemId(position: Int): Long = 0 override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View = ((convertView as? ArticleView) ?: ArticleView(context)).apply { setArticle(articles[position]) } fun addList(list: Array<Article>) { articles += list } fun clear() { articles = emptyArray<Article>() } }
2
Kotlin
1
1
52ca2833d9b87ffdcd875f5e1f827b89dded30fd
1,014
qiita-client-app-android
MIT License
app/src/main/java/com/spaceapp/presentation/explore/components/ExploreCard.kt
AhmetOcak
552,274,999
false
{"Kotlin": 385521}
package com.spaceapp.presentation.explore.components import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.spaceapp.R import com.spaceapp.core.designsystem.theme.White import com.spaceapp.core.navigation.NavName import com.spaceapp.core.navigation.NavScreen @Composable fun ExploreCard( modifier: Modifier = Modifier, navController: NavController, name: String, description: String, info1: String, info2: String, imageId: Int, imagePadding: PaddingValues = PaddingValues(0.dp), contentScale: ContentScale = ContentScale.Fit, backgroundColor: Color = MaterialTheme.colorScheme.surface ) { Box { Card( modifier = modifier .width(LocalConfiguration.current.screenWidthDp.dp - 96.dp) .height(320.dp) .clickable { try { navController.navigate("${NavName.explore_detail_screen_name}/$name/$description/$info1/$info2") { popUpTo(route = NavScreen.ExploreScreen.route) } } catch (e: Exception) { Log.e("e", e.toString()) } }, shape = RoundedCornerShape(32.dp), colors = CardDefaults.cardColors(backgroundColor), ) { Column( modifier = modifier.fillMaxSize(), horizontalAlignment = Alignment.Start ) { Image( modifier = modifier .fillMaxWidth() .height(220.dp) .weight(6f) .padding(imagePadding), painter = painterResource(id = imageId), contentDescription = null, contentScale = contentScale ) Row( modifier = modifier .fillMaxWidth() .weight(2f), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( modifier = modifier.padding(start = 16.dp, bottom = 16.dp), text = name, style = MaterialTheme.typography.headlineSmall ) IconButton( modifier = modifier.padding(bottom = 16.dp), onClick = { try { navController.navigate("${NavName.explore_detail_screen_name}/$name/$description/$info1/$info2") { popUpTo(route = NavScreen.ExploreScreen.route) } }catch (e: Exception) { Log.e("e", e.toString()) } } ) { Icon( painter = painterResource(id = R.drawable.ic_baseline_arrow_forward_ios), contentDescription = null, tint = White ) } } } } } }
0
Kotlin
1
2
faac912d41d8decca902f79d725aa560d1e6a7bf
4,614
Explore-Universe
MIT License
urbanairship-core/src/main/java/com/urbanairship/http/Response.kt
urbanairship
58,972,818
false
null
/* Copyright Airship and Contributors */ package com.urbanairship.http import android.net.Uri import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import com.urbanairship.UALog import com.urbanairship.util.Clock import com.urbanairship.util.DateUtils import com.urbanairship.util.UAHttpStatusUtil import java.text.ParseException import java.util.concurrent.TimeUnit /** * Model object containing response information from a request. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public data class Response<T> @JvmOverloads constructor( val status: Int, val result: T, val body: String? = null, val headers: Map<String, String> = emptyMap(), ) { public fun <R> map(mapper: (T) -> R): Response<R> { return Response( this.status, mapper(this.result), this.body, this.headers, ) } /** * True if the status is 200-299, otherwise false. * * @return `true` if the status is 200-299, otherwise `false`. */ val isSuccessful: Boolean get() = UAHttpStatusUtil.inSuccessRange(status) /** * True if the status is 500-599, otherwise false. * * @return `true` if the status is 500-599, otherwise `false`. */ val isServerError: Boolean get() = UAHttpStatusUtil.inServerErrorRange(status) /** * True if the status is 400-499, otherwise false. * * @return `true` if the status is 400-499, otherwise `false`. */ val isClientError: Boolean get() = UAHttpStatusUtil.inClientErrorRange(status) /** * True if the status is 429, otherwise false. * * @return `true` if the status is 429, otherwise `false`. */ val isTooManyRequestsError: Boolean get() = status == 429 /** * Returns the location header if set. * * @return The location header if set, otherwise null. */ val locationHeader: Uri? get() { val location = headers["Location"] ?: return null return try { Uri.parse(location) } catch (e: Exception) { UALog.e("Failed to parse location header.") null } } /** * Returns the retry-after header if set. * * @param timeUnit The resulting time unit. * @param defaultValue The default value. * @return The retry-after in the time unit if set, otherwise the defaultValue. */ public fun getRetryAfterHeader(timeUnit: TimeUnit, defaultValue: Long): Long { return getRetryAfterHeader(timeUnit, defaultValue, Clock.DEFAULT_CLOCK) } @VisibleForTesting public fun getRetryAfterHeader(timeUnit: TimeUnit, defaultValue: Long, clock: Clock): Long { val retryAfter = headers["Retry-After"] ?: return defaultValue try { val retryDate = DateUtils.parseIso8601(retryAfter) val milliseconds = retryDate - clock.currentTimeMillis() return timeUnit.convert(milliseconds, TimeUnit.MILLISECONDS) } catch (ignored: ParseException) { } try { val seconds = retryAfter.toLong() return timeUnit.convert(seconds, TimeUnit.SECONDS) } catch (ignored: Exception) { } UALog.e("Invalid RetryAfter header %s", retryAfter) return defaultValue } }
2
null
122
111
21d49c3ffd373e3ba6b51a706a4839ab3713db11
3,412
android-library
Apache License 2.0
remote-server/src/main/kotlin/Form.kt
CLOVIS-AI
464,628,603
false
null
package opensavvy.formulaide.remote.server import io.ktor.server.routing.* import opensavvy.backbone.Ref.Companion.request import opensavvy.formulaide.core.Department import opensavvy.formulaide.core.Form import opensavvy.formulaide.core.Template import opensavvy.formulaide.remote.api import opensavvy.formulaide.remote.dto.SchemaDto.Companion.toDto import opensavvy.formulaide.remote.dto.SchemaDto.Companion.toForm import opensavvy.spine.Identified import opensavvy.spine.ktor.server.route import opensavvy.state.progressive.firstValue fun Routing.forms( departments: Department.Service, templates: Template.Service, forms: Form.Service, ) { route(api.forms.get, contextGenerator) { forms.list(includeClosed = parameters.includeClosed) .bind() .map { api.templates.id.idOf(it.id) } } route(api.forms.create, contextGenerator) { forms.create( body.name, body.firstVersion.toForm( decodeDepartment = { api.departments.id.refOf(it, departments).bind() }, decodeTemplate = { api.templates.id.version.refOf(it, templates).bind() } ) ).bind() .let { api.templates.id.idOf(it.id) } .let { Identified(it, Unit) } } route(api.forms.id.create, contextGenerator) { val ref = api.forms.id.refOf(id, forms).bind() forms.createVersion( ref, body.toForm( decodeDepartment = { api.departments.id.refOf(it, departments).bind() }, decodeTemplate = { api.templates.id.version.refOf(it, templates).bind() } ) ).bind() .let { api.forms.id.version.idOf(it.form.id, it.version.toString()) } .let { Identified(it, Unit) } } route(api.forms.id.edit, contextGenerator) { val ref = api.forms.id.refOf(id, forms).bind() forms.edit( ref, name = body.name, open = body.open, public = body.public, ).bind() } route(api.forms.id.get, contextGenerator) { val ref = api.forms.id.refOf(id, forms).bind() ref.request().firstValue().bind() .toDto() } route(api.forms.id.version.get, contextGenerator) { val version = api.forms.id.version.refOf(id, forms).bind() version.request().firstValue().bind() .toDto() } }
0
Kotlin
0
0
aa086b58e67a1cc0ae0fb5a936fe661b46646419
2,138
Formulaide
Apache License 2.0
start/src/main/java/com/codelabs/state/todo/TodoViewModel.kt
Tonnie-Dev
398,608,286
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.codelabs.state.todo import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import timber.log.Timber class TodoViewModel : ViewModel() { // remove the LiveData and replace it with a mutableStateListOf //private var _todoItems = MutableLiveData(listOf<TodoItem>()) //val todoItems: LiveData<List<TodoItem>> = _todoItems //STATES // state: todoItems var todoItems = mutableStateListOf<TodoItem>() //restricting writes to this state object - only visible inside the ViewModel. private set //state private var editPosition by mutableStateOf(-1) // state val currentEditItem: TodoItem? get() = todoItems.getOrNull(editPosition) //EVENTS // event: add Item to the list fun addItem(item: TodoItem) { todoItems.add(item) } // event: item selected fun onEditItemSelected(item: TodoItem) { editPosition = todoItems.indexOf(item) Timber.i("Inside onEditItemSelected - position is: $editPosition") } //event: editItemChanged fun onEditItemChange(item: TodoItem) { //ensure the currentItem is non-null val currentItem = requireNotNull(currentEditItem) //ensure the ids match otherwise throw an exception require(currentItem.id == item.id) { //exception message "You can only change an item with the same id as currentEditItem" } //set currentItem to item todoItems[editPosition] = item Timber.i("Inside onEditItemChange - position is: $editPosition") } //event: editing done fun onEditDone() { editPosition = -1 Timber.i("Inside onEditDone() - position is: $editPosition") } // event: removeItem fun removeItem(item: TodoItem) { todoItems.remove(item) onEditDone() // don't keep the editor open when removing items } }
0
Kotlin
0
0
89daf953bc546c3ea21f4198973c8612bab82970
2,689
StateCodelab
Apache License 2.0
sentry/src/test/java/io/sentry/NoOpTransactionTest.kt
getsentry
3,368,190
false
null
package io.sentry import kotlin.test.Test import kotlin.test.assertNotNull import kotlin.test.assertNull class NoOpTransactionTest { private val transaction = NoOpTransaction.getInstance() @Test fun `startChild does not return null`() { assertNotNull(transaction.startChild("op")) assertNotNull(transaction.startChild("op", "desc")) } @Test fun `getSpanContext does not return null`() { assertNotNull(transaction.spanContext) } @Test fun `getOperation does not return null`() { assertNotNull(transaction.operation) } @Test fun `isProfileSampled returns null`() { assertNull(transaction.isProfileSampled) } }
170
null
400
920
ffa66c8d96f66d20feace09ea16d0c66e494f515
707
sentry-java
MIT License
plugins/kotlin/compiler-plugins/parcelize/tests/k1/test/org/jetbrains/kotlin/parcelize/ide/test/AbstractParcelizeK1QuickFixTest.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.pacelize.ide.test import org.jetbrains.kotlin.checkers.AbstractKotlinHighlightVisitorTest abstract class AbstractParcelizeCheckerTest : AbstractKotlinHighlightVisitorTest() { override fun setUp() { super.setUp() addParcelizeLibraries(module) } override fun tearDown() { try { removeParcelizeLibraries(module) } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } }
214
null
4829
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
648
intellij-community
Apache License 2.0
apollo-api/src/commonTest/kotlin/com/apollographql/apollo/api/internal/SimpleResponseReaderTest.kt
apollostack
69,469,299
false
null
package com.apollographql.apollo.api.internal import com.apollographql.apollo.api.BigDecimal import com.apollographql.apollo.api.CustomTypeAdapter import com.apollographql.apollo.api.CustomTypeValue import com.apollographql.apollo.api.EMPTY_OPERATION import com.apollographql.apollo.api.ResponseField import com.apollographql.apollo.api.ResponseField.Condition.Companion.typeCondition import com.apollographql.apollo.api.ScalarType import com.apollographql.apollo.api.ScalarTypeAdapters import kotlin.reflect.KClass import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.test.fail class SimpleResponseReaderTest { private val noConditions: List<ResponseField.Condition> = emptyList() @Test fun readString() { val successField = ResponseField.forString("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forString("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = "response1" recordSet["successFieldName"] = "response2" recordSet["classCastExceptionField"] = 1 val responseReader = responseReader(recordSet) assertEquals(expected = "response1", actual = responseReader.readString(successField)) try { responseReader.readString(classCastExceptionField) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readInt() { val successField = ResponseField.forInt("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forInt("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = BigDecimal(1) recordSet["successFieldName"] = BigDecimal(2) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals(expected = 1, actual = responseReader.readInt(successField)) try { responseReader.readInt(classCastExceptionField) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readLong() { val successField = ResponseField.forLong("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forLong("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = BigDecimal(1) recordSet["successFieldName"] = BigDecimal(2) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals(expected = 1, actual = responseReader.readLong(successField) as Long) try { responseReader.readLong(classCastExceptionField) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readDouble() { val successField = ResponseField.forDouble("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forDouble("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = BigDecimal(1.1) recordSet["successFieldName"] = BigDecimal(2.2) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals(expected = 1.1, actual = responseReader.readDouble(successField)!!) try { responseReader.readDouble(classCastExceptionField) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readBoolean() { val successField = ResponseField.forBoolean("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forBoolean("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = true recordSet["successFieldName"] = false recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertTrue(responseReader.readBoolean(successField)!!) try { responseReader.readBoolean(classCastExceptionField) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readObject() { val responseObject = Any() val successField = ResponseField.forObject("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forObject("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = emptyMap<Any, Any>() recordSet["successFieldName"] = emptyMap<Any, Any>() recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = responseObject, actual = responseReader.readObject(successField, object : ResponseReader.ObjectReader<Any> { override fun read(reader: ResponseReader): Any = responseObject })) try { responseReader.readObject(classCastExceptionField, object : ResponseReader.ObjectReader<Any> { override fun read(reader: ResponseReader): Any { return reader.readString(ResponseField.forString("anything", "anything", null, true, noConditions))!! } }) fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readFragment() { val responseObject = Any() val successFragmentField = ResponseField.forFragment("__typename", "__typename", listOf<ResponseField.Condition>(typeCondition(arrayOf("Fragment1")))) val skipFragmentField = ResponseField.forFragment("__typename", "__typename", listOf<ResponseField.Condition>(typeCondition(arrayOf("Fragment2")))) val recordSet: MutableMap<String, Any> = HashMap() recordSet["__typename"] = "Fragment1" val responseReader = responseReader(recordSet) assertEquals( expected = responseObject, actual = responseReader.readFragment(successFragmentField, object : ResponseReader.ObjectReader<Any> { override fun read(reader: ResponseReader): Any = responseObject }) ) assertNull( responseReader.readFragment(skipFragmentField, object : ResponseReader.ObjectReader<Any> { override fun read(reader: ResponseReader): Any = responseObject }) ) } @Test fun readCustomObjectMap() { val mapScalarType: ScalarType = object : ScalarType { override fun typeName(): String { return Map::class.simpleName!! } override fun className(): String { return "kotlin.collections.Map" } } val successField = ResponseField.forCustomType("successFieldResponseName", "successFieldName", null, false, mapScalarType, noConditions) val objectMap = mutableMapOf<String, Any>() objectMap["string"] = "string" objectMap["boolean"] = true objectMap["double"] = 1.99 objectMap["float"] = 2.99f objectMap["long"] = 3L objectMap["int"] = 4 objectMap["stringList"] = listOf("string1", "string2") objectMap["booleanList"] = listOf("true", "false") objectMap["doubleList"] = listOf(1.99, 2.99) objectMap["floatList"] = listOf(3.99f, 4.99f, 5.99f) objectMap["longList"] = listOf(5L, 7L) objectMap["intList"] = listOf(8, 9, 10) objectMap["object"] = HashMap(objectMap) objectMap["objectList"] = listOf(HashMap(objectMap), HashMap(objectMap)) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = objectMap recordSet["successFieldName"] = objectMap val responseReader = responseReader(recordSet) assertEquals(expected = objectMap, actual = responseReader.readCustomType<Map<*, *>>(successField)) } @Test fun readCustomObjectList() { val listScalarType: ScalarType = object : ScalarType { override fun typeName(): String { return List::class.simpleName!! } override fun className(): String { return "kotlin.collections.List" } } val successField = ResponseField.forCustomType("successFieldResponseName", "successFieldName", null, false, listScalarType, noConditions) val objectMap: MutableMap<String, Any> = HashMap() objectMap["string"] = "string" objectMap["boolean"] = true val objectList = listOf<Map<String, Any>>(objectMap, objectMap) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = objectList recordSet["successFieldName"] = objectList val responseReader = responseReader(recordSet) assertEquals(expected = objectList, actual = responseReader.readCustomType<List<*>>(successField)) } @Test fun readCustomWithDefaultAdapter() { val stringField = ResponseField.forCustomType("stringField", "stringField", null, false, scalarTypeFor(String::class, "kotlin.String"), noConditions) val booleanField = ResponseField.forCustomType("booleanField", "booleanField", null, false, scalarTypeFor(Boolean::class, "kotlin.Boolean"), noConditions) val integerField = ResponseField.forCustomType("integerField", "integerField", null, false, scalarTypeFor(Int::class, "kotlin.Int"), noConditions) val longField = ResponseField.forCustomType("longField", "longField", null, false, scalarTypeFor(Long::class, "kotlin.Long"), noConditions) val floatField = ResponseField.forCustomType("floatField", "floatField", null, false, scalarTypeFor(Float::class, "kotlin.Float"), noConditions) val doubleField = ResponseField.forCustomType("doubleField", "doubleField", null, false, scalarTypeFor(Double::class, "kotlin.Double"), noConditions) val unsupportedField = ResponseField.forCustomType("unsupportedField", "unsupportedField", null, false, scalarTypeFor(RuntimeException::class, "kotlin.RuntimeException"), noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet[stringField.responseName] = "string" recordSet[booleanField.responseName] = true recordSet[integerField.responseName] = BigDecimal(1) recordSet[longField.responseName] = BigDecimal(2) recordSet[floatField.responseName] = BigDecimal("3.99") recordSet[doubleField.responseName] = BigDecimal("4.99") recordSet[unsupportedField.responseName] = "smth" val responseReader = responseReader(recordSet) assertEquals(expected = "string", actual = responseReader.readCustomType(stringField)!!) assertEquals(expected = true, actual = responseReader.readCustomType(booleanField)!!) assertEquals(expected = 1, actual = responseReader.readCustomType(integerField)!!) assertEquals(expected = 2L, actual = responseReader.readCustomType(longField)!!) assertEquals(expected = 3.99f, actual = responseReader.readCustomType(floatField)!!) assertEquals(expected = 4.99, actual = responseReader.readCustomType(doubleField)!!) try { responseReader.readCustomType<Any>(unsupportedField) fail("Expect IllegalArgumentException") } catch (expected: IllegalArgumentException) { // expected } } @Test fun readStringList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf("value1", "value2", "value3") recordSet["successFieldName"] = listOf("value4", "value5") recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf("value1", "value2", "value3"), actual = responseReader.readList<Any>(successField) { reader: ResponseReader.ListItemReader -> reader.readString() } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readIntList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf(BigDecimal(1), BigDecimal(2), BigDecimal(3)) recordSet["successFieldName"] = listOf(BigDecimal(4), BigDecimal(5)) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf(1, 2, 3), actual = responseReader.readList<Any>(successField) { reader: ResponseReader.ListItemReader -> reader.readInt() } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readLongList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf(BigDecimal(1), BigDecimal(2), BigDecimal(3)) recordSet["successFieldName"] = listOf(BigDecimal(4), BigDecimal(5)) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf(1, 2, 3), actual = responseReader.readList<Any>(successField) { reader: ResponseReader.ListItemReader -> reader.readInt() } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readDoubleList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf(BigDecimal(1), BigDecimal(2), BigDecimal(3)) recordSet["successFieldName"] = listOf(BigDecimal(4), BigDecimal(5)) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf(1.0, 2.0, 3.0), actual = responseReader.readList<Any>(successField) { reader: ResponseReader.ListItemReader -> reader.readDouble() } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readBooleanList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf(true, false, true) recordSet["successFieldName"] = listOf(false, false) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf(true, false, true), actual = responseReader.readList<Any>(successField) { reader: ResponseReader.ListItemReader -> reader.readBoolean() } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readObjectList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val responseObject1 = Any() val responseObject2 = Any() val responseObject3 = Any() val objects = listOf(responseObject1, responseObject2, responseObject3) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = listOf(emptyMap(), emptyMap(), emptyMap<Any, Any>()) recordSet["successFieldName"] = listOf(emptyMap(), emptyMap(), emptyMap<Any, Any>()) recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) var index = 0 assertEquals( expected = objects, actual = responseReader.readList(successField) { reader -> reader.readObject { objects[index++] } } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun readListOfScalarList() { val successField = ResponseField.forList("successFieldResponseName", "successFieldName", null, false, noConditions) val classCastExceptionField = ResponseField.forList("classCastExceptionField", "classCastExceptionField", null, false, noConditions) val response1 = listOf(listOf("1", "2"), listOf("3", "4", "5")) val response2 = listOf(listOf("6", "7", "8"), listOf("9", "0")) val recordSet: MutableMap<String, Any> = HashMap() recordSet["successFieldResponseName"] = response1 recordSet["successFieldName"] = response2 recordSet["classCastExceptionField"] = "anything" val responseReader = responseReader(recordSet) assertEquals( expected = listOf(listOf("1", "2"), listOf("3", "4", "5")), actual = responseReader.readList(successField) { reader -> reader.readList(ResponseReader.ListItemReader::readString) } ) try { responseReader.readList(classCastExceptionField) { null!! } fail("expected ClassCastException") } catch (expected: ClassCastException) { // expected } } @Test fun optionalFieldsIOException() { val responseReader = responseReader(emptyMap()) responseReader.readString(ResponseField.forString("stringField", "stringField", null, true, noConditions)) responseReader.readInt(ResponseField.forInt("intField", "intField", null, true, noConditions)) responseReader.readLong(ResponseField.forLong("longField", "longField", null, true, noConditions)) responseReader.readDouble(ResponseField.forDouble("doubleField", "doubleField", null, true, noConditions)) responseReader.readBoolean(ResponseField.forBoolean("booleanField", "booleanField", null, true, noConditions)) responseReader.readObject(ResponseField.forObject("objectField", "objectField", null, true, noConditions)) { null!! } responseReader.readList(ResponseField.forList("scalarListField", "scalarListField", null, true, noConditions)) { null!! } } @Test fun mandatoryFieldsIOException() { val responseReader = responseReader(emptyMap()) try { responseReader.readString(ResponseField.forString("stringField", "stringField", null, false, noConditions)) fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readInt(ResponseField.forInt("intField", "intField", null, false, noConditions)) fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readLong(ResponseField.forLong("longField", "longField", null, false, noConditions)) fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readDouble(ResponseField.forDouble("doubleField", "doubleField", null, false, noConditions)) fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readBoolean(ResponseField.forBoolean("booleanField", "booleanField", null, false, noConditions)) fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readObject(ResponseField.forObject("objectField", "objectField", null, false, noConditions)) { null!! } fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } try { responseReader.readList(ResponseField.forList("scalarListField", "scalarListField", null, false, noConditions)) { null!! } fail("expected NullPointerException") } catch (expected: NullPointerException) { //expected } } @Test fun readScalarListWithNulls() { val scalarList = ResponseField.forList("list", "list", null, false, noConditions) val recordSet: MutableMap<String, Any> = HashMap() recordSet["list"] = listOf(null, "item2", "item3", null, "item5", null) val responseReader = responseReader(recordSet) assertEquals( expected = listOf(null, "item2", "item3", null, "item5", null), actual = responseReader.readList(scalarList) { reader: ResponseReader.ListItemReader -> reader.readString() }) } @Test fun readObjectListWithNulls() { val listField = ResponseField.forList("list", "list", null, false, noConditions) val indexField = ResponseField.forList("index", "index", null, false, noConditions) val responseObjects = listOf(null, Any(), Any(), null, Any(), null) val recordSet: MutableMap<String, Any> = HashMap() recordSet["list"] = listOf( null, mapOf("index" to "1"), mapOf("index" to "2"), null, mapOf("index" to "4"), null ) val responseReader = responseReader(recordSet) assertEquals( expected = responseObjects, actual = responseReader.readList(listField) { listReader -> listReader.readObject { reader -> responseObjects[reader.readString(indexField)!!.toInt()]!! } } ) } companion object { private fun responseReader(recordSet: Map<String, Any>): SimpleResponseReader { val customTypeAdapters: MutableMap<ScalarType, CustomTypeAdapter<*>> = HashMap() customTypeAdapters[OBJECT_CUSTOM_TYPE] = object : CustomTypeAdapter<Any?> { override fun decode(value: CustomTypeValue<*>): Any { return value.value.toString() } override fun encode(value: Any?): CustomTypeValue<*> { throw UnsupportedOperationException() } } return SimpleResponseReader(recordSet, EMPTY_OPERATION.variables(), ScalarTypeAdapters(customTypeAdapters)) } private fun scalarTypeFor(clazz: KClass<*>, className: String): ScalarType { return object : ScalarType { override fun typeName(): String { return clazz.simpleName!! } override fun className(): String { return className } } } private val OBJECT_CUSTOM_TYPE: ScalarType = object : ScalarType { override fun typeName(): String { return String::class.simpleName!! } override fun className(): String { return "kotlin.String" } } } }
22
null
531
2,897
f16ef0f4020af7a07c200f0fdcf1dac977d63637
24,336
apollo-android
MIT License
app/src/main/java/de/jensklingenberg/jetpackcomposeplayground/mysamples/github/material/switch/SwitchDemo.kt
Foso
187,719,625
false
null
package de.jensklingenberg.jetpackcomposeplayground.mysamples.github.material.switch import androidx.compose.material.MaterialTheme import androidx.compose.material.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @Composable fun SwitchDemo() { MaterialTheme { val checkedState = remember { mutableStateOf(true) } Switch( checked = checkedState.value, onCheckedChange = { checkedState.value = it } ) } }
13
null
287
3,404
53b5945345cbc4dcddfd965eb73085096cb8791a
555
Jetpack-Compose-Playground
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BriefcaseArrowRight.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.BriefcaseArrowRight: ImageVector get() { if (_briefcaseArrowRight != null) { return _briefcaseArrowRight!! } _briefcaseArrowRight = Builder(name = "BriefcaseArrowRight", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.5f, 3.0f) horizontalLineToRelative(-0.63f) curveToRelative(-0.45f, -1.72f, -2.01f, -3.0f, -3.87f, -3.0f) horizontalLineToRelative(-4.0f) curveToRelative(-1.86f, 0.0f, -3.43f, 1.28f, -3.87f, 3.0f) horizontalLineToRelative(-0.63f) curveTo(2.47f, 3.0f, 0.0f, 5.47f, 0.0f, 8.5f) verticalLineToRelative(10.0f) curveToRelative(0.0f, 3.03f, 2.47f, 5.5f, 5.5f, 5.5f) horizontalLineToRelative(13.0f) curveToRelative(3.03f, 0.0f, 5.5f, -2.47f, 5.5f, -5.5f) lineTo(24.0f, 8.5f) curveToRelative(0.0f, -3.03f, -2.47f, -5.5f, -5.5f, -5.5f) close() moveTo(21.0f, 18.5f) curveToRelative(0.0f, 1.38f, -1.12f, 2.5f, -2.5f, 2.5f) lineTo(5.5f, 21.0f) curveToRelative(-1.38f, 0.0f, -2.5f, -1.12f, -2.5f, -2.5f) lineTo(3.0f, 8.5f) curveToRelative(0.0f, -1.38f, 1.12f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(13.0f) curveToRelative(1.38f, 0.0f, 2.5f, 1.12f, 2.5f, 2.5f) verticalLineToRelative(10.0f) close() moveTo(17.87f, 12.79f) curveToRelative(0.39f, 0.39f, 0.39f, 1.02f, 0.0f, 1.41f) lineToRelative(-3.16f, 3.16f) curveToRelative(-0.63f, 0.63f, -1.71f, 0.18f, -1.71f, -0.71f) verticalLineToRelative(-1.66f) lineTo(7.5f, 14.99f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(5.5f) verticalLineToRelative(-1.66f) curveToRelative(0.0f, -0.89f, 1.08f, -1.34f, 1.71f, -0.71f) lineToRelative(3.16f, 3.16f) close() } } .build() return _briefcaseArrowRight!! } private var _briefcaseArrowRight: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,268
icons
MIT License
basic/src/main/java/com/xiaoxin/basic/widget/ViewClick.kt
XiaoXin956
474,917,723
false
null
package com.xiaoxin.basic.widget import android.view.View inline fun View.click(init: ViewClickListener.() -> Unit) { val viewClick = ViewClickListener() viewClick.init() setOnClickListener(viewClick) setOnLongClickListener(viewClick) } class ViewClickListener : View.OnClickListener, View.OnLongClickListener { private var click: ((View) -> Unit)? = null private var longClick: ((View) -> Unit)? = null fun onClick(method: ((View) -> Unit)? = null) { click = method } fun onLongClick(method: ((View) -> Unit)? = null) { longClick = method } override fun onClick(v: View?) { click?.invoke(v!!) } override fun onLongClick(v: View?): Boolean { longClick?.invoke(v!!) return true } }
0
Kotlin
0
4
bdbf05f52535978e947e3c1f0803e0f9dc4377d2
788
Toolkit
Apache License 2.0
app/src/main/java/com/ibrahimcanerdogan/turkishairlinesassistant/model/available/domestic/response/BookingClassAvail.kt
icanerdogan
727,407,042
false
{"Kotlin": 412038, "HTML": 7398}
package com.ibrahimcanerdogan.turkishairlinesassistant.model.available.domestic.response data class BookingClassAvail( val RPH: String, val ResBookDesigCode: String, val ResBookDesigQuantity: String, val ResBookDesigStatusCode: String )
0
Kotlin
0
1
6564a9cf8589028e9ced03a855a6b7eb07f7a5de
253
TurkishAirlinesAssistantApp
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/scene/entity/FishtankFishInfo.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 535420}
package data.scene.entity import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.Version import org.anime_game_servers.core.base.annotations.proto.ProtoModel @AddedIn(Version.GI_3_0_0) @ProtoModel interface FishtankFishInfo { var fishDistanceFromWater: Float var fishScale: Float var initialRotationY: Float }
0
Kotlin
3
6
9fc2c2ea7e3c2561ffaa66e7f58012ae1dcc4256
368
anime-game-multi-proto
MIT License
lib-whiteboard/src/main/kotlin/com/enigmastation/streampack/whiteboard/operation/ListOperationGrammar.kt
jottinger
850,104,415
false
{"Kotlin": 286785, "HTML": 32078, "Go": 2105, "Dockerfile": 923, "JavaScript": 676, "Svelte": 603, "Shell": 499, "TypeScript": 219, "Just": 148}
/* <NAME> (C)2024 */ package com.enigmastation.streampack.whiteboard.operation import com.enigmastation.streampack.rules.ExtendedGrammar import com.github.mpe85.grampa.createGrammar import com.github.mpe85.grampa.parser.Parser import com.github.mpe85.grampa.rule.Rule open class ListOperationGrammar : ExtendedGrammar<Unit>() { override fun start(): Rule<Unit> = sequence(char('~'), optionalWsp(), string("list"), wsp(), string("operations")) companion object { fun parser() = Parser(ListOperationGrammar::class.createGrammar()) } }
6
Kotlin
0
0
0ad05f65dd0f1db9ed3d125a876cf6e8e693a8c2
564
streampack
MIT License
generators/app/templates/presentation/src/main/java/com/kristal/generator/presentation/di/module/ServiceModule.kt
Cla1ty
108,220,263
false
null
package <%= appPackage %>.presentation.di.module import dagger.Module /** * Created by Dwi_Ari on 10/14/17. */ @Module abstract class ServiceModule { // @ContributesAndroidInjector(modules = arrayOf(EmptyModule::class)) // internal abstract fun bindAlphabetList(): AlphabetListFragment }
0
Kotlin
1
0
4133b44eb99c594155111fdb3be0b72730c0d6a2
299
Generator-Kristal
The Unlicense
compiler/fir/providers/src/org/jetbrains/kotlin/fir/resolve/calls/FirSyntheticNamesProvider.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.resolve.calls import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.FirSessionComponent import org.jetbrains.kotlin.name.Name abstract class FirSyntheticNamesProvider : FirSessionComponent { abstract fun possibleGetterNamesByPropertyName(name: Name): List<Name> abstract fun setterNameByGetterName(name: Name): Name abstract fun possiblePropertyNamesByAccessorName(name: Name): List<Name> } val FirSession.syntheticNamesProvider: FirSyntheticNamesProvider by FirSession.sessionComponentAccessor()
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
776
kotlin
Apache License 2.0
app/src/main/java/com/example/recipeapp/data/api/RecipeApi.kt
Someboty
747,740,247
false
{"Kotlin": 109244}
package com.example.recipeapp.data.api import com.example.recipeapp.data.models.network.NetworkRecipeDetailed import com.example.recipeapp.data.models.network.NetworkRecipeContainer import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query /** * Interface defining the API endpoints for retrieving recipe data. */ interface RecipeApi { /** * Retrieves a list of recipe previews. * * @param key The API key for authentication. * @param recipeAmount The number of recipes to retrieve. * @param offset The offset for paginated results. * @return A container of network recipe previews. */ @GET("complexSearch") suspend fun getRecipesPreviews( @Query("apiKey") key : String, @Query("number") recipeAmount: Int, @Query("offset") offset: Int ) : NetworkRecipeContainer /** * Retrieves a list of recipe previews based on a query. * * @param key The API key for authentication. * @param name The query string for recipe names. * @param recipeAmount The number of recipes to retrieve. * @return A container of network recipe previews. */ @GET("complexSearch") suspend fun getRecipesPreviewsByQuery( @Query("apiKey") key : String, @Query("query") name: String, @Query("number") recipeAmount: Int ): NetworkRecipeContainer /** * Retrieves detailed information for a specific recipe. * * @param recipeId The ID of the recipe to retrieve information for. * @param apiKey The API key for authentication. * @return Detailed information about the specified recipe. */ @GET("{recipeId}/information") suspend fun getRecipeInformation( @Path("recipeId") recipeId: Long, @Query("apiKey") apiKey: String ): NetworkRecipeDetailed }
0
Kotlin
0
0
15d50588b5ecde3440cc101cb69bfbf4e7c9b541
1,848
Recipe_App
MIT License
student/src/main/java/com/solutionteam/mindfulmentor/data/source/local/Converters.kt
DevSkillSeekers
746,597,864
false
{"Kotlin": 412451}
package com.solutionteam.mindfulmentor.data.local import androidx.room.ProvidedTypeConverter import androidx.room.TypeConverter import com.google.gson.Gson import java.util.Date @ProvidedTypeConverter class Converters(val gson: Gson) { @TypeConverter fun dateToLong(date: Date): Long = date.time @TypeConverter fun longToDate(long: Long): Date = Date(long) }
1
Kotlin
0
1
931d510724b2ae15fd6277988241bd229b7513ea
378
GradesFromGeeks
Apache License 2.0
src/main/kotlin/com/mcdev/twitterapikit/model/Topic.kt
kojofosu
421,822,016
false
null
package com.mcdev.twitterapikit.model import com.google.gson.annotations.SerializedName data class Topic( @SerializedName(value = "description") var description: String?, @SerializedName(value = "id") var id: String?, @SerializedName(value = "name") var name: String? )
0
Kotlin
2
34
d358785609c5d787de8092d0643c47dd33cf0485
298
TwitterApiKit
Apache License 2.0
samples/state-as-cells/features/base/ui/src/main/java/com/originsdigital/compositeadapter/ui/utils/FlowUtils.kt
netcosports
382,011,704
false
null
package com.originsdigital.compositeadapter.ui.utils import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch fun <T : Any> observeFlow( flow: Flow<T>, lifecycleOwner: LifecycleOwner, lifecycleState: Lifecycle.State = Lifecycle.State.RESUMED, delegate: suspend (T) -> Unit ) { lifecycleOwner.lifecycleScope.launch { lifecycleOwner.lifecycle.repeatOnLifecycle(lifecycleState) { flow.collect { item -> delegate(item) } } } }
1
Kotlin
0
11
c91c094f42f745b584d97d836beeffec3c30c05c
651
CompositeAdapter_Android
Apache License 2.0
bot/engine/src/main/kotlin/definition/StoryDataStep.kt
theopenconversationkit
84,538,053
false
null
/* * Copyright (C) 2017/2020 e-voyageurs technologies * * 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 ai.tock.bot.definition import ai.tock.bot.engine.BotBus /** * A step that can have specific preconditions and can use input data object in handler. * * @param T StoryDef * @param TD the data of the StoryDef * @param D the data of the step */ interface StoryDataStep<T : StoryHandlerDefinition, TD, D> : StoryStep<T> { override fun answer(): T.() -> Any? = { handler().invoke(this, null) } /** * Does this Step has to be selected from the Bus? * This method is called if [StoryHandlerBase.checkPreconditions] does not call [BotBus.end]. * If this functions returns true, the step is selected and remaining steps are not tested. */ fun selectFromBusAndData(): T.(TD?) -> Boolean = { false } /** * Checks preconditions - if [BotBus.end] is called, * [StoryHandlerDefinition.handle] is not called and the handling of bot answer is over. * Returned data is used in subsequent call of [handler] if not null * - else [StoryHandlerBase.checkPreconditions] returned data is used. */ fun checkPreconditions(): T.(TD?) -> D? = { null } /** * The custom handler for this step. * When returning a null value, * it means that the step is not able to answer to the current request. * * Default implementation returns null. */ fun handler(): T.(D?) -> Any? = { null } }
163
null
127
475
890f69960997ae9146747d082d808d92ee407fcb
1,990
tock
Apache License 2.0
repository/src/main/java/ca/bc/gov/repository/di/QrScannerModule.kt
bcgov
414,797,174
false
{"Kotlin": 1356975, "Java": 582146}
package ca.bc.gov.repository.di import ca.bc.gov.repository.scanner.QrScanner import com.google.mlkit.vision.barcode.BarcodeScanner import com.google.mlkit.vision.barcode.BarcodeScanning import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton /** * @author <NAME> */ @Module @InstallIn(SingletonComponent::class) class QrScannerModule { @Provides fun provideBarcodeScanner() = BarcodeScanning.getClient() @Provides @Singleton fun providesQrScanner(scanner: BarcodeScanner) = QrScanner(scanner) }
4
Kotlin
5
5
65815bb851e93dc1aa3397763d187ac829923fca
618
myhealthBC-android
Apache License 2.0
src/main/kotlin/homework1/ArrayDequeUtil.kt
faf0be172
340,895,478
false
null
package homework1 import kotlin.math.min import kotlin.math.max /** * The method [moveElement] moves element from one place to another */ fun ArrayDeque<Int>.moveElement(indexFrom: Int, indexTo: Int) { if (this.size <= max(indexFrom, indexTo) || min(indexFrom, indexTo) < 0) { throw ArrayIndexOutOfBoundsException("Some of indexes are out of bounds") } if (indexFrom != indexTo) { val movingElement = this[indexFrom] this.removeAt(indexFrom) this.add(indexTo, movingElement) } }
1
Kotlin
0
0
c53fb9c6b3398917c53efdbafd50f7e93cdfcdc7
532
Kotlin_homeworks
Apache License 2.0
data/src/main/java/divyansh/tech/animeclassroom/database/CacheDatabase.kt
yash-k9
413,458,244
true
{"HTML": 405869, "Kotlin": 194173}
package divyansh.tech.animeclassroom.database import androidx.room.Database import androidx.room.RoomDatabase import divyansh.tech.animeclassroom.mangaModels.OfflineMangaModel import divyansh.tech.animeclassroom.models.home.OfflineAnimeModel @Database(entities = [OfflineAnimeModel::class, OfflineMangaModel::class], version = 2) abstract class CacheDatabase :RoomDatabase(){ abstract fun cacheDao():CacheDao }
0
HTML
0
0
4b4fa3a89d6b83c132177e2ef0909e67fb614ad1
416
AnimeClassroom
The Unlicense
app/src/main/java/com/mytests/testExam/data/repository/AnimalFactsRepository.kt
FredNekrasov
766,574,196
false
{"Kotlin": 46693}
package com.mytests.testExam.data.repository import com.mytests.testExam.data.local.dao.IAnimalFactsDao import com.mytests.testExam.data.mappers.toDomain import com.mytests.testExam.data.mappers.toEntity import com.mytests.testExam.data.remote.dto.AnimalFactsDTO import com.mytests.testExam.domain.model.AnimalFacts import com.mytests.testExam.domain.repository.IAnimalFactsRepository import com.mytests.testExam.domain.util.ConnectionStatus import com.mytests.testExam.domain.util.ConnectionStatus.* import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.* import io.ktor.client.request.get import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class AnimalFactsRepository( private val dao: IAnimalFactsDao, private val client : HttpClient ) : IAnimalFactsRepository { override suspend fun updateEntity(animalFacts : AnimalFacts) = dao.insert(animalFacts.toEntity()) override fun getList( animalType : String, amount : Int ): Flow<Pair<ConnectionStatus, List<AnimalFacts>>> = flow { val listOfFacts = dao.getAll().map { it.toDomain() } emit(LOADING to listOfFacts) if(animalType.isEmpty() || animalType.isBlank() || amount <= 1) { emit(SUCCESS to listOfFacts) } else { try { val result = client.get("/facts/random?animal_type=$animalType&amount=$amount").body<List<AnimalFactsDTO>?>() if(result.isNullOrEmpty()) { emit(NO_DATA to listOfFacts) } else { result.forEach { dao.delete(it.toEntity()) dao.insert(it.toEntity()) } emit(SUCCESS to dao.getAll().map { it.toDomain() }) } } catch (e: RedirectResponseException) { emit(ERROR to listOfFacts) } catch (e: ClientRequestException) { emit(ERROR to listOfFacts) } catch (e: ServerResponseException) { emit(ERROR to listOfFacts) } } } }
0
Kotlin
0
1
e344e47e6cb1ba8f0634e3df75ffa3514270bc59
2,128
my-tests
MIT License
transformations/src/main/java/com/tsubasa/glide/transformations/BitmapTransformation.kt
Panjianan
108,394,197
false
null
package com.tsubasa.glide.transformations import android.content.Context import android.graphics.Bitmap import com.bumptech.glide.Glide import com.bumptech.glide.load.Transformation import com.bumptech.glide.load.engine.Resource import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool import com.bumptech.glide.load.resource.bitmap.BitmapResource import com.bumptech.glide.request.target.Target import com.bumptech.glide.util.Util import java.security.MessageDigest /*** * <br> Project GlideTransformations * <br> Package com.tsubasa.glide.transformations * <br> Description 相关转化的父类 * <br> Version 1.0 * <br> Author Tsubasa */ abstract class BitmapTransformation : Transformation<Bitmap> { protected abstract fun getId(): String protected abstract fun transform(context: Context, pool: BitmapPool, source: Bitmap, outWidth: Int, outHeight: Int): Bitmap override fun transform(context: Context, resource: Resource<Bitmap>, outWidth: Int, outHeight: Int): Resource<Bitmap> { if (!Util.isValidDimensions(outWidth, outHeight)) { throw IllegalArgumentException( "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight + " less than or equal to zero and not Target.SIZE_ORIGINAL") } val bitmapPool = Glide.get(context).bitmapPool val toTransform = resource.get() val targetWidth = outWidth val targetHeight = outHeight val transformed = transform(context.applicationContext, bitmapPool, toTransform, targetWidth, targetHeight) val result: Resource<Bitmap> if (toTransform == transformed) { result = resource } else { result = BitmapResource.obtain(transformed, bitmapPool)!! } return result } override fun updateDiskCacheKey(messageDigest: MessageDigest?) { messageDigest?.update(getId().toByteArray()) } }
1
Kotlin
1
6
9acd907f59b09402afbc61b7d08176ccec38e343
1,960
GlideTransformations
Apache License 2.0
evervault-inputs/src/main/java/com/evervault/sdk/input/ui/InlinePaymentCardInput.kt
evervault
650,073,299
false
{"Kotlin": 81167}
package com.evervault.sdk.input.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun PaymentCardInputScope.inline( modifier: Modifier = Modifier, padding: PaddingValues = PaddingValues(16.dp) ) { Row( modifier = modifier .background(MaterialTheme.colorScheme.primaryContainer) .padding(padding) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { CardImage(modifier = Modifier.width(30.dp)) CardNumberField(modifier = Modifier.weight(0.66f, true), options = PaymentCardInputScope.TextFieldOptions(), placeholder = "Card Number") ExpiryField(modifier = Modifier.weight(0.20f, true), options = PaymentCardInputScope.TextFieldOptions(), placeholder = "EXP") CVCField(modifier = Modifier.weight(0.14f, true), options = PaymentCardInputScope.TextFieldOptions(), placeholder = "CV2") } } @Composable fun inlinePaymentCardInputLayout(): @Composable() (PaymentCardInputScope.(Modifier) -> Unit) = { inline(modifier = it) }
1
Kotlin
1
4
415907fa65ff3a456ccbebb41a550ee2f226c102
1,618
evervault-android
MIT License
exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcConnectionImpl.kt
JetBrains
11,765,017
false
null
package org.jetbrains.exposed.sql.statements.jdbc import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.statements.Statement import org.jetbrains.exposed.sql.statements.StatementType import org.jetbrains.exposed.sql.statements.api.ExposedConnection import org.jetbrains.exposed.sql.statements.api.ExposedDatabaseMetadata import org.jetbrains.exposed.sql.statements.api.ExposedSavepoint import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.transactions.TransactionManager import java.sql.Connection import java.sql.PreparedStatement class JdbcConnectionImpl(override val connection: Connection) : ExposedConnection<Connection> { // Oracle driver could throw excpection on catalog override val catalog: String by lazy { try { connection.catalog } catch (_: Exception) { null } ?: connection.metaData.userName ?: "" } override fun commit() { connection.commit() } override fun rollback() { connection.rollback() } override val isClosed get() = connection.isClosed override fun close() { connection.close() } override var autoCommit: Boolean get() = connection.autoCommit set(value) { connection.autoCommit = value } override var transactionIsolation: Int get() = connection.transactionIsolation set(value) { connection.transactionIsolation = value } private val metadata by lazy { JdbcDatabaseMetadataImpl(catalog, connection.metaData) } override fun <T> metadata(body: ExposedDatabaseMetadata.() -> T): T = metadata.body() override fun prepareStatement(sql: String, returnKeys: Boolean) : PreparedStatementApi { val generated = if (returnKeys) PreparedStatement.RETURN_GENERATED_KEYS else PreparedStatement.NO_GENERATED_KEYS return JdbcPreparedStatementImpl(connection.prepareStatement(sql, generated), returnKeys) } override fun prepareStatement(sql: String, columns: Array<String>): PreparedStatementApi { return JdbcPreparedStatementImpl(connection.prepareStatement(sql, columns), true) } override fun executeInBatch(sqls: List<String>) { val types = sqls.map { stmt -> StatementType.values().find { stmt.startsWith(it.name, true) } ?: StatementType.OTHER } check(types.none { it == StatementType.SELECT }) { "SELECT statements are unsupported in batch execution" } val type = types.distinct().singleOrNull() ?: StatementType.OTHER val prepStatement = object : Statement<Unit>(type, emptyList()) { override fun prepared(transaction: Transaction, sql: String): PreparedStatementApi { val originalStatement = super.prepared(transaction, sql.substringBefore('\n')) val batchStatement = connection.createStatement().apply { sqls.forEach { addBatch(it) } } return object : PreparedStatementApi by originalStatement { override fun closeIfPossible() { batchStatement.close() originalStatement.closeIfPossible() } override fun executeUpdate(): Int { batchStatement.executeBatch() return 0 } } } override fun PreparedStatementApi.executeInternal(transaction: Transaction) { executeUpdate() } override fun prepareSQL(transaction: Transaction): String = sqls.joinToString("\n") override fun arguments(): Iterable<Iterable<Pair<ColumnType, Any?>>> = emptyList() } prepStatement.execute(TransactionManager.current()) } override fun setSavepoint(name: String): ExposedSavepoint { return JdbcSavepoint(name, connection.setSavepoint(name)) } override fun releaseSavepoint(savepoint: ExposedSavepoint) { connection.releaseSavepoint((savepoint as JdbcSavepoint).savepoint) } override fun rollback(savepoint: ExposedSavepoint) { connection.rollback((savepoint as JdbcSavepoint).savepoint) } }
351
null
648
7,851
f396d8ae6cf8923f574d2a6a1f098c88452957b6
4,399
Exposed
Apache License 2.0
backend/data/src/main/kotlin/io/tolgee/formats/csv/in/CsvFileParser.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.formats.csv.`in` import com.opencsv.CSVParserBuilder import com.opencsv.CSVReaderBuilder import io.tolgee.formats.csv.CsvEntry import java.io.InputStream class CsvFileParser( private val inputStream: InputStream, private val delimiter: Char, private val languageFallback: String, ) { val rawData: List<Array<String>> by lazy { val inputReader = inputStream.reader() val parser = CSVParserBuilder().withSeparator(delimiter).build() val reader = CSVReaderBuilder(inputReader).withCSVParser(parser).build() return@lazy reader.readAll() } val headers: Array<String>? by lazy { rawData.firstOrNull() } val languages: List<String> by lazy { headers?.takeIf { it.size > 1 }?.drop(1) ?: emptyList() } val languagesWithFallback: Sequence<String> get() = languages.asSequence().plus(generateSequence { languageFallback }) val rows: List<Array<String>> by lazy { rawData.takeIf { it.size > 1 }?.drop(1) ?: emptyList() } fun Array<String>.rowToCsvEntries(): Sequence<CsvEntry> { if (isEmpty()) { return emptySequence() } val keyName = getOrNull(0) ?: "" if (size == 1) { return sequenceOf(CsvEntry(keyName, languageFallback, null)) } val translations = drop(1).asSequence() return translations .zip(languagesWithFallback) .map { (translation, languageTag) -> CsvEntry( keyName, languageTag, translation, ) } } fun parse(): List<CsvEntry> { return rows.flatMap { it.rowToCsvEntries() } } }
170
TypeScript
188
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
1,586
tolgee-platform
Apache License 2.0
sdk/src/main/java/io/portone/sdk/android/issuebillingkeyandpay/IssueBillingKeyAndPayJavascriptInterface.kt
portone-io
835,174,061
false
{"Kotlin": 197769, "HTML": 1179}
package io.portone.sdk.android.issuebillingkeyandpay interface IssueBillingKeyAndPayJavascriptInterface { fun fail( transactionType: String?, txId: String?, paymentId: String?, billingKey: String?, code: String, message: String ) }
0
Kotlin
0
2
07509908b066a19fc5e0e96afca415816687d2f4
288
android-sdk
MIT License
integrasjonstest/src/test/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/integrasjonstest/TrengerIT.kt
navikt
495,713,363
false
null
package no.nav.helsearbeidsgiver.inntektsmelding.integrasjonstest import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import no.nav.helsearbeidsgiver.felles.BehovType import no.nav.helsearbeidsgiver.felles.DataFelt import no.nav.helsearbeidsgiver.felles.EventName import no.nav.helsearbeidsgiver.felles.Key import no.nav.helsearbeidsgiver.felles.TrengerData import no.nav.helsearbeidsgiver.felles.TrengerInntekt import no.nav.helsearbeidsgiver.felles.json.toJson import no.nav.helsearbeidsgiver.felles.rapidsrivers.redis.RedisKey import no.nav.helsearbeidsgiver.felles.test.json.fromJsonMapOnlyKeys import no.nav.helsearbeidsgiver.felles.test.mock.mockTrengerInntekt import no.nav.helsearbeidsgiver.inntektsmelding.integrasjonstest.utils.EndToEndTest import no.nav.helsearbeidsgiver.utils.json.fromJson import no.nav.helsearbeidsgiver.utils.json.serializer.UuidSerializer import no.nav.helsearbeidsgiver.utils.json.toJson import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.util.UUID @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TrengerIT : EndToEndTest() { @Test fun `Test trengerIM meldingsflyt`() { var transactionId: UUID publish( Key.EVENT_NAME to EventName.TRENGER_REQUESTED.toJson(), Key.CLIENT_ID to Mock.clientId.toJson(UuidSerializer), DataFelt.FORESPOERSEL_ID to Mock.forespoerselId.toJson(UuidSerializer) ) waitForMessages(10000) messages.filter(EventName.TRENGER_REQUESTED) .filter(BehovType.HENT_TRENGER_IM) .first() .fromJsonMapOnlyKeys() .let { // Ble lagret i databasen transactionId = it[Key.UUID].shouldNotBeNull().fromJson(UuidSerializer) } publish( Key.EVENT_NAME to EventName.TRENGER_REQUESTED.toJson(), Key.DATA to "".toJson(), Key.UUID to transactionId.toJson(), DataFelt.FORESPOERSEL_SVAR to mockTrengerInntekt().toJson(TrengerInntekt.serializer()) ) waitForMessages(12000) messages.filter(EventName.TRENGER_REQUESTED) .filter(BehovType.HENT_TRENGER_IM) .first() .fromJsonMapOnlyKeys() .let { // Ble lagret i databasen it[Key.UUID]?.fromJson(UuidSerializer) shouldBe transactionId } messages.filter(EventName.TRENGER_REQUESTED) .filter(BehovType.VIRKSOMHET) .first() .fromJsonMapOnlyKeys() .let { // Ble lagret i databasen it[Key.UUID]?.fromJson(UuidSerializer) shouldBe transactionId } messages.filter(EventName.TRENGER_REQUESTED) .filter(BehovType.FULLT_NAVN) .first() .fromJsonMapOnlyKeys() .let { // Ble lagret i databasen it[Key.UUID]?.fromJson(UuidSerializer) shouldBe transactionId } messages.filter(EventName.TRENGER_REQUESTED) .filter(BehovType.INNTEKT) .first() .fromJsonMapOnlyKeys() .let { // Ble lagret i databasen it[Key.UUID]?.fromJson(UuidSerializer) shouldBe transactionId } val trengerResultatJson = redisStore.get(RedisKey.of(Mock.clientId.toString())) println("In test $trengerResultatJson") val objekt = trengerResultatJson?.fromJson(TrengerData.serializer()) println(objekt) } private object Mock { val clientId: UUID = UUID.randomUUID() val forespoerselId: UUID = UUID.randomUUID() } }
16
Kotlin
0
2
f722ac506d9fb2459a4ff05fd807dc4909329b51
3,732
helsearbeidsgiver-inntektsmelding
MIT License
order-service/data-access/src/main/kotlin/com/food/ordering/system/order/service/dataaccess/order/entity/OrderItemEntity.kt
ani2fun
558,480,625
false
{"Kotlin": 161253, "PLpgSQL": 4264, "Shell": 113}
package com.food.ordering.system.order.service.dataaccess.order.entity import jakarta.persistence.CascadeType import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.Id import jakarta.persistence.IdClass import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.Table import java.math.BigDecimal import java.util.UUID @Entity @Table(name = "order_items") @IdClass(OrderItemEntityId::class) class OrderItemEntity( @Id @Column(name = "id") val id: Long? = null, @Id @ManyToOne(cascade = [CascadeType.ALL]) @JoinColumn(name = "order_id") var order: OrderEntity? = null, @Column(name = "product_id") val productId: UUID? = null, @Column(name = "price") val price: BigDecimal? = null, @Column(name = "quantity") val quantity: Int? = null, @Column(name = "sub_total") val subTotal: BigDecimal? = null, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OrderItemEntity) return false if (id != other.id) return false return true } override fun hashCode(): Int { return id?.hashCode() ?: 0 } }
0
Kotlin
0
0
66422bb8028aa8aae767de9fc2fdcdc31e2613d7
1,225
food-ordering-system
Apache License 2.0
app/src/test/kotlin/no/nav/tiltakspenger/vedtak/db/TestDataHelper.kt
navikt
487,246,438
false
{"Kotlin": 990435, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.vedtak.db import mu.KotlinLogging import no.nav.tiltakspenger.common.SaksnummerGenerator import no.nav.tiltakspenger.libs.persistering.infrastruktur.PostgresSessionFactory import no.nav.tiltakspenger.libs.persistering.infrastruktur.SessionCounter import no.nav.tiltakspenger.utbetaling.ports.UtbetalingsvedtakRepo import no.nav.tiltakspenger.vedtak.repository.behandling.BehandlingPostgresRepo import no.nav.tiltakspenger.vedtak.repository.benk.SaksoversiktPostgresRepo import no.nav.tiltakspenger.vedtak.repository.meldekort.MeldekortPostgresRepo import no.nav.tiltakspenger.vedtak.repository.sak.SakPostgresRepo import no.nav.tiltakspenger.vedtak.repository.statistikk.sak.StatistikkSakRepoImpl import no.nav.tiltakspenger.vedtak.repository.statistikk.stønad.StatistikkStønadPostgresRepo import no.nav.tiltakspenger.vedtak.repository.søknad.PostgresSøknadRepo import no.nav.tiltakspenger.vedtak.repository.utbetaling.UtbetalingsvedtakPostgresRepo import no.nav.tiltakspenger.vedtak.repository.vedtak.RammevedtakPostgresRepo import javax.sql.DataSource internal class TestDataHelper( private val dataSource: DataSource, val saksnummerGenerator: SaksnummerGenerator, ) { private val log = KotlinLogging.logger {} private val sessionCounter = SessionCounter(log) private val sessionFactory = PostgresSessionFactory(dataSource, sessionCounter) val søknadRepo = PostgresSøknadRepo(sessionFactory) val behandlingRepo = BehandlingPostgresRepo(sessionFactory) val vedtakRepo = RammevedtakPostgresRepo(sessionFactory) val sakRepo = SakPostgresRepo(sessionFactory) val saksoversiktRepo = SaksoversiktPostgresRepo(sessionFactory) val statistikkSakRepo = StatistikkSakRepoImpl(sessionFactory) val statistikkStønadRepo = StatistikkStønadPostgresRepo(sessionFactory) val meldekortRepo = MeldekortPostgresRepo(sessionFactory) val utbetalingsvedtakRepo: UtbetalingsvedtakRepo = UtbetalingsvedtakPostgresRepo(sessionFactory) } private val dbManager = TestDatabaseManager() /** * @param runIsolated Tømmer databasen før denne testen for kjøre i isolasjon. Brukes når man gjør operasjoner på tvers av saker. */ internal fun withMigratedDb(runIsolated: Boolean = false, test: (TestDataHelper) -> Unit) { dbManager.withMigratedDb(runIsolated, test) }
8
Kotlin
0
1
d96f55831e67b1afbe7f2221d299ccc744250c3a
2,327
tiltakspenger-vedtak
MIT License
src/test/kotlin/br/com/zupacademy/mario/pix/cadastra/CadastraChavePixTest.kt
Mutrano
387,557,514
true
{"Kotlin": 40068}
package br.com.zupacademy.mario.pix.cadastra import br.com.zupacademy.mario.CadastraKeyRequest import br.com.zupacademy.mario.PixKeyManagerCadastraGrpcServiceGrpc import br.com.zupacademy.mario.TipoDeChave import br.com.zupacademy.mario.TipoDeConta import br.com.zupacademy.mario.integration.ContaDoClienteNoItauClient import br.com.zupacademy.mario.integration.DadosContaClienteResponse import br.com.zupacademy.mario.integration.InstituicaoResponse import br.com.zupacademy.mario.integration.TitularResponse import br.com.zupacademy.mario.pix.ChavePixRepository import br.com.zupacademy.mario.pix.paraNovaChave import io.grpc.ManagedChannel import io.grpc.Status import io.grpc.StatusRuntimeException import io.micronaut.context.annotation.Factory import io.micronaut.grpc.annotation.GrpcChannel import io.micronaut.http.HttpResponse import io.micronaut.test.annotation.MockBean import io.micronaut.test.extensions.junit5.annotation.MicronautTest import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.Mockito import javax.inject.Singleton @MicronautTest(transactional = false) class CadastraChavePixTest( val repository: ChavePixRepository, val grpcClient: PixKeyManagerCadastraGrpcServiceGrpc.PixKeyManagerCadastraGrpcServiceBlockingStub, val itauClient: ContaDoClienteNoItauClient ) { /** * 1 - happy path do cadastro de chave * 2 - erro de validação do tipo de chave * 3 - erros de validação em geral * 4 - usuário não encontrado no ERP Itaú * **/ @BeforeEach fun setup() { repository.deleteAll() } @Test fun `Deve criar uma chave pix de uma chave valido`() { //ação val request = CadastraKeyRequest.newBuilder() .setChave("26481207002") .setClienteId("c56dfef4-7901-44fb-84e2-a2cefb157890") .setTipoDeChave(TipoDeChave.CPF) .setTipoDeConta(TipoDeConta.CONTA_CORRENTE) .build() //mock erp itau Mockito.`when`(itauClient.buscaContaPorTipo(request.clienteId, request.tipoDeConta.name)).thenReturn( HttpResponse.ok(dadosDoCliente()) ) val response = grpcClient.cadastra(request) //verificação assertEquals(request.clienteId, response.clienteId) assertNotNull(response.pixId) assertTrue(response.pixId.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\$".toRegex())) } @Test fun `Não deve cadastrar chave inválida`() { //ação val request = CadastraKeyRequest.newBuilder() .setChave("26481207005") // cpf inválido .setClienteId("c56dfef4-7901-44fb-84e2-a2cefb157890") .setTipoDeChave(TipoDeChave.CPF) .setTipoDeConta(TipoDeConta.CONTA_CORRENTE) .build() val thrown = assertThrows<StatusRuntimeException> { grpcClient.cadastra(request) } //verificação with(thrown) { assertEquals(Status.INVALID_ARGUMENT.code, status.code) } } @Test fun `Não deve cadastrar com campos em branco`() { val request = CadastraKeyRequest.newBuilder().build() val thrown = assertThrows<StatusRuntimeException> { grpcClient.cadastra(request) } //verificação with(thrown) { assertEquals(Status.INVALID_ARGUMENT.code, status.code) } } @Test fun `Não deve cadastrar chave ja existente`() { // cenário val request = requestValida() val novaChave = request.paraNovaChave() val contaAssociada = dadosDoCliente().paraConta() val chaveSalva = novaChave.paraChave(contaAssociada) repository.save(chaveSalva) // ação val thrown = assertThrows<StatusRuntimeException> { grpcClient.cadastra(request) } //verificação with(thrown) { assertEquals(Status.ALREADY_EXISTS.code, status.code) } } @Test fun `Não deve cadastrar se não encontrar o cliente no ERP do Itaú`() { //cenário val request = requestValida() Mockito.`when`( itauClient.buscaContaPorTipo( clienteId = request.clienteId, tipo = request.tipoDeConta.name ) ).thenReturn(HttpResponse.notFound()) val thrown = assertThrows<StatusRuntimeException> { grpcClient.cadastra(request) } with(thrown) { assertEquals(Status.NOT_FOUND.code, status.code) } } @Factory class Clients { @Singleton fun blockingStub(@GrpcChannel("grpc-server") channel: ManagedChannel): PixKeyManagerCadastraGrpcServiceGrpc.PixKeyManagerCadastraGrpcServiceBlockingStub? { return PixKeyManagerCadastraGrpcServiceGrpc.newBlockingStub(channel) } } @MockBean(ContaDoClienteNoItauClient::class) fun ContaDoClienteNoItauClient(): ContaDoClienteNoItauClient { return Mockito.mock(ContaDoClienteNoItauClient::class.java) } } fun dadosDoCliente(): DadosContaClienteResponse { return DadosContaClienteResponse( tipo = "CONTA_CORRENTE", instituicao = InstituicaoResponse(nome = "ITAÚ UNIBANCO S.A.", ispb = "60701190"), agencia = "0001", numero = "291900", titular = TitularResponse( id = "c56dfef4-7901-44fb-84e2-a2cefb157890", nome = "<NAME>", cpf = "02467781054" ) ) } fun requestValida(): CadastraKeyRequest { return CadastraKeyRequest.newBuilder() .setChave("26481207002") .setClienteId("c56dfef4-7901-44fb-84e2-a2cefb157890") .setTipoDeChave(TipoDeChave.CPF) .setTipoDeConta(TipoDeConta.CONTA_CORRENTE) .build() }
0
Kotlin
0
0
63082c77003de9b4b165fc514d700374258d8bca
5,912
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/qm/cleanmodule/ui/fragment/bottomsheet/BottomSheetViewModel.kt
Qenawi
407,044,351
false
null
package com.qm.cleanmodule.ui.fragment.bottomsheet import androidx.databinding.ObservableBoolean import androidx.databinding.adapters.TextViewBindingAdapter import com.google.android.material.bottomsheet.BottomSheetBehavior import com.qm.cleanmodule.base.viewmodel.BaseViewModel import com.qm.cleanmodule.constants.Codes import com.qm.cleanmodule.data.model.SearchItemInterface import timber.log.Timber // BottomSheetViewModel @Docs class BottomSheetViewModel : BaseViewModel() { val adapter = SearchAdapter(::onItemClick) val obsShowHeader = ObservableBoolean() private fun onItemClick(searchItem: SearchItemInterface) { } fun onCloseClick() { setValue(Codes.BACK_BUTTON_PRESSED) } fun handleStates(newState: Int) { when (newState) { BottomSheetBehavior.STATE_EXPANDED -> { obsShowHeader.set(true) } BottomSheetBehavior.STATE_COLLAPSED -> { } BottomSheetBehavior.STATE_HALF_EXPANDED -> { obsShowHeader.set(false) } BottomSheetBehavior.STATE_HIDDEN -> { setValue(Codes.BACK_BUTTON_PRESSED) } } } fun onTextChange(): TextViewBindingAdapter.OnTextChanged { return TextViewBindingAdapter.OnTextChanged { s, _, _, _ -> adapter.filter.filter(s) } } fun gotData(args: BottomSheetFragmentArgs) { args.data?.let { adapter.setList(it.toList()) } ?: Timber.e("list is null") } }
0
Kotlin
0
0
77ab5bba0e4c5a09da778a187dabe34aa062b451
1,414
clean_poc
MIT License
code/1758. Clean Architecture on Android 12-Clean-Architecture-on-Android/12-Clean-Architecture-on-Android/Demo2/final/mobile-ui/src/main/java/com/raywenderlich/android/creatures/ui/injection/module/BrowseActivityModule.kt
iOSDevLog
186,328,282
false
null
package com.raywenderlich.android.creatures.ui.injection.module import com.raywenderlich.android.creatures.domain.interactor.browse.GetCreatures import com.raywenderlich.android.creatures.presentation.browse.BrowseCreaturesViewModelFactory import com.raywenderlich.android.creatures.presentation.mapper.CreatureMapper import dagger.Module import dagger.Provides /** * Module used to provide dependencies at an activity-level. */ @Module open class BrowseActivityModule { @Provides fun provideBrowseCreaturesViewModelFactory(getCreatures: GetCreatures, creatureMapper: CreatureMapper): BrowseCreaturesViewModelFactory { return BrowseCreaturesViewModelFactory(getCreatures, creatureMapper) } }
0
null
1
4
8b81fbeb046abfeda95f9870c3c29b4998dbb12d
759
raywenderlich
MIT License
app/src/main/java/com/pi3/teethkids/fragments/auth/RegisterFragment.kt
Johnviitoor
662,683,322
false
null
package com.pi3.teethkids.fragments.auth import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.findNavController import com.pi3.teethkids.R import com.pi3.teethkids.databinding.FragmentRegisterBinding import com.pi3.teethkids.utils.FirebaseUtils class RegisterFragment : Fragment() { private lateinit var binding: FragmentRegisterBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) addEventListeners() } private fun addEventListeners() { with (binding) { buttonLogin.setOnClickListener { view?.findNavController()?.navigate(R.id.action_registerFragment_to_loginFragment) } buttonRegister.setOnClickListener { registerUser() } } } private fun validateInputFields(): Boolean { // Validation Rules val emailValidation: Boolean = binding.inputEmail.text.toString().trim().isNotEmpty() val passwordValidation: Boolean = binding.inputPassword.text.toString().isNotEmpty() val confirmPasswordValidation: Boolean = binding.inputConfirmPassword.text.toString().isNotEmpty() val passwordSameValidation: Boolean = binding.inputPassword.text.toString() == binding.inputConfirmPassword.text.toString() // Validation Message val blankMessage = "Esse campo não pode ser vazio" val passwordSameMessage = "As senhas devem ser iguais" if (!emailValidation) { binding.inputEmail.error = blankMessage } if (!passwordValidation) { binding.inputPassword.error = blankMessage } if (!confirmPasswordValidation) { binding.inputConfirmPassword.error = blankMessage } if (!passwordSameValidation) { binding.inputPassword.error = passwordSameMessage binding.inputConfirmPassword.error = passwordSameMessage } if (!emailValidation || !passwordValidation || !confirmPasswordValidation || !passwordSameValidation) { Toast.makeText(activity, "Tente novamente!", Toast.LENGTH_SHORT).show() return false } return true } private fun registerUser() { if (validateInputFields()) { // Get input val email: String = binding.inputEmail.text.toString().trim() val password: String = binding.inputPassword.text.toString() // Perform registration FirebaseUtils().auth .createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { // Navigate to CompleteRegistration view?.findNavController()?.navigate(R.id.action_registerFragment_to_completeRegistrationFragment) } else { // Error handling Toast.makeText(activity, task.exception!!.message.toString(), Toast.LENGTH_SHORT).show() } } } } }
0
Kotlin
0
0
084ee49d0b997f6c9a656aea6bf4ff09ed7d48ff
3,548
TeethKids_Kotlin
Apache License 2.0
app/unit-tests/src/org/commcare/android/tests/navigation/ExternalLaunchTests.kt
dimagi
20,939,877
false
null
package org.commcare.android.tests.navigation import android.content.Intent import android.os.Bundle import androidx.test.ext.junit.runners.AndroidJUnit4 import org.commcare.CommCareTestApplication import org.commcare.activities.DispatchActivity import org.commcare.activities.FormEntryActivity import org.commcare.activities.StandardHomeActivity import org.commcare.android.util.TestAppInstaller import org.commcare.android.util.TestUtils import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.Shadows import org.robolectric.annotation.Config import java.util.ArrayList @Config(application = CommCareTestApplication::class) @RunWith(AndroidJUnit4::class) class ExternalLaunchTests { @Before fun setup() { TestAppInstaller.installAppAndLogin( "jr://resource/commcare-apps/index_and_cache_test/profile.ccpr", "test", "123") TestUtils.processResourceTransactionIntoAppDb("/commcare-apps/case_list_lookup/restore.xml") } @Test fun testLaunchUsingSessionEndpoint() { // endpoint without arguments var homeActivity = launchHomeActivityWithSessionEndpoint("registration_form", Bundle()) verifyNextIntent(Shadows.shadowOf(homeActivity).nextStartedActivity, "Case MGMT > Registration") val argsAsBundle = Bundle() // endpoint with a case selction argsAsBundle.putString("case_id", "b319e951-03f1-4172-b662-4fb3964a0be7") homeActivity = launchHomeActivityWithSessionEndpoint("visit_form", argsAsBundle) verifyNextIntent(Shadows.shadowOf(homeActivity).nextStartedActivity, "Case MGMT > Visit > [stan]") // test with another case id argsAsBundle.clear() argsAsBundle.putString("case_id", "8e011880-602f-4017-b9d6-ed9dcbba7516") homeActivity = launchHomeActivityWithSessionEndpoint("visit_form", argsAsBundle) verifyNextIntent(Shadows.shadowOf(homeActivity).nextStartedActivity, "Case MGMT > Visit > [ellen]") // endpoint to case close form argsAsBundle.clear() argsAsBundle.putString("case_id", "c44c7ade-0cec-4401-b422-4c475f0043ae") homeActivity = launchHomeActivityWithSessionEndpoint("close_form", argsAsBundle) verifyNextIntent(Shadows.shadowOf(homeActivity).nextStartedActivity, "Case MGMT > Close > [pat]") // list args val argsAsList = ArrayList<String>() argsAsList.add("c44c7ade-0cec-4401-b422-4c475f0043ae") homeActivity = launchHomeActivityWithSessionEndpoint("close_form", argsAsList) verifyNextIntent(Shadows.shadowOf(homeActivity).nextStartedActivity, "Case MGMT > Close > [pat]") } private fun verifyNextIntent(nextIntent: Intent, header: String) { val intentActivityName: String = nextIntent.component!!.className Assert.assertEquals(FormEntryActivity::class.java.name, intentActivityName) assertEquals(nextIntent.extras!!.getString(FormEntryActivity.KEY_HEADER_STRING), header) } private fun launchHomeActivityWithSessionEndpoint(endpointId: String, args: Any): StandardHomeActivity { val intent = Intent("org.commcare.dalvik.action.CommCareSession") intent.putExtra(DispatchActivity.SESSION_ENDPOINT_ID, endpointId) if (args is Bundle) { intent.putExtra(DispatchActivity.SESSION_ENDPOINT_ARGUMENTS_BUNDLE, args) } else { intent.putStringArrayListExtra(DispatchActivity.SESSION_ENDPOINT_ARGUMENTS_LIST, args as ArrayList<String>) } intent.putExtra(DispatchActivity.WAS_EXTERNAL, true) return Robolectric.buildActivity(StandardHomeActivity::class.java, intent).create().resume().get() } }
32
Java
23
32
8a1bf52325ee7198e122eb1e43a21900e33ed29a
3,829
commcare-android
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinToResolvedCallTransformer.kt
yuexiaodong
101,063,201
true
{"Java": 24105373, "Kotlin": 24091694, "JavaScript": 144857, "Protocol Buffer": 57164, "HTML": 53068, "Lex": 18174, "Groovy": 14228, "ANTLR": 9797, "IDL": 8122, "Shell": 5436, "CSS": 4679, "Batchfile": 4437}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.resolve.calls.tower import org.jetbrains.kotlin.builtins.replaceReturnType import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.FunctionDescriptorImpl import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.calls.ArgumentTypeResolver import org.jetbrains.kotlin.resolve.calls.DiagnosticReporterByTrackingStrategy import org.jetbrains.kotlin.resolve.calls.REPORT_MISSING_NEW_INFERENCE_DIAGNOSTIC import org.jetbrains.kotlin.resolve.calls.callResolverUtil.getEffectiveExpectedType import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.isFakeElement import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext import org.jetbrains.kotlin.resolve.calls.context.CallPosition import org.jetbrains.kotlin.resolve.calls.model.* import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.makeNullableTypeIfSafeReceiver import org.jetbrains.kotlin.resolve.calls.results.ResolutionStatus import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.UnwrappedType import org.jetbrains.kotlin.types.expressions.DataFlowAnalyzer import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils import java.util.* class KotlinToResolvedCallTransformer( private val callCheckers: Iterable<CallChecker>, private val languageFeatureSettings: LanguageVersionSettings, private val dataFlowAnalyzer: DataFlowAnalyzer, private val argumentTypeResolver: ArgumentTypeResolver, private val constantExpressionEvaluator: ConstantExpressionEvaluator ) { fun <D : CallableDescriptor> transformAndReport( baseResolvedCall: ResolvedKotlinCall, context: BasicCallResolutionContext, trace: BindingTrace? // if trace is not null then all information will be reported to this trace ): ResolvedCall<D> { if (baseResolvedCall is ResolvedKotlinCall.CompletedResolvedKotlinCall) { val allResolvedCalls = baseResolvedCall.allInnerCalls.mapTo(ArrayList<ResolvedCall<*>>()) { transformAndReportCompletedCall<CallableDescriptor>(it, context, trace) } val result = transformAndReportCompletedCall<D>(baseResolvedCall.completedCall, context, trace) allResolvedCalls.add(result) if (trace != null) { val callCheckerContext = CallCheckerContext(context.replaceBindingTrace(trace), languageFeatureSettings) for (resolvedCall in allResolvedCalls) { runCallCheckers(resolvedCall, callCheckerContext) } runLambdaArgumentsChecks(context, trace, baseResolvedCall.lambdaArguments) allResolvedCalls.map { if (it is VariableAsFunctionResolvedCall) it.functionCall else it }.forEach { runArgumentsChecks(context, trace, it as NewResolvedCallImpl<*>) } } return result } val onlyResolvedCall = (baseResolvedCall as ResolvedKotlinCall.OnlyResolvedKotlinCall) trace?.record(BindingContext.ONLY_RESOLVED_CALL, onlyResolvedCall.candidate.kotlinCall.psiKotlinCall.psiCall, onlyResolvedCall) return createStubResolvedCallAndWriteItToTrace(onlyResolvedCall.candidate, trace) } fun <D : CallableDescriptor> createStubResolvedCallAndWriteItToTrace(candidate: KotlinResolutionCandidate, trace: BindingTrace?): ResolvedCall<D> { val result = when (candidate) { is VariableAsFunctionKotlinResolutionCandidate -> { val variableStub = StubOnlyResolvedCall<VariableDescriptor>(candidate.resolvedVariable) val invokeStub = StubOnlyResolvedCall<FunctionDescriptor>(candidate.invokeCandidate) StubOnlyVariableAsFunctionCall(variableStub, invokeStub) as ResolvedCall<D> } is SimpleKotlinResolutionCandidate -> { StubOnlyResolvedCall<D>(candidate) } } if (trace != null) { val tracing = candidate.kotlinCall.psiKotlinCall.tracingStrategy tracing.bindReference(trace, result) tracing.bindResolvedCall(trace, result) } return result } private fun <D : CallableDescriptor> transformAndReportCompletedCall( completedCall: CompletedKotlinCall, context: BasicCallResolutionContext, trace: BindingTrace? ): ResolvedCall<D> { fun <C> C.runIfTraceNotNull(action: (BasicCallResolutionContext, BindingTrace, C) -> Unit): C { if (trace != null) action(context, trace, this) return this } return when (completedCall) { is CompletedKotlinCall.Simple -> { NewResolvedCallImpl<D>(completedCall).runIfTraceNotNull(this::bindResolvedCall) } is CompletedKotlinCall.VariableAsFunction -> { val resolvedCall = NewVariableAsFunctionResolvedCallImpl( completedCall, NewResolvedCallImpl(completedCall.variableCall), NewResolvedCallImpl<FunctionDescriptor>(completedCall.invokeCall) ).runIfTraceNotNull(this::bindResolvedCall) @Suppress("UNCHECKED_CAST") (resolvedCall as ResolvedCall<D>) } } } private fun runCallCheckers(resolvedCall: ResolvedCall<*>, callCheckerContext: CallCheckerContext) { val calleeExpression = if (resolvedCall is VariableAsFunctionResolvedCall) resolvedCall.variableCall.call.calleeExpression else resolvedCall.call.calleeExpression val reportOn = if (calleeExpression != null && !calleeExpression.isFakeElement) calleeExpression else resolvedCall.call.callElement for (callChecker in callCheckers) { callChecker.check(resolvedCall, reportOn, callCheckerContext) if (resolvedCall is VariableAsFunctionResolvedCall) { callChecker.check(resolvedCall.variableCall, reportOn, callCheckerContext) } } } private fun runLambdaArgumentsChecks( context: BasicCallResolutionContext, trace: BindingTrace, lambdaArguments: List<PostponedLambdaArgument> ) { for (lambdaArgument in lambdaArguments) { val returnType = lambdaArgument.finalReturnType updateTraceForLambdaReturnType(lambdaArgument, trace, returnType) for (lambdaResult in lambdaArgument.resultArguments) { val resultValueArgument = lambdaResult as? PSIKotlinCallArgument ?: continue val newContext = context.replaceDataFlowInfo(resultValueArgument.dataFlowInfoAfterThisArgument) .replaceExpectedType(returnType) .replaceBindingTrace(trace) val argumentExpression = resultValueArgument.valueArgument.getArgumentExpression() ?: continue updateRecordedType(argumentExpression, newContext) } } } private fun updateTraceForLambdaReturnType(lambdaArgument: PostponedLambdaArgument, trace: BindingTrace, returnType: UnwrappedType) { val psiCallArgument = lambdaArgument.argument.psiCallArgument val ktArgumentExpression: KtExpression val ktFunction: KtElement when (psiCallArgument) { is LambdaKotlinCallArgumentImpl -> { ktArgumentExpression = psiCallArgument.ktLambdaExpression ktFunction = ktArgumentExpression.functionLiteral } is FunctionExpressionImpl -> { ktArgumentExpression = psiCallArgument.ktFunction ktFunction = ktArgumentExpression } else -> throw AssertionError("Unexpected psiCallArgument for resolved lambda argument: $psiCallArgument") } val functionDescriptor = trace.bindingContext.get(BindingContext.FUNCTION, ktFunction) as? FunctionDescriptorImpl ?: throw AssertionError("No function descriptor for resolved lambda argument") functionDescriptor.setReturnType(returnType) val existingLambdaType = trace.getType(ktArgumentExpression) ?: throw AssertionError("No type for resolved lambda argument") trace.recordType(ktArgumentExpression, existingLambdaType.replaceReturnType(returnType)) } // todo very beginning code private fun runArgumentsChecks( context: BasicCallResolutionContext, trace: BindingTrace, resolvedCall: NewResolvedCallImpl<*> ) { for (valueArgument in resolvedCall.call.valueArguments) { val argumentMapping = resolvedCall.getArgumentMapping(valueArgument!!) val (expectedType, callPosition) = when (argumentMapping) { is ArgumentMatch -> Pair( getEffectiveExpectedType(argumentMapping.valueParameter, valueArgument), CallPosition.ValueArgumentPosition(resolvedCall, argumentMapping.valueParameter, valueArgument)) else -> Pair(TypeUtils.NO_EXPECTED_TYPE, CallPosition.Unknown) } val newContext = context.replaceDataFlowInfo(resolvedCall.dataFlowInfoForArguments.getInfo(valueArgument)) .replaceExpectedType(expectedType) .replaceCallPosition(callPosition) .replaceBindingTrace(trace) // todo external argument val argumentExpression = valueArgument.getArgumentExpression() ?: continue updateRecordedType(argumentExpression, newContext) } } fun updateRecordedType( expression: KtExpression, context: BasicCallResolutionContext ): KotlinType? { val deparenthesized = expression.let { KtPsiUtil.getLastElementDeparenthesized(it, context.statementFilter) } ?: return null val recordedType = context.trace.getType(deparenthesized) var updatedType = getResolvedCallForArgumentExpression(deparenthesized, context)?.run { makeNullableTypeIfSafeReceiver(resultingDescriptor.returnType, context) } ?: recordedType // For the cases like 'foo(1)' the type of '1' depends on expected type (it can be Int, Byte, etc.), // so while the expected type is not known, it's IntegerValueType(1), and should be updated when the expected type is known. if (recordedType != null && !recordedType.constructor.isDenotable) { updatedType = argumentTypeResolver.updateResultArgumentTypeIfNotDenotable(context, deparenthesized) ?: updatedType } updatedType = updateRecordedTypeForArgument(updatedType, recordedType, expression, context) dataFlowAnalyzer.checkType(updatedType, deparenthesized, context) return updatedType } private fun getResolvedCallForArgumentExpression(expression: KtExpression, context: BasicCallResolutionContext) = if (!ExpressionTypingUtils.dependsOnExpectedType(expression)) null else expression.getResolvedCall(context.trace.bindingContext) // See CallCompleter#updateRecordedTypeForArgument private fun updateRecordedTypeForArgument( updatedType: KotlinType?, recordedType: KotlinType?, argumentExpression: KtExpression, context: BasicCallResolutionContext ): KotlinType? { if ((!ErrorUtils.containsErrorType(recordedType) && recordedType == updatedType) || updatedType == null) return updatedType val expressions = ArrayList<KtExpression>().also { expressions -> var expression: KtExpression? = argumentExpression while (expression != null) { expressions.add(expression) expression = deparenthesizeOrGetSelector(expression, context.statementFilter) } expressions.reverse() } var shouldBeMadeNullable: Boolean = false for (expression in expressions) { if (!(expression is KtParenthesizedExpression || expression is KtLabeledExpression || expression is KtAnnotatedExpression)) { shouldBeMadeNullable = hasNecessarySafeCall(expression, context.trace) } BindingContextUtils.updateRecordedType(updatedType, expression, context.trace, shouldBeMadeNullable) } return context.trace.getType(argumentExpression) } private fun deparenthesizeOrGetSelector(expression: KtExpression, statementFilter: StatementFilter): KtExpression? { val deparenthesized = KtPsiUtil.deparenthesizeOnce(expression) if (deparenthesized != expression) return deparenthesized return when (expression) { is KtBlockExpression -> statementFilter.getLastStatementInABlock(expression) is KtQualifiedExpression -> expression.selectorExpression else -> null } } private fun hasNecessarySafeCall(expression: KtExpression, trace: BindingTrace): Boolean { // We are interested in type of the last call: // 'a.b?.foo()' is safe call, but 'a?.b.foo()' is not. // Since receiver is 'a.b' and selector is 'foo()', // we can only check if an expression is safe call. if (expression !is KtSafeQualifiedExpression) return false //If a receiver type is not null, then this safe expression is useless, and we don't need to make the result type nullable. val expressionType = trace.getType(expression.receiverExpression) return expressionType != null && TypeUtils.isNullableType(expressionType) } private fun bindResolvedCall(context: BasicCallResolutionContext, trace: BindingTrace, simpleResolvedCall: NewResolvedCallImpl<*>) { reportCallDiagnostic(context, trace, simpleResolvedCall.completedCall) val tracing = simpleResolvedCall.completedCall.kotlinCall.psiKotlinCall.tracingStrategy tracing.bindReference(trace, simpleResolvedCall) tracing.bindResolvedCall(trace, simpleResolvedCall) } private fun bindResolvedCall(context: BasicCallResolutionContext, trace: BindingTrace, variableAsFunction: NewVariableAsFunctionResolvedCallImpl) { reportCallDiagnostic(context, trace, variableAsFunction.variableCall.completedCall) reportCallDiagnostic(context, trace, variableAsFunction.functionCall.completedCall) val outerTracingStrategy = variableAsFunction.completedCall.kotlinCall.psiKotlinCall.tracingStrategy outerTracingStrategy.bindReference(trace, variableAsFunction.variableCall) outerTracingStrategy.bindResolvedCall(trace, variableAsFunction) variableAsFunction.functionCall.kotlinCall.psiKotlinCall.tracingStrategy.bindReference(trace, variableAsFunction.functionCall) } private fun reportCallDiagnostic( context: BasicCallResolutionContext, trace: BindingTrace, completedCall: CompletedKotlinCall.Simple ) { val trackingTrace = TrackingBindingTrace(trace) val newContext = context.replaceBindingTrace(trackingTrace) val diagnosticReporter = DiagnosticReporterByTrackingStrategy(constantExpressionEvaluator, newContext, completedCall.kotlinCall.psiKotlinCall) for (diagnostic in completedCall.resolutionStatus.diagnostics) { trackingTrace.reported = false diagnostic.report(diagnosticReporter) val dontRecordToTraceAsIs = diagnostic is ResolutionDiagnostic && diagnostic !is VisibilityError val shouldReportMissingDiagnostic = !trackingTrace.reported && !dontRecordToTraceAsIs if (shouldReportMissingDiagnostic && REPORT_MISSING_NEW_INFERENCE_DIAGNOSTIC) { val factory = if (diagnostic.candidateApplicability.isSuccess) Errors.NEW_INFERENCE_DIAGNOSTIC else Errors.NEW_INFERENCE_ERROR trace.report(factory.on(diagnosticReporter.psiKotlinCall.psiCall.callElement, "Missing diagnostic: $diagnostic")) } } } } class TrackingBindingTrace(val trace: BindingTrace) : BindingTrace by trace { var reported: Boolean = false override fun report(diagnostic: Diagnostic) { trace.report(diagnostic) reported = true } fun markAsReported() { reported = true } } sealed class NewAbstractResolvedCall<D : CallableDescriptor>(): ResolvedCall<D> { abstract val argumentMappingByOriginal: Map<ValueParameterDescriptor, ResolvedCallArgument> abstract val kotlinCall: KotlinCall private var argumentToParameterMap: Map<ValueArgument, ArgumentMatchImpl>? = null private val _valueArguments: Map<ValueParameterDescriptor, ResolvedValueArgument> by lazy { createValueArguments() } override fun getCall(): Call = kotlinCall.psiKotlinCall.psiCall override fun getValueArguments(): Map<ValueParameterDescriptor, ResolvedValueArgument> = _valueArguments override fun getValueArgumentsByIndex(): List<ResolvedValueArgument>? { val arguments = ArrayList<ResolvedValueArgument?>(candidateDescriptor.valueParameters.size) for (i in 0..candidateDescriptor.valueParameters.size - 1) { arguments.add(null) } for ((parameterDescriptor, value) in valueArguments) { val oldValue = arguments.set(parameterDescriptor.index, value) if (oldValue != null) { return null } } if (arguments.any { it == null }) return null @Suppress("UNCHECKED_CAST") return arguments as List<ResolvedValueArgument> } override fun getArgumentMapping(valueArgument: ValueArgument): ArgumentMapping { if (argumentToParameterMap == null) { argumentToParameterMap = argumentToParameterMap(resultingDescriptor, valueArguments) } return argumentToParameterMap!![valueArgument] ?: ArgumentUnmapped } override fun getDataFlowInfoForArguments() = object : DataFlowInfoForArguments { override fun getResultInfo() = kotlinCall.psiKotlinCall.resultDataFlowInfo override fun getInfo(valueArgument: ValueArgument): DataFlowInfo { val externalPsiCallArgument = kotlinCall.externalArgument?.psiCallArgument if (externalPsiCallArgument?.valueArgument == valueArgument) { return externalPsiCallArgument.dataFlowInfoAfterThisArgument } return kotlinCall.psiKotlinCall.dataFlowInfoForArguments.getInfo(valueArgument) } } private fun argumentToParameterMap( resultingDescriptor: CallableDescriptor, valueArguments: Map<ValueParameterDescriptor, ResolvedValueArgument> ): Map<ValueArgument, ArgumentMatchImpl> = LinkedHashMap<ValueArgument, ArgumentMatchImpl>().also { result -> for (parameter in resultingDescriptor.valueParameters) { val resolvedArgument = valueArguments[parameter] ?: continue for (arguments in resolvedArgument.arguments) { result[arguments] = ArgumentMatchImpl(parameter).apply { recordMatchStatus(ArgumentMatchStatus.SUCCESS) } } } } private fun createValueArguments(): Map<ValueParameterDescriptor, ResolvedValueArgument> = LinkedHashMap<ValueParameterDescriptor, ResolvedValueArgument>().also { result -> for ((originalParameter, resolvedCallArgument) in argumentMappingByOriginal) { val resultingParameter = resultingDescriptor.valueParameters[originalParameter.index] result[resultingParameter] = when (resolvedCallArgument) { ResolvedCallArgument.DefaultArgument -> DefaultValueArgument.DEFAULT is ResolvedCallArgument.SimpleArgument -> { val valueArgument = resolvedCallArgument.callArgument.psiCallArgument.valueArgument if (resultingParameter.isVararg) VarargValueArgument().apply { addArgument(valueArgument) } else ExpressionValueArgument(valueArgument) } is ResolvedCallArgument.VarargArgument -> VarargValueArgument().apply { resolvedCallArgument.arguments.map { it.psiCallArgument.valueArgument }.forEach { addArgument(it) } } } } } } class NewResolvedCallImpl<D : CallableDescriptor>( val completedCall: CompletedKotlinCall.Simple ): NewAbstractResolvedCall<D>() { override val kotlinCall: KotlinCall get() = completedCall.kotlinCall override fun getStatus(): ResolutionStatus = completedCall.resolutionStatus.resultingApplicability.toResolutionStatus() override val argumentMappingByOriginal: Map<ValueParameterDescriptor, ResolvedCallArgument> get() = completedCall.argumentMappingByOriginal override fun getCandidateDescriptor(): D = completedCall.candidateDescriptor as D override fun getResultingDescriptor(): D = completedCall.resultingDescriptor as D override fun getExtensionReceiver(): ReceiverValue? = completedCall.extensionReceiver?.receiverValue override fun getDispatchReceiver(): ReceiverValue? = completedCall.dispatchReceiver?.receiverValue override fun getExplicitReceiverKind(): ExplicitReceiverKind = completedCall.explicitReceiverKind override fun getTypeArguments(): Map<TypeParameterDescriptor, KotlinType> { val typeParameters = candidateDescriptor.typeParameters.takeIf { it.isNotEmpty() } ?: return emptyMap() return typeParameters.zip(completedCall.typeArguments).toMap() } override fun getSmartCastDispatchReceiverType(): KotlinType? = null // todo } fun ResolutionCandidateApplicability.toResolutionStatus(): ResolutionStatus = when (this) { ResolutionCandidateApplicability.RESOLVED, ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY -> ResolutionStatus.SUCCESS ResolutionCandidateApplicability.INAPPLICABLE_WRONG_RECEIVER -> ResolutionStatus.RECEIVER_TYPE_ERROR else -> ResolutionStatus.OTHER_ERROR } class NewVariableAsFunctionResolvedCallImpl( val completedCall: CompletedKotlinCall.VariableAsFunction, override val variableCall: NewResolvedCallImpl<VariableDescriptor>, override val functionCall: NewResolvedCallImpl<FunctionDescriptor> ): VariableAsFunctionResolvedCall, ResolvedCall<FunctionDescriptor> by functionCall class StubOnlyResolvedCall<D : CallableDescriptor>(val candidate: SimpleKotlinResolutionCandidate): NewAbstractResolvedCall<D>() { override fun getStatus() = candidate.status.resultingApplicability.toResolutionStatus() override fun getCandidateDescriptor(): D = candidate.candidateDescriptor as D override fun getResultingDescriptor(): D = candidate.descriptorWithFreshTypes as D override fun getExtensionReceiver() = candidate.extensionReceiver?.receiver?.receiverValue override fun getDispatchReceiver() = candidate.dispatchReceiverArgument?.receiver?.receiverValue override fun getExplicitReceiverKind() = candidate.explicitReceiverKind override fun getTypeArguments(): Map<TypeParameterDescriptor, KotlinType> = emptyMap() override fun getSmartCastDispatchReceiverType(): KotlinType? = null override val argumentMappingByOriginal: Map<ValueParameterDescriptor, ResolvedCallArgument> get() = candidate.argumentMappingByOriginal override val kotlinCall: KotlinCall get() = candidate.kotlinCall } class StubOnlyVariableAsFunctionCall( override val variableCall: StubOnlyResolvedCall<VariableDescriptor>, override val functionCall: StubOnlyResolvedCall<FunctionDescriptor> ) : VariableAsFunctionResolvedCall, ResolvedCall<FunctionDescriptor> by functionCall
1
Java
1
1
d5f0607cef375fd0a0b3fc8643fc95e2c93df4de
25,708
kotlin
Apache License 2.0
app/src/androidInstrumentedTest/kotlin/io/github/xxfast/decompose/router/app/TestPagesRouters.kt
xxfast
599,478,957
false
{"Kotlin": 64949, "Swift": 2406, "HTML": 676, "CSS": 342}
package io.github.xxfast.decompose.router.app import android.content.pm.ActivityInfo import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertTextContains import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToIndex import androidx.compose.ui.test.performScrollToNode import org.junit.Rule import org.junit.Test class TestPagesRouters { @get:Rule val composeRule: TestActivityRule = createAndroidComposeRule() @Test fun testPagesNavigation(): Unit = with(composeRule) { // Go to pages and swipe to the 5th page onNode(bottomNavPagesItem).performClick() onNode(pager).performScrollToIndex(5) onNode(hasText("5")).assertExists() // Verify pages screens are restored activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE onNode(pager).assertExists() onNode(hasText("5")).assertExists() activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT onNode(pager).assertExists() onNode(hasText("5")).assertExists() } }
8
Kotlin
9
218
f66446689428f1716c12e47d53cbcdf7be560283
1,226
Decompose-Router
Apache License 2.0
src/org/toml/lang/icons/TomlIconProvider.kt
Falkenfighter
46,069,512
false
null
package org.toml.lang.icons import com.intellij.ide.IconProvider import com.intellij.psi.PsiElement import org.toml.lang.core.psi.TomlFile import javax.swing.Icon public class TomlIconProvider : IconProvider() { override fun getIcon(element: PsiElement, flags: Int): Icon? { return when (element) { is TomlFile -> getFileIcon(element) else -> null } } fun getFileIcon(element: TomlFile): Icon? { return when (element.name) { "Cargo.toml" -> TomlIcons.CARGO_FILE "Cargo.lock" -> TomlIcons.CARGO_LOCK_FILE else -> null } } }
1
null
1
1
211da249631d3932a030ccc9bb05eef5d4987d50
635
intellij-rust
MIT License
app/src/main/java/com/sweet/dagger/di/AmountModule.kt
amirMohammadShirin
839,199,119
false
{"Kotlin": 15413}
package com.sweet.dagger.di import dagger.Module import dagger.Provides import java.math.BigDecimal @Module class AmountModule { @Provides @MinAmount fun provideMinAmount() = BigDecimal.ZERO @Provides @MaxAmount fun provideMaxAmount() = BigDecimal(10000) }
0
Kotlin
0
1
0f428b2f133e8092dfb4ae75860053785d302f88
285
dagger
MIT License
app/src/main/java/com/hiteshsahu/notificationlistener/activity/dummy/BigTextMainActivity.kt
hiteshsahu
240,263,632
false
null
/* Copyright 2016 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.hiteshsahu.notificationlistener.activity.dummy import android.app.Activity import android.app.NotificationManager import android.content.Context import android.os.Bundle import com.hiteshsahu.notificationlistener.NotificationDemoActivity import com.hiteshsahu.notificationlistener.R /** * Template class meant to include functionality for your Social App. (This project's main focus * is on Notification Styles.) */ class BigPictureSocialMainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_big_picture_main) // Cancel Notification val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(NotificationDemoActivity.NOTIFICATION_ID) // TODO: Handle and display social post from your database } }
1
Kotlin
2
5
c42f4dfecdc9aab51be1fd6340063969c840748e
1,525
Android-Notification-Demo
Apache License 2.0
build-logic/convention/src/main/kotlin/com/significo/bugtracker/AndroidCompose.kt
SignificoHealth
824,561,094
false
{"Kotlin": 237482}
package com.significo.bugtracker import com.android.build.api.dsl.CommonExtension import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies /** * Configure Compose-specific options */ @Suppress("StringLiteralDuplication") internal fun Project.configureAndroidCompose( commonExtension: CommonExtension<*, *, *, *, *, *>, ) { commonExtension.apply { buildFeatures { compose = true } dependencies { val bom = platform(libs.androidx.compose.bom) "implementation"(bom) "androidTestImplementation"(bom) "implementation"(libs.bundles.compose.ui) } } }
2
Kotlin
0
1
ed27c4012925789e47f8fc422f9d095ab3a821df
669
bug-tracker-showcase-android
Apache License 2.0
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/integer-literals/hexadecimal-integer-literals/p-1/neg/2.1.fir.kt
android
263,405,600
true
null
// TESTCASE NUMBER: 1 val value_1 = 0x_1234567890 // TESTCASE NUMBER: 2 val value_2 = 0X_______23456789 // TESTCASE NUMBER: 3 val value_3 = 0X_2_3_4_5_6_7_8_9 // TESTCASE NUMBER: 4 val value_4 = <!ILLEGAL_CONST_EXPRESSION!>0x_<!>
0
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
233
kotlin
Apache License 2.0
turf/src/commonMain/kotlin/io/github/elcolto/geokjson/turf/measurement/Square.kt
elcolto
807,275,879
false
{"Kotlin": 320710}
package io.github.elcolto.geokjson.turf.measurement import io.github.elcolto.geokjson.geojson.BoundingBox import io.github.elcolto.geokjson.geojson.Position import io.github.elcolto.geokjson.turf.ExperimentalTurfApi /** * Takes a bounding box and calculates the minimum square bounding box that would contain the input. * @return [BoundingBox] a square surrounding [boundingBox] */ @ExperimentalTurfApi public fun square(boundingBox: BoundingBox): BoundingBox { val (east, north) = boundingBox.northeast val (west, south) = boundingBox.southwest val horizontalDistance = distance(Position(west, south), Position(east, south)) val verticalDistance = distance(Position(west, south), Position(west, north)) return if (horizontalDistance >= verticalDistance) { val verticalMidpoint = (south + north) / 2 BoundingBox( west = west, south = verticalMidpoint - (east - west) / 2, east = east, north = verticalMidpoint + (east - west) / 2, ) } else { val horizontalMidpoint = (west + east) / 2 BoundingBox( west = horizontalMidpoint - (north - south) / 2, south = south, east = horizontalMidpoint + (north - south) / 2, north = north, ) } }
44
Kotlin
0
2
c7026b9765141120a74277287476195255a7735f
1,310
GeoKJSON
Apache License 2.0
sample/src/androidTest/java/com/sebaslogen/resacaapp/sample/hilt/ComposeActivityRecreationTests.kt
sebaslogen
431,489,181
false
{"Kotlin": 100252, "Swift": 621, "HTML": 339, "CSS": 102}
package com.sebaslogen.resacaapp.sample.hilt import android.content.Intent import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.junit4.createEmptyComposeRule import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.sebaslogen.resaca.COMPOSITION_RESUMED_TIMEOUT_IN_SECONDS import com.sebaslogen.resacaapp.sample.ui.main.ComposeActivity import com.sebaslogen.resacaapp.sample.ui.main.hiltSingleViewModelScopedDestination import com.sebaslogen.resacaapp.sample.ui.main.hiltViewModelScopedDestination import com.sebaslogen.resacaapp.sample.ui.main.showSingleScopedViewModel import com.sebaslogen.resacaapp.sample.utils.ComposeTestUtils import com.sebaslogen.resacaapp.sample.viewModelsClearedGloballySharedCounter import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class ComposeActivityRecreationTests : ComposeTestUtils { private lateinit var scenario: ActivityScenario<ComposeActivity> @get:Rule override val composeTestRule = createEmptyComposeRule() @Before fun setUp() { scenario = ActivityScenario.launch( Intent(ApplicationProvider.getApplicationContext(), ComposeActivity::class.java).apply { putExtra(ComposeActivity.START_DESTINATION, hiltViewModelScopedDestination) }) } @Test fun whenISwitchFromLightModeToNightMode_thenTheOneAndOnlyHiltScopedViewModelThatSOnlyUsedInLightModeIsGoneAndTheRestStay() { // Given the starting screen with Hilt ViewModel scoped that is ONLY shown in light mode composeTestRule.waitForIdle() // Find the scoped text fields and grab their texts val initialFakeScopedRepoText = retrieveTextFromNodeWithTestTag("FakeRepo Scoped") retrieveTextFromNodeWithTestTag("Hilt FakeInjectedViewModel Scoped") printComposeUiTreeToLog() // When I change to night mode and apply the configuration change by recreating the Activity showSingleScopedViewModel = false // This is a fake night-mode change but it will remove Composable after Activity re-creation scenario.recreate() printComposeUiTreeToLog() // Then the scoped object is still the same but the Hilt Injected ViewModel disappears // Then the text of the NOT scoped object is different from the original one because it's a new object onNodeWithTestTag("FakeRepo Scoped").assertIsDisplayed().assertTextEquals(initialFakeScopedRepoText) onNodeWithTestTag("Hilt FakeInjectedViewModel Scoped", assertDisplayed = false).assertDoesNotExist() } @Test fun whenTheActivityIsRecreated_thenTheScopedObjectAndHiltInjectedScopedViewModelRemainTheSame() { // Given the starting screen with Hilt injected ViewModel scoped composeTestRule.waitForIdle() // Find the scoped text fields and grab their texts val initialFakeScopedRepoText = retrieveTextFromNodeWithTestTag("FakeRepo Scoped") val initialHiltFakeScopedViewModelText = retrieveTextFromNodeWithTestTag("Hilt FakeSecondInjectedViewModel Scoped") printComposeUiTreeToLog() // When I change to night mode and apply the configuration change by recreating the Activity showSingleScopedViewModel = false // This is a fake night-mode change but it will remove Composable after Activity re-creation scenario.recreate() printComposeUiTreeToLog() // Then the scoped objects are still the same onNodeWithTestTag("FakeRepo Scoped").assertIsDisplayed().assertTextEquals(initialFakeScopedRepoText) onNodeWithTestTag("Hilt FakeSecondInjectedViewModel Scoped").assertIsDisplayed().assertTextEquals(initialHiltFakeScopedViewModelText) } @Test fun whenISwitchFromLightModeToNightMode_thenTheOneAndOnlyHiltScopedViewModelThatSOnlyUsedInLightModeIsGone() { // Given the starting screen with ViewModel scoped that is ONLY shown in light mode scenario = ActivityScenario.launch( Intent(ApplicationProvider.getApplicationContext(), ComposeActivity::class.java).apply { putExtra(ComposeActivity.START_DESTINATION, hiltSingleViewModelScopedDestination) }) scenario.recreate() composeTestRule.waitForIdle() // Find the scoped text fields and grab their texts retrieveTextFromNodeWithTestTag("Hilt FakeInjectedViewModel Scoped") val initialAmountOfViewModelsCleared = viewModelsClearedGloballySharedCounter.get() printComposeUiTreeToLog() // When I change to night mode and apply the configuration change by recreating the Activity showSingleScopedViewModel = false // This is a fake night-mode change but it will remove Composable after Activity re-creation scenario.recreate() printComposeUiTreeToLog() Thread.sleep(COMPOSITION_RESUMED_TIMEOUT_IN_SECONDS * 1000) // Wait for the ViewModel to be cleared val finalAmountOfViewModelsCleared = viewModelsClearedGloballySharedCounter.get() // Then the scoped ViewModel disappears onNodeWithTestTag("Hilt FakeInjectedViewModel Scoped", assertDisplayed = false).assertDoesNotExist() assert(finalAmountOfViewModelsCleared == initialAmountOfViewModelsCleared + 1) { "The amount of FakeInjectedViewModel that were cleared after key change ($finalAmountOfViewModelsCleared) " + "was not higher that the amount before the key change ($initialAmountOfViewModelsCleared)" } } }
2
Kotlin
9
406
9d923bd86cc7c0db028a29c617c946091f627cff
5,777
resaca
MIT License
host/src/commonMain/kotlin/base/binding/IndirectFunctionBindingProvider.kt
illarionov
848,247,126
false
{"Kotlin": 993693, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package at.released.weh.host.base.binding import at.released.weh.host.base.function.IndirectFunctionTableIndex public fun interface IndirectFunctionBindingProvider { public fun getFunctionBinding(indirectId: IndirectFunctionTableIndex): WasmFunctionBinding? }
0
Kotlin
0
2
eaa94b81d4da64d2ea763eb2cfe61a386d56f092
536
wasi-emscripten-host
Apache License 2.0
src/main/kotlin/no/nav/eessi/pensjon/personidentifisering/PersonModel.kt
navikt
178,813,650
false
null
package no.nav.eessi.pensjon.personidentifisering import no.nav.eessi.pensjon.eux.model.SedType import no.nav.eessi.pensjon.eux.model.buc.SakType import no.nav.eessi.pensjon.personoppslag.pdl.model.SokKriterier import no.nav.eessi.pensjon.shared.person.Fodselsnummer import java.time.LocalDate data class IdentifisertPerson( val aktoerId: String, //fra PDL val personNavn: String?, //fra PDL val landkode: String?, //fra PDL val geografiskTilknytning: String?, //fra PDL val personRelasjon: SEDPersonRelasjon, //fra PDL val fodselsdato: String? = null, //innhenting fra FnrHelper og SED var personListe: List<IdentifisertPerson>? = null //fra PDL){} ) { override fun toString(): String { return "IdentifisertPerson(aktoerId='$aktoerId', personNavn=$personNavn, landkode=$landkode, geografiskTilknytning=$geografiskTilknytning, personRelasjon=$personRelasjon)" } fun flereEnnEnPerson() = personListe != null && personListe!!.size > 1 } data class SEDPersonRelasjon( val fnr: Fodselsnummer?, val relasjon: Relasjon, val saktype: SakType? = null, val sedType: SedType? = null, val sokKriterier: SokKriterier? = null, val fdato: LocalDate? = null, val rinaDocumentId: String ) { fun isFnrDnrSinFdatoLikSedFdato(): Boolean { //fdato == null and return true validation allow fnr //fdato == null and return false validation fail if (fdato == null) return true return fnr?.getBirthDate() == fdato } } enum class Relasjon { FORSIKRET, GJENLEVENDE, AVDOD, ANNET, BARN, FORSORGER }
1
Kotlin
2
6
ecffc4ad04aa9da50a0a7de401e5b9eb5ea34f95
1,743
eessi-pensjon-journalforing
MIT License
plugins/opendmp-ffmpeg/src/main/kotlin/io/opendmp/plugin/ffmpeg/config/FFMPEGConfiguration.kt
rhinoman
266,865,791
false
null
package io.opendmp.plugin.ffmpeg.config import io.opendmp.common.model.ProcessorType import io.opendmp.common.model.plugin.FieldDescription import io.opendmp.common.model.plugin.FieldType import io.opendmp.common.model.plugin.PluginConfiguration import io.opendmp.sdk.plugin.config.PluginConfigurationProvider import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Configuration @Configuration class FFMPEGConfiguration : PluginConfigurationProvider { private val fields = mapOf( "command" to FieldDescription( type = FieldType.STRING, required = true, helperText = "The command line to pass to FFMPEG"), "timeout" to FieldDescription( type = FieldType.NUMBER, required = false, helperText = "The amount of time (in seconds) to wait for FFMPEG to complete")) @Value("\${odmp.plugin.name}") lateinit var pluginName: String override fun pluginConfiguration() = PluginConfiguration( serviceName = pluginName, displayName = "FFMPEG Processor", type = ProcessorType.EXTERNAL, fields = fields) }
6
Kotlin
5
27
c7f36699647c6c4952e069d062099efe12e9b179
1,251
odmp
Apache License 2.0
app/src/main/java/com/samuelokello/kazihub/domain/model/job/JobResponse.kt
OkelloSam21
749,782,789
false
{"Kotlin": 326914}
package com.samuelokello.kazihub.domain.model.job import com.google.gson.annotations.SerializedName data class JobResponse( @SerializedName("code") val code: Int?, @SerializedName("data") val job: List<data>?, @SerializedName("message") val message: String?, @SerializedName("status") val status: String? )
0
Kotlin
0
0
6333e167c837eb9ae9d4549a09ca6ae621e12353
341
KaziHub
MIT License
android/app-newm/src/main/java/io/newm/NewmAppComposable.kt
projectNEWM
435,674,758
false
{"Kotlin": 559511, "Swift": 299324}
package io.newm import android.content.Intent import android.net.Uri import androidx.activity.compose.BackHandler import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExitTransition import androidx.compose.animation.slideInVertically import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalBottomSheetLayout import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.slack.circuit.backstack.rememberSaveableBackStack import com.slack.circuit.foundation.NavigableCircuitContent import com.slack.circuit.foundation.rememberCircuitNavigator import io.newm.core.resources.R import io.newm.core.theme.Black import io.newm.core.theme.BrightOrange import io.newm.core.theme.DarkPink import io.newm.core.theme.DarkViolet import io.newm.core.theme.Gray100 import io.newm.core.theme.LightSkyBlue import io.newm.core.theme.OceanGreen import io.newm.core.theme.YellowJacket import io.newm.core.theme.inter import io.newm.core.ui.utils.drawWithBrush import io.newm.core.ui.utils.iconGradient import io.newm.feature.musicplayer.MiniPlayer import io.newm.feature.musicplayer.MusicPlayerScreen import io.newm.screens.Screen import io.newm.shared.NewmAppLogger import kotlinx.coroutines.launch import com.slack.circuit.runtime.screen.Screen as CircuitScreen internal const val TAG_BOTTOM_NAVIGATION = "TAG_BOTTOM_NAVIGATION" private val HomeIconGradient = iconGradient(LightSkyBlue, DarkViolet) private val AccountIconGradient = iconGradient(LightSkyBlue, DarkViolet) private val LibraryIconGradient = iconGradient(DarkViolet, DarkPink) private val SearchIconGradient = iconGradient(DarkPink, BrightOrange) private val WalletIconGradient = iconGradient(OceanGreen, LightSkyBlue) private val MarketIconGradient = iconGradient(BrightOrange, YellowJacket) val LocalIsBottomBarVisible = compositionLocalOf { mutableStateOf(true) } @Composable internal fun isBottomBarVisible() = remember { mutableStateOf(true) } val initialScreen = Screen.NFTLibrary @OptIn(ExperimentalMaterialApi::class) @Composable internal fun NewmApp(logger: NewmAppLogger) { val backstack = rememberSaveableBackStack { push(initialScreen) } val circuitNavigator = rememberCircuitNavigator( backstack, // Disabling back handler because we are using our own enableBackHandler = false ) val context = LocalContext.current val newmNavigator = rememberNewmNavigator(circuitNavigator, logger, {}, launchBrowser = { url -> context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }) val currentRootScreen = backstack.topRecord?.screen val sheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Hidden, skipHalfExpanded = true ) val coroutineScope = rememberCoroutineScope() BackHandler( enabled = backstack.size > 1 || currentRootScreen != initialScreen || sheetState.isVisible ) { when { sheetState.isVisible -> coroutineScope.launch { sheetState.hide() } backstack.size > 1 -> newmNavigator.pop() currentRootScreen != initialScreen -> newmNavigator.resetRoot(initialScreen) } } ModalBottomSheetLayout( modifier = Modifier, sheetState = sheetState, sheetContent = { MusicPlayerScreen(onNavigateUp = { coroutineScope.launch { sheetState.hide() } }) }, ) { Scaffold( bottomBar = { AnimatedVisibility( visible = LocalIsBottomBarVisible.current.value, enter = slideInVertically(initialOffsetY = { it }), exit = ExitTransition.None ) { Column( modifier = Modifier.fillMaxWidth(), ) { MiniPlayer( modifier = Modifier.clickable { coroutineScope.launch { sheetState.show() } } ) Spacer( modifier = Modifier .height(2.dp) .fillMaxWidth() .background(MaterialTheme.colors.surface) ) NewmBottomNavigation( currentRootScreen = currentRootScreen, onNavigationSelected = { circuitNavigator.resetRoot(it) } ) } } } ) { padding -> NavigableCircuitContent( modifier = Modifier.padding(padding), navigator = newmNavigator, backstack = backstack ) } } } @Composable internal fun NewmBottomNavigation( currentRootScreen: CircuitScreen?, onNavigationSelected: (Screen) -> Unit ) { Column(Modifier.height(76.dp)) { BottomNavigation( modifier = Modifier .fillMaxHeight() .testTag(TAG_BOTTOM_NAVIGATION), backgroundColor = Black, contentColor = Gray100 ) { HomeBottomNavigationItem( selected = currentRootScreen == Screen.NFTLibrary, iconResId = R.drawable.ic_library, labelResId = R.string.nft_library, selectedIconBrush = LibraryIconGradient, selectedLabelColor = DarkPink, onClick = { onNavigationSelected(Screen.NFTLibrary) }, ) HomeBottomNavigationItem( selected = currentRootScreen == Screen.UserAccount, iconResId = R.drawable.ic_profile, labelResId = R.string.account, selectedIconBrush = AccountIconGradient, selectedLabelColor = DarkPink, onClick = { onNavigationSelected(Screen.UserAccount) }, ) } } } @Preview(showBackground = true) @Composable fun BottomNavigationBarPreview() { NewmBottomNavigation(Screen.NFTLibrary) {} } // Based on content from: https://github.com/wlara/android-next-gen/blob/main/app/src/main/java/com/github/wlara/nextgen/ui/home/HomeScreen.kt @Composable private fun RowScope.HomeBottomNavigationItem( selected: Boolean, @DrawableRes iconResId: Int, @StringRes labelResId: Int, selectedIconBrush: Brush, selectedLabelColor: Color, onClick: () -> Unit, ) { val label = stringResource(id = labelResId) BottomNavigationItem( icon = { Icon( modifier = if (selected) { Modifier .align(Alignment.CenterVertically) .drawWithBrush(selectedIconBrush) } else { Modifier.align(Alignment.CenterVertically) }, painter = painterResource(id = iconResId), contentDescription = label, ) }, label = { Text( text = label, fontFamily = inter, fontWeight = FontWeight.SemiBold, fontSize = 10.sp, color = if (selected) selectedLabelColor else Color.Unspecified ) }, selected = selected, onClick = onClick ) }
2
Kotlin
9
16
fcb5edf172891478ac612260c3eacdb42e1e943d
9,265
newm-mobile
Apache License 2.0
android/app-newm/src/main/java/io/newm/NewmAppComposable.kt
projectNEWM
435,674,758
false
{"Kotlin": 559511, "Swift": 299324}
package io.newm import android.content.Intent import android.net.Uri import androidx.activity.compose.BackHandler import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExitTransition import androidx.compose.animation.slideInVertically import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalBottomSheetLayout import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.slack.circuit.backstack.rememberSaveableBackStack import com.slack.circuit.foundation.NavigableCircuitContent import com.slack.circuit.foundation.rememberCircuitNavigator import io.newm.core.resources.R import io.newm.core.theme.Black import io.newm.core.theme.BrightOrange import io.newm.core.theme.DarkPink import io.newm.core.theme.DarkViolet import io.newm.core.theme.Gray100 import io.newm.core.theme.LightSkyBlue import io.newm.core.theme.OceanGreen import io.newm.core.theme.YellowJacket import io.newm.core.theme.inter import io.newm.core.ui.utils.drawWithBrush import io.newm.core.ui.utils.iconGradient import io.newm.feature.musicplayer.MiniPlayer import io.newm.feature.musicplayer.MusicPlayerScreen import io.newm.screens.Screen import io.newm.shared.NewmAppLogger import kotlinx.coroutines.launch import com.slack.circuit.runtime.screen.Screen as CircuitScreen internal const val TAG_BOTTOM_NAVIGATION = "TAG_BOTTOM_NAVIGATION" private val HomeIconGradient = iconGradient(LightSkyBlue, DarkViolet) private val AccountIconGradient = iconGradient(LightSkyBlue, DarkViolet) private val LibraryIconGradient = iconGradient(DarkViolet, DarkPink) private val SearchIconGradient = iconGradient(DarkPink, BrightOrange) private val WalletIconGradient = iconGradient(OceanGreen, LightSkyBlue) private val MarketIconGradient = iconGradient(BrightOrange, YellowJacket) val LocalIsBottomBarVisible = compositionLocalOf { mutableStateOf(true) } @Composable internal fun isBottomBarVisible() = remember { mutableStateOf(true) } val initialScreen = Screen.NFTLibrary @OptIn(ExperimentalMaterialApi::class) @Composable internal fun NewmApp(logger: NewmAppLogger) { val backstack = rememberSaveableBackStack { push(initialScreen) } val circuitNavigator = rememberCircuitNavigator( backstack, // Disabling back handler because we are using our own enableBackHandler = false ) val context = LocalContext.current val newmNavigator = rememberNewmNavigator(circuitNavigator, logger, {}, launchBrowser = { url -> context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }) val currentRootScreen = backstack.topRecord?.screen val sheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Hidden, skipHalfExpanded = true ) val coroutineScope = rememberCoroutineScope() BackHandler( enabled = backstack.size > 1 || currentRootScreen != initialScreen || sheetState.isVisible ) { when { sheetState.isVisible -> coroutineScope.launch { sheetState.hide() } backstack.size > 1 -> newmNavigator.pop() currentRootScreen != initialScreen -> newmNavigator.resetRoot(initialScreen) } } ModalBottomSheetLayout( modifier = Modifier, sheetState = sheetState, sheetContent = { MusicPlayerScreen(onNavigateUp = { coroutineScope.launch { sheetState.hide() } }) }, ) { Scaffold( bottomBar = { AnimatedVisibility( visible = LocalIsBottomBarVisible.current.value, enter = slideInVertically(initialOffsetY = { it }), exit = ExitTransition.None ) { Column( modifier = Modifier.fillMaxWidth(), ) { MiniPlayer( modifier = Modifier.clickable { coroutineScope.launch { sheetState.show() } } ) Spacer( modifier = Modifier .height(2.dp) .fillMaxWidth() .background(MaterialTheme.colors.surface) ) NewmBottomNavigation( currentRootScreen = currentRootScreen, onNavigationSelected = { circuitNavigator.resetRoot(it) } ) } } } ) { padding -> NavigableCircuitContent( modifier = Modifier.padding(padding), navigator = newmNavigator, backstack = backstack ) } } } @Composable internal fun NewmBottomNavigation( currentRootScreen: CircuitScreen?, onNavigationSelected: (Screen) -> Unit ) { Column(Modifier.height(76.dp)) { BottomNavigation( modifier = Modifier .fillMaxHeight() .testTag(TAG_BOTTOM_NAVIGATION), backgroundColor = Black, contentColor = Gray100 ) { HomeBottomNavigationItem( selected = currentRootScreen == Screen.NFTLibrary, iconResId = R.drawable.ic_library, labelResId = R.string.nft_library, selectedIconBrush = LibraryIconGradient, selectedLabelColor = DarkPink, onClick = { onNavigationSelected(Screen.NFTLibrary) }, ) HomeBottomNavigationItem( selected = currentRootScreen == Screen.UserAccount, iconResId = R.drawable.ic_profile, labelResId = R.string.account, selectedIconBrush = AccountIconGradient, selectedLabelColor = DarkPink, onClick = { onNavigationSelected(Screen.UserAccount) }, ) } } } @Preview(showBackground = true) @Composable fun BottomNavigationBarPreview() { NewmBottomNavigation(Screen.NFTLibrary) {} } // Based on content from: https://github.com/wlara/android-next-gen/blob/main/app/src/main/java/com/github/wlara/nextgen/ui/home/HomeScreen.kt @Composable private fun RowScope.HomeBottomNavigationItem( selected: Boolean, @DrawableRes iconResId: Int, @StringRes labelResId: Int, selectedIconBrush: Brush, selectedLabelColor: Color, onClick: () -> Unit, ) { val label = stringResource(id = labelResId) BottomNavigationItem( icon = { Icon( modifier = if (selected) { Modifier .align(Alignment.CenterVertically) .drawWithBrush(selectedIconBrush) } else { Modifier.align(Alignment.CenterVertically) }, painter = painterResource(id = iconResId), contentDescription = label, ) }, label = { Text( text = label, fontFamily = inter, fontWeight = FontWeight.SemiBold, fontSize = 10.sp, color = if (selected) selectedLabelColor else Color.Unspecified ) }, selected = selected, onClick = onClick ) }
2
Kotlin
9
16
fcb5edf172891478ac612260c3eacdb42e1e943d
9,265
newm-mobile
Apache License 2.0
src/main/kotlin/no/nav/medlemskap/regler/v1/Hovedregler.kt
navikt
225,422,169
false
{"Kotlin": 931416, "Gherkin": 415998, "Shell": 151, "Dockerfile": 147}
package no.nav.medlemskap.regler.v1 import no.nav.medlemskap.domene.Datagrunnlag import no.nav.medlemskap.domene.Statsborgerskapskategori import no.nav.medlemskap.domene.Ytelse import no.nav.medlemskap.regler.ReglerForHovedsakligArbeidstaker import no.nav.medlemskap.regler.common.Regel.Companion.jaKonklusjon import no.nav.medlemskap.regler.common.Regel.Companion.neiKonklusjon import no.nav.medlemskap.regler.common.Regel.Companion.uavklartKonklusjon import no.nav.medlemskap.regler.common.RegelId import no.nav.medlemskap.regler.common.Regler import no.nav.medlemskap.regler.common.Resultat import no.nav.medlemskap.regler.common.Resultat.Companion.finnÅrsaker import no.nav.medlemskap.regler.common.Svar import no.nav.medlemskap.regler.common.Svar.* class Hovedregler(private val datagrunnlag: Datagrunnlag) { private val reglerForRequestValidering = ReglerForRequestValidering.fraDatagrunnlag(datagrunnlag) private val reglerForOverstyring = ReglerForOverstyring.fraDatagrunnlag(datagrunnlag) private val reglerForStatsborgerskap = ReglerForStatsborgerskap.fraDatagrunnlag(datagrunnlag) private val reglerForTredjelandsborgerFamlie = ReglerForTredjelandsborgerFamilie.fraDatagrunnlag(datagrunnlag) fun kjørHovedregler(): Resultat { val requestValideringResultat = reglerForRequestValidering.kjørRegel() if (requestValideringResultat.svar != JA) { return requestValideringResultat } val ytelse = reglerForRequestValidering.ytelse val resultater = mutableListOf<Resultat>() // val resultatForOverstyring = reglerForOverstyring.kjørHovedflyt() // val reglerSomSkalOverstyres = reglerForOverstyring.reglerSomSkalOverstyres(resultatForOverstyring) val reglerSomSkalOverstyres = emptyMap<RegelId, Svar>() // resultater.add(resultatForOverstyring) resultater.addAll(kjørFellesRegler()) val resultatStatsborgerskap = reglerForStatsborgerskap.kjørHovedflyt() resultater.add(resultatStatsborgerskap) var resultatEOSFamilie: Resultat? = null if (!resultatStatsborgerskap.erNorskBorger() && !resultatStatsborgerskap.erEøsBorger()) { resultatEOSFamilie = reglerForTredjelandsborgerFamlie.kjørHovedflyt() resultater.add(resultatEOSFamilie) } val resultaterForStatsborger = kjørReglerForStatsborgerskap(resultatStatsborgerskap, resultatEOSFamilie, reglerSomSkalOverstyres) resultater.addAll(resultaterForStatsborger) return utledResultat(ytelse, resultater) } private fun kjørReglerForStatsborgerskap( resultatStatsborgerskap: Resultat, resultatEOSFamilie: Resultat?, reglerSomSkalOverstyres: Map<RegelId, Svar> ): List<Resultat> { val statsborgerskapskategori = velgStatsborgerskapKategori(resultatStatsborgerskap, resultatEOSFamilie) return when (statsborgerskapskategori) { Statsborgerskapskategori.TREDJELANDSBORGER -> kjørReglerForTredjelandsborgere() Statsborgerskapskategori.EØS_BORGER -> kjørReglerForEøsBorgere(reglerSomSkalOverstyres, resultatEOSFamilie) Statsborgerskapskategori.TREDJELANDSBORGER_MED_EOS_FAMILIE -> kjørReglerForEøsBorgere( reglerSomSkalOverstyres, resultatEOSFamilie ) Statsborgerskapskategori.NORSK_BORGER -> kjørReglerForNorskeBorgere(reglerSomSkalOverstyres) } } private fun velgStatsborgerskapKategori( resultatStatsborgerskap: Resultat, resultatEOSFamilie: Resultat? ): Statsborgerskapskategori { return when (resultatEOSFamilie?.svar) { JA -> resultatEOSFamilie.bestemStatsborgerskapskategori() else -> resultatStatsborgerskap.bestemStatsborgerskapskategori() } } private fun kjørReglerForTredjelandsborgere(): List<Resultat> { val resultater = mutableListOf<Resultat>() resultater.add(ReglerForHovedsakligArbeidstaker.fraDatagrunnlag(datagrunnlag).kjørHovedflyt()) resultater.add(ReglerForOppholdstillatelse.fraDatagrunnlag(datagrunnlag).kjørHovedflyt()) val resultatMedl = ReglerForMedl.fraDatagrunnlag(datagrunnlag).kjørHovedflyt() resultater.add(resultatMedl) if (resultatMedl.erRegelflytKonklusjon() && resultatMedl.svar == JA || resultatMedl.svar == UAVKLART) { resultater.add(ReglerForAndreStatsborgere.fraDatagrunnlag(datagrunnlag).kjørHovedflyt()) } return resultater } private fun kjørReglerForNorskeBorgere(overstyrteRegler: Map<RegelId, Svar>): List<Resultat> { return listOf( ReglerForMedl.fraDatagrunnlag(datagrunnlag), ReglerForArbeidsforhold.fraDatagrunnlag(datagrunnlag, overstyrteRegler), ReglerForBosatt.fraDatagrunnlag(datagrunnlag), ReglerForNorskeStatsborgere.fraDatagrunnlag(datagrunnlag, overstyrteRegler) ).map { it.kjørHovedflyt() } } private fun kjørReglerForEøsBorgere( overstyrteRegler: Map<RegelId, Svar>, resultatEOSFamilie: Resultat? ): List<Resultat> { val resultater = mutableListOf<Resultat>() if (resultatEOSFamilie?.svar == JA) { resultater.add(ReglerForOppholdstillatelse.fraDatagrunnlag(datagrunnlag).kjørHovedflyt()) } val reglerForEØSBorgerResultater = listOf( ReglerForMedl.fraDatagrunnlag(datagrunnlag).kjørHovedflyt(), ReglerForArbeidsforhold.fraDatagrunnlag(datagrunnlag, overstyrteRegler).kjørHovedflyt(), ReglerForBosatt.fraDatagrunnlag(datagrunnlag).kjørHovedflyt(), ReglerForEøsBorgere.fraDatagrunnlag(datagrunnlag).kjørHovedflyt() ) resultater.addAll(reglerForEØSBorgerResultater) return resultater } private fun kjørFellesRegler(): List<Resultat> { val fellesRegler = listOf( ReglerForDoedsfall.fraDatagrunnlag(datagrunnlag), ReglerForFellesArbeidsforhold.fraDatagrunnlag(datagrunnlag) ) return fellesRegler.map(Regler::kjørHovedflyt) } companion object { private fun utledResultat(ytelse: Ytelse, resultater: List<Resultat>): Resultat { val førsteNei = resultater.find { it.svar == NEI } if (førsteNei != null) { return lagKonklusjon(neiResultat(ytelse), resultater) } val medlemskonklusjon = resultater.find { it.erMedlemskonklusjon() } if (medlemskonklusjon != null) { return lagKonklusjon(konklusjon(ytelse, medlemskonklusjon), resultater) } if (resultater.all { it.svar == JA }) { return lagKonklusjon(jaResultat(ytelse), resultater) } return lagKonklusjon(uavklartResultat(ytelse), resultater) } private fun lagKonklusjon(konklusjon: Resultat, resultater: List<Resultat>): Resultat { return konklusjon.copy(delresultat = lagDelresultat(resultater), årsaker = resultater.finnÅrsaker()) } private fun lagDelresultat(resultater: List<Resultat>): List<Resultat> { return resultater.map { if (it.regelId == RegelId.REGEL_FLYT_KONKLUSJON || it.regelId == RegelId.REGEL_MEDLEM_KONKLUSJON && it.delresultat.isNotEmpty()) it.delresultat.first() else it } } private fun konklusjon(ytelse: Ytelse, resultat: Resultat): Resultat { return when (resultat.svar) { JA -> jaKonklusjon(ytelse).utfør().copy(harDekning = resultat.harDekning, dekning = resultat.dekning) NEI -> neiKonklusjon(ytelse).utfør().copy(harDekning = resultat.harDekning, dekning = resultat.dekning) UAVKLART -> uavklartKonklusjon(ytelse).utfør().copy(harDekning = resultat.harDekning, dekning = resultat.dekning) } } private fun uavklartResultat(ytelse: Ytelse): Resultat { return uavklartKonklusjon(ytelse).utfør() } private fun neiResultat(ytelse: Ytelse): Resultat { return neiKonklusjon(ytelse).utfør() } private fun jaResultat(ytelse: Ytelse): Resultat { return jaKonklusjon(ytelse).utfør() } } }
9
Kotlin
1
0
c58390762d85967f1a3f412abfddcbfcad99702d
8,277
medlemskap-oppslag
MIT License
jdroid-android-sample/src/main/java/com/jdroid/android/sample/ui/google/signin/GoogleSignInFragment.kt
petsnarua
258,267,623
true
{"Kotlin": 742915, "Java": 383189, "HTML": 3936, "Shell": 2559, "JavaScript": 564}
package com.jdroid.android.sample.ui.google.signin import android.content.Intent import android.os.Bundle import android.view.View import android.widget.TextView import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.common.SignInButton import com.google.android.material.snackbar.Snackbar import com.jdroid.android.fragment.AbstractFragment import com.jdroid.android.google.signin.GoogleSignInHelper import com.jdroid.android.google.signin.GoogleSignInListener import com.jdroid.android.loading.FragmentLoading import com.jdroid.android.loading.NonBlockingLoading import com.jdroid.android.sample.R class GoogleSignInFragment : AbstractFragment(), GoogleSignInListener { private lateinit var googleSignInHelper: GoogleSignInHelper private lateinit var signInButton: SignInButton private lateinit var signOutButton: View private lateinit var revokeButton: View private lateinit var status: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun getContentFragmentLayout(): Int? { return R.layout.google_sign_in_fragment } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) status = findView(R.id.status) signInButton = findView(R.id.signIn) signInButton.setSize(SignInButton.SIZE_WIDE) signInButton.setOnClickListener { googleSignInHelper.signIn() } signOutButton = findView(R.id.signOut) signOutButton.setOnClickListener { googleSignInHelper.signOut() } revokeButton = findView(R.id.revoke) revokeButton.setOnClickListener { googleSignInHelper.revokeAccess() } googleSignInHelper = object : GoogleSignInHelper(this@GoogleSignInFragment, this@GoogleSignInFragment) { override fun isRequestIdTokenEnabled(): Boolean { return true } override fun isServerAuthCodeEnabled(): Boolean { return true } } } override fun onStart() { super.onStart() googleSignInHelper.verifyLastSignedInAccount() // TODO // googleSignInHelper.silentSignIn(); } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) googleSignInHelper.onActivityResult(requestCode, resultCode, data!!) } override fun onGoogleSignIn(googleSignInAccount: GoogleSignInAccount) { val builder = StringBuilder() builder.append("Display Name: ") builder.append(googleSignInAccount.displayName) builder.append("\nEmail: ") builder.append(googleSignInAccount.email) builder.append("\nGranted Scopes: ") builder.append(googleSignInAccount.grantedScopes) builder.append("\nId: ") builder.append(googleSignInAccount.id) builder.append("\nId Token: ") builder.append(if (googleSignInAccount.idToken != null) googleSignInAccount.idToken!!.substring(0, 50) else null) builder.append("\nServer Auth Code: ") builder.append(googleSignInAccount.serverAuthCode) status.text = builder.toString() signInButton.visibility = View.GONE signOutButton.visibility = View.VISIBLE Snackbar.make(findView(R.id.container), "onGoogleSignIn", Snackbar.LENGTH_SHORT).show() } override fun onGoogleSignOut() { status.setText(R.string.notLogged) signInButton.visibility = View.VISIBLE signOutButton.visibility = View.GONE Snackbar.make(findView(R.id.container), "onGoogleSignOut", Snackbar.LENGTH_SHORT).show() } override fun onGoogleAccessRevoked() { status.setText(R.string.notLogged) signInButton.visibility = View.VISIBLE signOutButton.visibility = View.GONE Snackbar.make(findView(R.id.container), "onGoogleAccessRevoked", Snackbar.LENGTH_SHORT).show() } override fun getDefaultLoading(): FragmentLoading? { return NonBlockingLoading() } }
0
null
0
0
8b4d1654fdabe6d2e13487f8045a83b2e6e0e5fe
4,170
jdroid-android
Apache License 2.0
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrInstanceInitializerCallImpl.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.ir.expressions.impl import org.jetbrains.kotlin.ir.declarations.IrAttributeContainer import org.jetbrains.kotlin.ir.expressions.IrInstanceInitializerCall import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.types.IrType class IrInstanceInitializerCallImpl( override val startOffset: Int, override val endOffset: Int, override var classSymbol: IrClassSymbol, override var type: IrType, ) : IrInstanceInitializerCall() { override var attributeOwnerId: IrAttributeContainer = this override var originalBeforeInline: IrAttributeContainer? = null }
166
null
5771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,232
kotlin
Apache License 2.0
app/src/main/java/com/programmazionemobile/progettoLucaBenzi/MainActivity.kt
onboarding92
260,157,158
false
null
@file:Suppress("DEPRECATION") package com.programmazionemobile.progettoLucaBenzi import android.content.pm.PackageManager import android.graphics.* import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.HandlerThread import android.util.DisplayMetrics import android.util.Log import android.util.Rational import android.util.Size import android.view.Surface import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.* import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* import java.io.ByteArrayOutputStream import java.io.File import java.util.* class MainActivity : AppCompatActivity() { private var lensFacing = CameraX.LensFacing.BACK private val tag = "MainActivity" private var isProcessing: Boolean = false private var PERMISSION_REQUEST_CODE = 101 var REQUIRED_PERMISSIONS = arrayOf("android.permission.CAMERA") private var classifyActivity: ClassifyActivity = ClassifyActivity(this@MainActivity) var dbSq: DBHelper= DBHelper(this); override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (allPermissionsGranted()) { textureView.post { startCamera() } textureView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> transformationsMethod() } } else { ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, this.PERMISSION_REQUEST_CODE ) } classifyActivity .initialize() .addOnSuccessListener { } .addOnFailureListener { e -> Log.e(tag, "Errore nel settaggio del classificatore.", e) } } private fun startCamera() { val displayMetrics = DisplayMetrics().also { textureView.display.getRealMetrics(it) } val screenAspectRatio = Rational(1, 1) val screenSize = Size(displayMetrics.widthPixels, displayMetrics.heightPixels) val previewConfig = PreviewConfig.Builder().apply { setLensFacing(lensFacing) setTargetResolution(screenSize) setTargetAspectRatio(screenAspectRatio) setTargetRotation(windowManager.defaultDisplay.rotation) setTargetRotation(textureView.display.rotation) }.build() val preview = Preview(previewConfig) preview.setOnPreviewOutputUpdateListener { textureView.surfaceTexture = it.surfaceTexture transformationsMethod() } val analyzerConfiguration = ImageAnalysisConfig.Builder().apply { val analyzerThread = HandlerThread("AnalysisThread").apply { start() } setCallbackHandler(Handler(analyzerThread.looper)) setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE) }.build() val analyzer = ImageAnalysis(analyzerConfiguration) analyzer.analyzer = ImageAnalysis.Analyzer { imageProxy: ImageProxy, _: Int -> if (!isProcessing) { isProcessing = true val bitmap = imageProxy.toBitmap() this.classifyActivity .classifyAsync(bitmap) .addOnSuccessListener { result -> predictedTextView?.text = result isProcessing = false } .addOnFailureListener { isProcessing = false } } } val captureConfig = ImageCaptureConfig.Builder() .setTargetAspectRatio(screenAspectRatio) .setTargetRotation(windowManager.defaultDisplay.rotation) .setTargetResolution(screenSize) .setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY) .build() val capture = ImageCapture(captureConfig) btnDetectObject.setOnClickListener { val fileName = System.currentTimeMillis().toString() val fileFormat = ".jpg" val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) val imageFile = createTempFile(fileName, fileFormat) val date = Date() val output = File(dir, "CheckImage $date.jpeg") // Store captured image in the temporary file capture.takePicture(imageFile, object : ImageCapture.OnImageSavedListener { override fun onImageSaved(file: File) { Log.d("funziona: ",dbSq.insertData(output!!.absolutePath).toString().plus(" ")); val msg = "Photo capture succeeded: ${file.absolutePath}" Log.d("CameraXApp", msg) } override fun onError(useCaseError: ImageCapture.UseCaseError, message: String, cause: Throwable?) { val msg = "Photo capture failed: $message" Log.e("CameraXApp", msg, cause) } }) } CameraX.bindToLifecycle(this, preview, analyzer,capture) } private fun ImageProxy.toBitmap(): Bitmap { val yBuffer = planes[0].buffer // Y val uBuffer = planes[1].buffer // U val vBuffer = planes[2].buffer // V val ySize = yBuffer.remaining() val uSize = uBuffer.remaining() val vSize = vBuffer.remaining() val nv21 = ByteArray(ySize + uSize + vSize) yBuffer.get(nv21, 0, ySize) vBuffer.get(nv21, ySize, vSize) uBuffer.get(nv21, ySize + vSize, uSize) val yuvImage = YuvImage(nv21, ImageFormat.NV21, this.width, this.height, null) val arrayOutputStream = ByteArrayOutputStream() yuvImage.compressToJpeg(Rect(0, 0, yuvImage.width, yuvImage.height), 100, arrayOutputStream) val imageBytes = arrayOutputStream.toByteArray() return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) } private fun transformationsMethod() { val matrix = Matrix() val centerX = textureView.width / 2f val centerY = textureView.height / 2f val rotationDegrees = when (textureView.display.rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> return } matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY) textureView.setTransform(matrix) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == PERMISSION_REQUEST_CODE) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText(this, "Bisogna dare il permesso all'app di utilizzare la videocamera.", Toast.LENGTH_SHORT) .show() finish() } } } private fun allPermissionsGranted(): Boolean { for (permission in REQUIRED_PERMISSIONS) { if (ContextCompat.checkSelfPermission( this, permission ) != PackageManager.PERMISSION_GRANTED ) { return false } } return true } override fun onDestroy() { classifyActivity.close() super.onDestroy() } }
0
Kotlin
0
0
3e52355e03f4422fcbecacba39227ac3fc18df01
7,676
AndroidAppObjectDetection
MIT License
app/src/main/java/com/ahmed/carefer/ui/theme/Theme.kt
ahmedshaban1
571,586,573
false
null
package com.ahmed.carefer.ui.theme import android.app.Activity import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView /*private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 )*/ private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun CareferTheme( content: @Composable () -> Unit ) { val colorScheme = LightColorScheme val view = LocalView.current if (!view.isInEditMode) { SideEffect { (view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb() } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
0
Kotlin
0
0
7b119d6495e4a406908fa2566ec3bf34f1a1fb97
1,268
carefer
Apache License 2.0
urbanairship-debug/src/main/java/com/urbanairship/debug/deviceinfo/tag/groups/TagGroupFragment.kt
urbanairship
58,972,818
false
null
/* Copyright Urban Airship and Contributors */ package com.urbanairship.debug.deviceinfo.tag.groups import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.urbanairship.debug.R import com.urbanairship.debug.databinding.UaFragmentDeviceInfoTagGroupsBinding import com.urbanairship.debug.extensions.setupToolbarWithNavController class TagGroupFragment : Fragment() { private lateinit var viewModel: TagGroupViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { viewModel = ViewModelProvider(this).get(TagGroupViewModel::class.java) val binding = UaFragmentDeviceInfoTagGroupsBinding.inflate(inflater, container, false) binding.lifecycleOwner = this binding.viewModel = viewModel binding.radioGroupIdentifierType.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.channelChip -> viewModel.tagGroupType.set(TagGroupType.CHANNEL) R.id.namedUserChip -> viewModel.tagGroupType.set(TagGroupType.CONTACT) } } when (viewModel.tagGroupType.get()) { TagGroupType.CHANNEL -> binding.radioGroupIdentifierType.check(R.id.channelChip) TagGroupType.CONTACT -> binding.radioGroupIdentifierType.check(R.id.namedUserChip) else -> Unit // Do nothing } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbarWithNavController(R.id.toolbar) } }
2
null
122
111
21d49c3ffd373e3ba6b51a706a4839ab3713db11
1,765
android-library
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/leagues/opmodes/autonomous/old/blue/BlueBackstageToCenterFull.kt
AtomicRobotics3805
693,892,433
false
{"Kotlin": 244821, "Java": 56909}
package org.firstinspires.ftc.teamcode.leagues.opmodes.autonomous.old.blue import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.Disabled import org.atomicrobotics3805.cflib.Constants import org.atomicrobotics3805.cflib.driving.drivers.MecanumDrive import org.atomicrobotics3805.cflib.driving.localizers.TwoWheelOdometryLocalizer import org.atomicrobotics3805.cflib.opmodes.AutonomousOpMode import org.firstinspires.ftc.teamcode.drive.CompetitionDriveConstants import org.firstinspires.ftc.teamcode.localizers.CompetitionOdometryConstants import org.firstinspires.ftc.teamcode.mechanisms.Arm import org.firstinspires.ftc.teamcode.mechanisms.Lid import org.firstinspires.ftc.teamcode.mechanisms.DetectionMechanism import org.firstinspires.ftc.teamcode.mechanisms.Intake import org.firstinspires.ftc.teamcode.mechanisms.Lift import org.firstinspires.ftc.teamcode.leagues.routines.old.BackstageRoutines import org.firstinspires.ftc.teamcode.leagues.routines.old.SharedRoutines import org.firstinspires.ftc.teamcode.leagues.trajectoryFactory.CompetitionTrajectoryFactory @Disabled @Autonomous(name = "Blue Backstage to Center Park Two Pixels", group = "Blue Backstage", preselectTeleOp="Competition TeleOp v1 - Blue") class BlueBackstageToCenterFull: AutonomousOpMode( Constants.Color.BLUE, CompetitionTrajectoryFactory, { BackstageRoutines.backstageFullPathAndPark }, { SharedRoutines.initRoutineCenterPark }, MecanumDrive( CompetitionDriveConstants, TwoWheelOdometryLocalizer(CompetitionOdometryConstants) ) { CompetitionTrajectoryFactory.backstageStartPose }, Arm, Lid, Lift, Intake, DetectionMechanism )
0
Kotlin
0
1
a6e231e464ea8e85e33912381b40cd9f511913a1
1,716
2024-Centerstage
BSD 3-Clause Clear License
app/src/main/java/com/example/whisper/vo/addcontact/AddContactUiModel.kt
alexandermalinov
537,907,360
false
{"Kotlin": 123950}
package com.example.whisper.vo.addcontact import com.example.whisper.vo.contacts.ContactUiModel data class AddContactUiModel( val contacts: List<ContactUiModel> = emptyList(), val isLoading: Boolean = false, )
0
Kotlin
0
0
d020aa0f2d977d2ac05840ca658072b0f722cd44
220
whisper
MIT License
sketch-core/src/main/kotlin/com/github/panpf/sketch/util/SketchUtils.kt
panpf
14,798,941
false
null
/* * Copyright (C) 2022 panpf <<EMAIL>> * * 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.panpf.sketch.util import android.graphics.drawable.Drawable import android.graphics.drawable.DrawableWrapper import android.graphics.drawable.LayerDrawable import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.view.View import androidx.appcompat.graphics.drawable.DrawableWrapperCompat import com.github.panpf.sketch.Sketch import com.github.panpf.sketch.core.R import com.github.panpf.sketch.drawable.SketchCountBitmapDrawable import com.github.panpf.sketch.drawable.SketchDrawable import com.github.panpf.sketch.drawable.internal.CrossfadeDrawable import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.DisplayResult import com.github.panpf.sketch.request.internal.ViewTargetRequestManager class SketchUtils private constructor() { companion object { internal fun requestManagerOrNull(view: View): ViewTargetRequestManager? = view.getTag(R.id.sketch_request_manager) as ViewTargetRequestManager? /** * Dispose the request that's attached to this view (if there is one). */ fun dispose(view: View) = requestManagerOrNull(view)?.dispose() /** * Get the [DisplayResult] of the most recently executed image request that's attached to this view. */ fun getResult(view: View): DisplayResult? = requestManagerOrNull(view)?.getResult() /** * Restart ImageRequest */ fun restart(view: View) = requestManagerOrNull(view)?.restart() /** * Get the [DisplayRequest] of the most recently executed image request that's attached to this view. */ fun getRequest(view: View): DisplayRequest? = requestManagerOrNull(view)?.getRequest()?.let { it as DisplayRequest } /** * Get the [Sketch] of the most recently executed image request that's attached to this view. */ fun getSketch(view: View): Sketch? = requestManagerOrNull(view)?.getSketch() } } /** * Find the last [SketchDrawable] from the specified Drawable */ fun Drawable.findLeafSketchDrawable(): SketchDrawable? { val drawable = this return when { drawable is SketchDrawable -> drawable drawable is CrossfadeDrawable || drawable is LayerDrawable -> { drawable.findLeafChildDrawable()?.findLeafSketchDrawable() } drawable is DrawableWrapperCompat -> { drawable.drawable?.findLeafSketchDrawable() } VERSION.SDK_INT >= VERSION_CODES.M && drawable is DrawableWrapper -> { drawable.drawable?.findLeafSketchDrawable() } else -> null } } /** * Find the last [SketchDrawable] from the specified Drawable */ @Deprecated( message = "Please use findLeafSketchDrawable()", replaceWith = ReplaceWith(expression = "findLeafSketchDrawable()") ) fun Drawable.findLastSketchDrawable(): SketchDrawable? { return findLeafSketchDrawable() } /** * Traverse all SketchCountBitmapDrawable in specified Drawable */ fun Drawable.iterateSketchCountBitmapDrawable(block: (SketchCountBitmapDrawable) -> Unit) { val drawable = this when { drawable is SketchCountBitmapDrawable -> { block(drawable) } drawable is LayerDrawable -> { val layerCount = drawable.numberOfLayers for (index in 0 until layerCount) { drawable.getDrawable(index).iterateSketchCountBitmapDrawable(block) } } drawable is CrossfadeDrawable -> { drawable.start?.iterateSketchCountBitmapDrawable(block) drawable.end?.iterateSketchCountBitmapDrawable(block) } drawable is DrawableWrapperCompat -> { drawable.drawable?.iterateSketchCountBitmapDrawable(block) } VERSION.SDK_INT >= VERSION_CODES.M && drawable is DrawableWrapper -> { drawable.drawable?.iterateSketchCountBitmapDrawable(block) } } } fun Drawable.updateIsDisplayed(displayed: Boolean, caller: String) { this.iterateSketchCountBitmapDrawable { it.countBitmap.setIsDisplayed(displayed, caller) } }
2
null
308
1,978
82ffde1ff148311bb5b36eb70a4c82224d1f3af4
4,808
sketch
Apache License 2.0
app/src/main/java/com/google/firebase/udacity/daggerPosts/dagger/ui/main/posts/PostRecyclerAdapter.kt
mohameddawood
210,697,211
false
null
package com.google.firebase.udacity.daggerPosts.dagger.ui.main.posts import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.google.firebase.udacity.daggerPosts.R import com.google.firebase.udacity.daggerPosts.dagger.models.Post import java.util.* class PostRecyclerAdapter : RecyclerView.Adapter<ViewHolder>() { private var posts: List<Post> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { var view: View = LayoutInflater.from(parent.context).inflate( R.layout.layout_post_list_item, parent, false ) return PostViewHolder(view) } override fun getItemCount(): Int = posts.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { (holder as PostViewHolder).bind(posts[position]) } fun setPosts(posts: List<Post?>?) { this.posts = posts as List<Post> notifyDataSetChanged() } class PostViewHolder(itemView: View) : ViewHolder(itemView) { var title: TextView = itemView.findViewById(R.id.title) fun bind(post: Post) { title.text = post.title } } }
0
Kotlin
1
5
4fefc6d03e915b9b95e428fda9176e753e49cd6a
1,366
Dagger2PostsApp
Apache License 2.0
app/src/main/java/com/example/usptu_map/project_objects/coordinates/MapPoints.kt
Naillin
763,187,107
false
{"Kotlin": 44616}
package com.example.usptu_map.project_objects.coordinates import com.example.usptu_map.project_objects.base_entities.AcademicBuilding import com.example.usptu_map.project_objects.base_entities.Building import com.example.usptu_map.project_objects.base_entities.Dormitory import com.example.usptu_map.project_objects.base_entities.ParcelablePoint import com.example.usptu_map.project_objects.coordinates.PolygonsMapPoints.firstCorpusArea import com.yandex.mapkit.geometry.Point object MapPoints { //Центр карты val CENTER_USPTU_CITY_COORD: Point = Point(54.818329, 56.058558) //Границы карты от центра в пол километра val SOUTHWEST_USPTU_CITY_COORD: Point = Point(54.813824 + 0.000010, 56.050740 + 0.000010) val NORTHEAST_USPTU_CITY_COORD: Point = Point(54.822834 - 0.000010, 56.066376 - 0.000010) val DINING_ROOM :Point = Point(54.816945,56.059144) val universityBildings = listOf( //закрепить полигоны из PolygonsMapPoints Building("Жральня", "default", ParcelablePoint.fromMapKitPoint(DINING_ROOM), "dining") ) //КОРПУСА val CORPUSES = listOf( Point(54.818545, 56.058506),//1 Point(54.817290, 56.061571),//2 Point(54.817669, 56.061149),//3 Point(54.8165320, 56.0624580),//4 Point(54.820161, 56.058817),//7 Point(54.8194760, 56.0683220),//8 Point(54.8174690, 56.0588440),//11 Point(54.816022, 56.060243),//УФК1 Point(54.814870, 56.060504) //УФК2 ) val academicBuildings = listOf( //закрепить полигоны из PolygonsMapPoints AcademicBuilding("Building 1", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[0]), listOf("Department 1", "Department 2"), 0, firstCorpusArea.map { ParcelablePoint.fromMapKitPoint(it) }), AcademicBuilding("Building 2", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[1]), listOf("Department 3", "Department 4"), 0), AcademicBuilding("Building 3", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[2]), listOf("Department 5", "Department 6"), 0), AcademicBuilding("Building 4", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[3]), listOf("Department 7", "Department 8"), 0), AcademicBuilding("Building 7", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[4]), listOf("Department 9", "Department 10"), 0), AcademicBuilding("Building 8", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[5]), listOf("Department 11", "Department 12"), 0), AcademicBuilding("Building 11", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[6]), listOf("Department 13", "Department 14"), 0), AcademicBuilding("UFK 1", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[7]), listOf("Department 15", "Department 16"), 0), AcademicBuilding("UFK 2", "default", ParcelablePoint.fromMapKitPoint(CORPUSES[8]), listOf("Department 17", "Department 18"), 0) ) //ОБЩЕЖИТИЯ val UNIVERSITY_DORMITORY = listOf( Point(54.81726, 56.05812), //1 Point(54.817552, 56.059662),//2 Point(54.817002, 56.060883),//3 Point(54.816286, 56.060848),//4 Point(54.815860, 56.061125),//УЧЕБНО ЖИЛТЩНЫЙ КОМПЛЕКС Point(54.815087, 56.061719),//5 Point(54.815987, 56.062137),//6 Point(54.814532, 56.061292)//10 ) val universityDormitories = listOf( //закрепить полигоны из PolygonsMapPoints Dormitory("Dormitory 1", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[0]), 0), Dormitory("Dormitory 2", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[1]), 0), Dormitory("Dormitory 3", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[2]), 0), Dormitory("Dormitory 4", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[3]), 0), Dormitory("Educational and Housing Complex", "default", ParcelablePoint.fromMapKitPoint( UNIVERSITY_DORMITORY[4]), 0), Dormitory("Dormitory 5", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[5]), 0), Dormitory("Dormitory 6", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[6]), 0), Dormitory("Dormitory 10", "default", ParcelablePoint.fromMapKitPoint(UNIVERSITY_DORMITORY[7]), 0) ) val combinedBuildingList = listOf( universityBildings, academicBuildings, universityDormitories ).flatten() //Объединит все выбранные элементы в один список }
0
Kotlin
0
0
fc5320d053823c8a2e38f5851f4cd841168ba5df
4,447
USPTU_Map
MIT License
underwave/src/commonMain/kotlin/com/aallam/underwave/log/Logger.kt
Aallam
229,120,653
false
null
package com.aallam.underwave.log /** * May be used to create a custom logging solution to override the [Default] behaviour. */ expect interface Logger { /** * Pass the log details off to the [Logger] implementation. * * @param priority the priority/type of this log message * @param tag used to identify the source of a log message. * @param message the message to be logged. */ fun log(priority: Int, tag: String, message: String) /** * Default implementation of [Logger]. */ object Default : Logger }
0
Kotlin
0
0
0403c4c9cfdfc07a0de9e8e079c5cff00a15e421
564
Underwave
Apache License 2.0
src/main/kotlin/org/move/ide/refactoring/MvRenameProcessor.kt
pontem-network
279,299,159
false
null
package org.move.ide.refactoring import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenamePsiElementProcessor import com.intellij.usageView.UsageInfo import org.move.lang.core.psi.* import org.move.lang.core.psi.ext.descendantOfTypeStrict import org.move.lang.core.psi.ext.equalsTo import org.move.lang.core.psi.ext.isShorthand import org.move.lang.core.psi.ext.owner class MvRenameProcessor : RenamePsiElementProcessor() { override fun canProcessElement(element: PsiElement): Boolean = element is MvNamedElement override fun renameElement( element: PsiElement, newName: String, usages: Array<out UsageInfo>, listener: RefactoringElementListener? ) { val psiFactory = element.project.psiFactory when (element) { is MvModule -> { // if only module in file and file has the same name -> rename file val file = element.containingMoveFile if (file != null) { val filename = FileUtil.getNameWithoutExtension(file.name) if (filename == element.name && file.modules().singleOrNull()?.equalsTo(element) == true ) { file.name = "$newName.move" } } } is MvStructField -> { usages.forEach { val usage = it.element when { usage is MvStructLitField && usage.isShorthand -> { // NEW_FIELD_NAME: OLD_VARIABLE_NAME val newLitField = psiFactory.structLitField(newName, usage.referenceName) usage.replace(newLitField) } usage is MvStructPatField && usage.isShorthand -> { // NEW_PAT_FIELD_NAME: OLD_VARIABLE_NAME val newPatField = psiFactory.structPatField(newName, usage.referenceName) usage.replace(newPatField) } } } } is MvBindingPat -> { val owner = element.owner usages.forEach { when (owner) { is MvLetStmt -> { val field = it.element?.maybeLitFieldParent // OLD_FIELD_NAME: NEW_VARIABLE_NAME when { field is MvStructLitField && field.isShorthand -> { val newField = psiFactory.structLitField(field.referenceName, newName) field.replace(newField) } field is MvSchemaLitField && field.isShorthand -> { val newField = psiFactory.schemaLitField(field.referenceName, newName) field.replace(newField) } } } is MvSchemaFieldStmt -> { // NEW_SCHEMA_FIELD_NAME: OLD_VARIABLE_NAME val schemaLitField = it.element as? MvSchemaLitField ?: return@forEach val newSchemaLitField = psiFactory.schemaLitField(newName, schemaLitField.referenceName) schemaLitField.replace(newSchemaLitField) } } } } } val elementToRename = when { element is MvBindingPat && element.parent is MvStructPatField -> { val newField = psiFactory.structPatField(element.identifier.text, element.text) val newFieldInTree = element.parent.replace(newField) newFieldInTree.descendantOfTypeStrict<MvBindingPat>()!! } else -> element } super.renameElement(elementToRename, newName, usages, listener) } val PsiElement.maybeLitFieldParent get() = PsiTreeUtil.findFirstParent(this) { it is MvStructLitField || it is MvSchemaLitField } }
4
null
7
69
c0192da133a0d0b0cb22456f55d3ee8c7a973109
4,585
intellij-move
MIT License
app/src/main/java/com/example/instasocialwsapp/Post.kt
melisgb
274,247,024
false
null
package com.example.instasocialwsapp class Post { var postID : String? = null var postContent : String? = null var postImageUrl : String? = null var dateCreated : String? = null var postUserId : String? = null var postPersonName : String? = null var postProfImage : String? = null constructor(postID : String, postContent : String, postImageUrl : String, dateCreated: String, postUserId : String?, postPersonName : String, postProfImage: String){ this.postID = postID this.postContent = postContent this.postImageUrl = postImageUrl this.dateCreated = dateCreated this.postUserId = postUserId this.postPersonName = postPersonName this.postProfImage = postProfImage } }
0
Kotlin
0
0
1d291b334857938ae802be4919bb9e80a80dcecb
779
InstaSocialWSApp
MIT License
common/src/main/java/ca/bc/gov/common/model/config/DataSetFeatureFlag.kt
bcgov
414,797,174
false
{"Kotlin": 1316203, "Java": 582146}
package ca.bc.gov.common.model.config /** * @author pinakin.kansara * Created 2023-12-05 at 10:18 a.m. */ sealed class DataSetFeatureFlag(private val flags: Set<String>) { fun isClinicalDocumentEnabled(): Boolean = flags.contains("clinicalDocument") fun isCovid19TestResultEnabled(): Boolean = flags.contains("covid19TestResult") fun isDiagnosticImagingEnabled(): Boolean = flags.contains("diagnosticImaging") fun isHealthVisitEnabled(): Boolean = flags.contains("healthVisit") fun isHospitalVisitEnabled(): Boolean = flags.contains("hospitalVisit") fun isImmunizationEnabled(): Boolean = flags.contains("immunization") fun isLabResultEnabled(): Boolean = flags.contains("labResult") fun isMedicationEnabled(): Boolean = flags.contains("medication") fun isNoteEnabled(): Boolean = flags.contains("note") fun isSpecialAuthorityRequestEnabled(): Boolean = flags.contains("specialAuthorityRequest") fun isBcCancerScreeningEnabled(): Boolean = flags.contains("bcCancerScreening") } data class PatientDataSetFeatureFLag(private val flags: Set<String>) : DataSetFeatureFlag(flags) data class DependentDataSetFeatureFLag(private val flags: Set<String>) : DataSetFeatureFlag(flags)
7
Kotlin
5
5
d91c6c5a237d42ecf429ba66d01efb405f91666c
1,224
myhealthBC-android
Apache License 2.0
nanokt-android/src/main/java/com/conena/nanokt/android/os/MessageUtils.kt
conena
592,106,905
false
{"Kotlin": 415799}
/* * Copyright (C) 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. * */ @file:JvmName(name = "MessageUtils") @file:Suppress("NOTHING_TO_INLINE", "unused") package com.conena.nanokt.android.os import android.os.Message import android.os.Messenger import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Chainable setter for [Message.replyTo]. */ inline fun Message.setReplyTo(replyTo: Messenger?): Message { this.replyTo = replyTo return this } /** * Chainable setter for [Message.what]. */ inline fun Message.setWhat(what: Int): Message { this.what = what return this } /** * Chainable setter for [Message.arg1]. */ inline fun Message.setArg1(arg1: Int): Message { this.arg1 = arg1 return this } /** * Chainable setter for [Message.arg2]. */ inline fun Message.setArg2(arg2: Int): Message { this.arg2 = arg2 return this } /** * Invokes [block] with the receiver as argument, returns the result and calls [Message.recycle] * even when an exception is thrown. Exceptions are passed through. * @return The result of [block]. */ inline fun <R> Message.use(block: (Message) -> R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } try { return block(this) } finally { recycle() } }
1
Kotlin
1
77
0f3315d5a2d9ba602f6a4ea9757d859bdb040a29
1,835
nanokt
Apache License 2.0
src/main/kotlin/org/jetbrains/fortran/lang/resolve/FortranUnitReferenceImpl.kt
sharkovadarya
124,751,449
false
{"Gradle": 1, "Gradle Kotlin DSL": 1, "INI": 1, "Shell": 1, "Text": 32, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 169, "Fortran Free Form": 110, "Fortran": 11, "Java": 12, "XML": 2, "HTML": 18, "JFlex": 1}
package org.jetbrains.fortran.lang.resolve import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.FortranProgramUnit import org.jetbrains.fortran.lang.psi.ext.FortranNamedElement import org.jetbrains.fortran.lang.psi.impl.FortranLabelDeclImpl import org.jetbrains.fortran.lang.psi.impl.FortranUnitDeclImpl import org.jetbrains.fortran.lang.psi.mixin.FortranUnitImplMixin class FortranUnitReferenceImpl(element: FortranUnitImplMixin) : FortranReferenceBase<FortranUnitImplMixin>(element), FortranReference { override val FortranUnitImplMixin.referenceAnchor: PsiElement get() = integerliteral override fun getVariants(): Array<Any> = emptyArray() override fun resolveInner(): List<FortranNamedElement> { val programUnit = PsiTreeUtil.getParentOfType(element, FortranProgramUnit::class.java) ?: return emptyList() return PsiTreeUtil.findChildrenOfType(programUnit, FortranUnitDeclImpl::class.java) .filter { element.getUnitValue() == it.getUnitValue() } .toMutableList() } }
1
null
1
1
cffd11994cf571bcd2c54b1d0c960e405c3c66f3
1,108
fortran-plugin
Apache License 2.0
plugin/src/main/kotlin/me/dkim19375/bedwars/plugin/listener/PlayerDropItemListener.kt
UntouchedOdin0
369,201,206
true
{"Kotlin": 274143}
/* * MIT License * * Copyright (c) 2021 dkim19375 * * 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 me.dkim19375.bedwars.plugin.listener import me.dkim19375.bedwars.plugin.BedwarsPlugin import me.dkim19375.bedwars.plugin.util.isArmor import me.dkim19375.bedwars.plugin.util.isTool import me.dkim19375.bedwars.plugin.util.isWeapon import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerDropItemEvent class PlayerDropItemListener(private val plugin: BedwarsPlugin) : Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) private fun PlayerDropItemEvent.onDrop() { if (plugin.gameManager.getGame(player) == null) { return } val type = itemDrop.itemStack.type if (type.isArmor() || type.isTool() || type.isWeapon()) { isCancelled = true } } }
0
null
0
0
541da69bc8163d43851c087ce505aede7cfebe9e
1,976
Bedwars
MIT License
app/src/androidTest/java/io/libredrop/android/testutils/ElapsedTimeIdlingResource.kt
libredrop
156,920,250
false
null
package io.libredrop.android.testutils import androidx.test.espresso.IdlingResource import androidx.test.espresso.IdlingResource.ResourceCallback class ElapsedTimeIdlingResource(private val waitingTime: Long) : IdlingResource { private val startTime: Long = System.currentTimeMillis() private lateinit var resourceCallback: ResourceCallback override fun getName(): String { return ElapsedTimeIdlingResource::class.java.name + ":" + waitingTime } override fun isIdleNow(): Boolean { val elapsed = System.currentTimeMillis() - startTime val idle = elapsed >= waitingTime if (idle) { resourceCallback.onTransitionToIdle() } return idle } override fun registerIdleTransitionCallback(resourceCallback: ResourceCallback) { this.resourceCallback = resourceCallback } }
0
Kotlin
1
0
5d3ad24cbce02e4ec98f971f6961a2a59f1f563c
867
libredrop-android
MIT License
libraries/core/src/androidTest/kotlin/com/bumble/appyx/core/plugin/BackPressHandlerTest.kt
bumble-tech
493,334,393
false
null
package com.bumble.appyx.core.plugin import android.os.Parcelable import androidx.activity.OnBackPressedCallback import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.State import androidx.test.espresso.Espresso import androidx.test.platform.app.InstrumentationRegistry import com.bumble.appyx.Appyx import com.bumble.appyx.core.AppyxTestScenario import com.bumble.appyx.core.InternalAppyxTestActivity import com.bumble.appyx.core.children.nodeOrNull import com.bumble.appyx.core.composable.Children import com.bumble.appyx.core.modality.BuildContext import com.bumble.appyx.core.node.ParentNode import com.bumble.appyx.core.node.node import com.bumble.appyx.navmodel.backstack.BackStack import com.bumble.appyx.navmodel.backstack.activeElement import com.bumble.appyx.navmodel.backstack.operation.push import kotlinx.parcelize.Parcelize import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.instanceOf import org.junit.After import org.junit.Rule import org.junit.Test class BackPressHandlerTest { private var backHandler = TestPlugin() private var childBackHandler = TestPlugin() @get:Rule val rule = AppyxTestScenario { buildContext -> TestParentNode( buildContext = buildContext, plugin = backHandler, childPlugin = childBackHandler, ) } @After fun after() { Appyx.exceptionHandler = null InternalAppyxTestActivity.reset() } @Test fun navigation_handles_back_press_when_plugin_has_disabled_listener() { rule.start() pushChildB() disablePlugin() Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(rule.node.backStack.activeElement, equalTo(TestParentNode.NavTarget.ChildA)) assertThat(backHandler.onBackPressedHandled, equalTo(false)) } @Test fun custom_plugin_handles_back_press_before_navigation() { rule.start() pushChildB() Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(rule.node.backStack.activeElement, equalTo(TestParentNode.NavTarget.ChildB)) assertThat(backHandler.onBackPressedHandled, equalTo(true)) } @Test fun activity_is_closed_when_nobody_can_handle_back_press() { rule.start() disablePlugin() Espresso.pressBackUnconditionally() Espresso.onIdle() rule.waitForIdle() assertThat(rule.activityScenario.state, equalTo(State.DESTROYED)) } @Test fun reports_incorrect_handler() { var exception: Exception? = null Appyx.exceptionHandler = { exception = it } backHandler = object : TestPlugin() { override val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { } } override val onBackPressedCallbackList: List<OnBackPressedCallback> = listOf( onBackPressedCallback, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { } } ) } rule.start() Espresso.onIdle() rule.waitForIdle() assertThat(exception, instanceOf(IllegalStateException::class.java)) } @Test fun child_back_handler_works_before_parent() { rule.start() runOnMainSync { rule.node.backStack.push(TestParentNode.NavTarget.ChildWithPlugin) } Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(childBackHandler.onBackPressedHandled, equalTo(true)) } @Test fun appyx_handles_back_press_before_activity_handler() { InternalAppyxTestActivity.handleBackPress.value = true rule.start() pushChildB() Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(backHandler.onBackPressedHandled, equalTo(true)) } @Test fun activity_handles_back_press_if_appyx_cant() { InternalAppyxTestActivity.handleBackPress.value = true rule.start() disablePlugin() Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(InternalAppyxTestActivity.onBackPressedHandled, equalTo(true)) } @Test // real case for https://github.com/bumble-tech/appyx/issues/118 fun appyx_handles_back_press_after_activity_returns_from_background() { fun TestParentNode.findChildNode() = children.value.values.firstNotNullOf { value -> value.nodeOrNull?.takeIf { value.key.navTarget == TestParentNode.NavTarget.ChildWithPlugin } } as TestParentNode rule.start() runOnMainSync { rule.node.run { backStack.push(TestParentNode.NavTarget.ChildWithPlugin) val node = findChildNode() node.backStack.push(TestParentNode.NavTarget.ChildB) } } rule.activityScenario.moveToState(Lifecycle.State.CREATED) rule.waitForIdle() rule.activityScenario.moveToState(Lifecycle.State.RESUMED) rule.waitForIdle() Espresso.pressBack() Espresso.onIdle() rule.waitForIdle() assertThat(childBackHandler.onBackPressedHandled, equalTo(true)) } private fun runOnMainSync(runner: Runnable) { InstrumentationRegistry.getInstrumentation().runOnMainSync(runner) } private fun pushChildB() { runOnMainSync { rule.node.backStack.push(TestParentNode.NavTarget.ChildB) } } private fun disablePlugin() { backHandler.onBackPressedCallback.isEnabled = false } class TestParentNode( buildContext: BuildContext, val backStack: BackStack<NavTarget> = BackStack( initialElement = NavTarget.ChildA, savedStateMap = null, ), plugin: Plugin?, private val childPlugin: Plugin?, ) : ParentNode<TestParentNode.NavTarget>( buildContext = buildContext, navModel = backStack, plugins = listOfNotNull(plugin), ) { sealed class NavTarget : Parcelable { @Parcelize object ChildA : NavTarget() @Parcelize object ChildB : NavTarget() @Parcelize object ChildWithPlugin : NavTarget() } override fun resolve(navTarget: NavTarget, buildContext: BuildContext) = when (navTarget) { NavTarget.ChildA -> node(buildContext) { Spacer( modifier = Modifier .fillMaxSize() .background(Color.Green) ) } NavTarget.ChildB -> node(buildContext) { Spacer( modifier = Modifier .fillMaxSize() .background(Color.Red) ) } NavTarget.ChildWithPlugin -> TestParentNode( buildContext = buildContext, plugin = childPlugin, childPlugin = null, ) } @Composable override fun View(modifier: Modifier) { Column(modifier) { Spacer( modifier = Modifier .fillMaxWidth() .background(Color.Black) .height(26.dp) ) Spacer( modifier = Modifier .fillMaxWidth() .height(10.dp) ) Children(navModel = backStack, modifier = Modifier.fillMaxSize()) } } } private open class TestPlugin : BackPressHandler { var onBackPressedHandled = false private set override val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { onBackPressedHandled = true } } } }
68
Kotlin
45
754
1c13ab49fb3e2eb0bcd192332d597f8c05d3f6a9
8,755
appyx
Apache License 2.0
src/test/kotlin/no/nav/helse/flex/service/SaksbehandlingsServiceTest.kt
navikt
451,810,928
false
{"Kotlin": 339483, "Dockerfile": 267}
package no.nav.helse.flex.service import com.fasterxml.jackson.module.kotlin.readValue import no.nav.helse.flex.FellesTestoppsett import no.nav.helse.flex.any import no.nav.helse.flex.arkivering.Arkivaren import no.nav.helse.flex.domain.dto.Sykepengesoknad import no.nav.helse.flex.objectMapper import no.nav.helse.flex.repository.InnsendingDbRecord import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.SpyBean import org.springframework.test.annotation.DirtiesContext import java.time.Instant import java.time.LocalDateTime import java.util.concurrent.TimeUnit @DirtiesContext class SaksbehandlingsServiceTest : FellesTestoppsett() { @SpyBean lateinit var arkivaren: Arkivaren @Autowired lateinit var saksbehandlingsService: SaksbehandlingsService @Test fun behandlerSoknaderSomEttersendesTilNavDerDetManglerOppgave() { val now = LocalDateTime.now() val sykepengesoknadUtenOppgave = objectMapper.readValue(this::class.java.getResource("/soknadArbeidstakerMedNeisvar.json"), Sykepengesoknad::class.java) .copy(sendtNav = null, sendtArbeidsgiver = now) val sykepengesoknadEttersendingTilNAV = objectMapper.readValue(this::class.java.getResource("/soknadArbeidstakerMedNeisvar.json"), Sykepengesoknad::class.java) .copy(sendtNav = now, sendtArbeidsgiver = now) val oppgaveRequestFør = oppgaveMockWebserver.requestCount saksbehandlingsService.behandleSoknad(sykepengesoknadUtenOppgave) verify(arkivaren, times(1)).opprettJournalpost(any()) assertThat(oppgaveMockWebserver.requestCount).isEqualTo(oppgaveRequestFør) saksbehandlingsService.behandleSoknad(sykepengesoknadEttersendingTilNAV) saksbehandlingsService.opprettOppgave(sykepengesoknadEttersendingTilNAV, innsending(sykepengesoknadEttersendingTilNAV)) verify(arkivaren, times(1)).opprettJournalpost(any()) val oppgaveRequest = oppgaveMockWebserver.takeRequest(5, TimeUnit.SECONDS)!! assertThat(oppgaveRequest.requestLine).isEqualTo("POST /api/v1/oppgaver HTTP/1.1") } @Test fun `oppretter oppgave med korrekte felter`() { val søknad = objectMapper.readValue(this::class.java.getResource("/soknadArbeidstakerMedNeisvar.json"), Sykepengesoknad::class.java) saksbehandlingsService.opprettOppgave(søknad, innsending(søknad)) val oppgaveRequest = oppgaveMockWebserver.takeRequest(5, TimeUnit.SECONDS)!! assertThat(oppgaveRequest.requestLine).isEqualTo("POST /api/v1/oppgaver HTTP/1.1") val oppgaveRequestBody = objectMapper.readValue<OppgaveRequest>(oppgaveRequest.body.readUtf8()) assertThat(oppgaveRequestBody.journalpostId).isEqualTo("journalpostId") assertThat(oppgaveRequestBody.beskrivelse).isEqualTo( """ Søknad om sykepenger for perioden 16.10.2018 til 24.10.2018 Arbeidsgiver: ARBEIDSGIVER A/S Organisasjonsnummer: 1257358 Periode 1: 16.10.2018 - 20.10.2018 Grad: 100 Periode 2: 21.10.2018 - 24.10.2018 Grad: 40 Betaler arbeidsgiveren lønnen din når du er syk? Vet ikke """.trimIndent(), ) assertThat(oppgaveRequestBody.tema).isEqualTo("SYK") assertThat(oppgaveRequestBody.oppgavetype).isEqualTo("SOK") assertThat(oppgaveRequestBody.prioritet).isEqualTo("NORM") assertThat(oppgaveRequestBody.behandlingstema).isEqualTo("ab0061") } private fun innsending(sykepengesoknadUtenOppgave: Sykepengesoknad): InnsendingDbRecord { return InnsendingDbRecord( id = "innsending-guid", sykepengesoknadId = sykepengesoknadUtenOppgave.id, journalpostId = "journalpostId", oppgaveId = null, behandlet = Instant.now(), ) } }
4
Kotlin
0
0
d2f70c0245adee2534e2d9497d3ffbd41894a1bf
4,116
sykepengesoknad-arkivering-oppgave
MIT License
ksp-di/kmmsharedmodule/src/commonMain/kotlin/com/azharkova/kmmdi/shared/base/IView.kt
anioutkazharkova
388,542,263
false
null
package com.azharkova.kmmdi.shared.base interface IView : com.azharkova.kmmdi.shared.base.IInputView interface IInputView
0
Objective-C
0
8
e211991b9f3fdcae5528d2389ac580df751d46b9
124
ksp-di-playground
Apache License 2.0
core/src/main/kotlin/io/github/serpro69/kfaker/exception/RetryLimitException.kt
serpro69
174,969,439
false
null
package io.github.serpro69.kfaker.exception @Suppress("unused") class RetryLimitException : Exception { constructor(message: String) : super(message) constructor(message: String, throwable: Throwable) : super(message, throwable) constructor(throwable: Throwable) : super(throwable) }
21
null
42
462
22b0f971c9f699045b30d913c6cbca02060ed9b3
300
kotlin-faker
MIT License
lib_net/src/main/java/com/caixin/android/net/callback/ResultCallbackBitmap.kt
Enowr
270,223,076
false
null
package com.caixin.android.net.callback import android.graphics.Bitmap import android.graphics.BitmapFactory import com.caixin.android.net.NetManager import okhttp3.Call import okhttp3.Response // 图片结果回调 abstract class ResultCallbackBitmap : ResultCallback() { override fun start() {} override fun response(call: Call, response: Response) { val responseBody = response.body if (responseBody == null) { responseBodyGetNull(call, response) return } try { val inputStream = responseBody.byteStream() val bitmap = BitmapFactory.decodeStream(inputStream) NetManager.mainHandler.post { if (bitmap == null) { otherException( call, response, IllegalArgumentException("BitmapFactory.decodeStream() function get null") ) } else { finish(bitmap) } } } catch (e: Exception) { NetManager.mainHandler.post { otherException(call, response, e) } } } override fun otherException(call: Call, response: Response, e: Exception) { failure(call, e) } override fun responseBodyGetNull(call: Call, response: Response) {} abstract fun finish(bitmap: Bitmap) override fun downloadProgress(url: String, total: Long, current: Long) { NetManager.mainHandler.post { downloadProgressOnMainThread(url, total, current) } } override fun uploadProgress(fileName: String, total: Long, current: Long) {} override fun uploadProgressOnMainThread(fileName: String, total: Long, current: Long) {} }
0
Kotlin
0
0
45cc0234f28f5c2420f6b3abdf2e1226e9e72cb3
1,758
AndroidHelperOld
Apache License 2.0
sample/src/main/java/com/kizitonwose/calendar/sample/compose/Example9Page.kt
kizitonwose
182,417,603
false
{"Kotlin": 670112, "HTML": 343, "CSS": 102}
package com.kizitonwose.calendar.sample.compose import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Checkbox import androidx.compose.material.CheckboxDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import com.kizitonwose.calendar.compose.CalendarState import com.kizitonwose.calendar.compose.HorizontalCalendar import com.kizitonwose.calendar.compose.WeekCalendar import com.kizitonwose.calendar.compose.rememberCalendarState import com.kizitonwose.calendar.compose.weekcalendar.WeekCalendarState import com.kizitonwose.calendar.compose.weekcalendar.rememberWeekCalendarState import com.kizitonwose.calendar.core.DayPosition import com.kizitonwose.calendar.core.WeekDayPosition import com.kizitonwose.calendar.core.atStartOfMonth import com.kizitonwose.calendar.core.daysOfWeek import com.kizitonwose.calendar.core.nextMonth import com.kizitonwose.calendar.core.previousMonth import com.kizitonwose.calendar.core.yearMonth import com.kizitonwose.calendar.sample.R import com.kizitonwose.calendar.sample.compose.Example9PageSharedComponents.CalendarHeader import com.kizitonwose.calendar.sample.compose.Example9PageSharedComponents.Day import com.kizitonwose.calendar.sample.compose.Example9PageSharedComponents.MonthAndWeekCalendarTitle import com.kizitonwose.calendar.sample.compose.Example9PageSharedComponents.WeekModeToggle import com.kizitonwose.calendar.sample.shared.displayText import kotlinx.coroutines.launch import java.time.DayOfWeek import java.time.LocalDate import java.time.YearMonth /** * Go to [Example9PageAnimatedVisibility] to see how toggling between week and * month modes can be done using [AnimatedVisibility] if that interests you. */ @Composable fun Example9Page(adjacentMonths: Long = 500) { val currentDate = remember { LocalDate.now() } val currentMonth = remember(currentDate) { currentDate.yearMonth } val startMonth = remember(currentDate) { currentMonth.minusMonths(adjacentMonths) } val endMonth = remember(currentDate) { currentMonth.plusMonths(adjacentMonths) } val selections = remember { mutableStateListOf<LocalDate>() } val daysOfWeek = remember { daysOfWeek() } var isWeekMode by remember { mutableStateOf(false) } val coroutineScope = rememberCoroutineScope() Column( modifier = Modifier .fillMaxSize() .background(Color.White), ) { val monthState = rememberCalendarState( startMonth = startMonth, endMonth = endMonth, firstVisibleMonth = currentMonth, firstDayOfWeek = daysOfWeek.first(), ) val weekState = rememberWeekCalendarState( startDate = startMonth.atStartOfMonth(), endDate = endMonth.atEndOfMonth(), firstVisibleWeekDate = currentDate, firstDayOfWeek = daysOfWeek.first(), ) CalendarTitle( isWeekMode = isWeekMode, monthState = monthState, weekState = weekState, ) CalendarHeader(daysOfWeek = daysOfWeek) val monthCalendarAlpha by animateFloatAsState(if (isWeekMode) 0f else 1f) val weekCalendarAlpha by animateFloatAsState(if (isWeekMode) 1f else 0f) var weekCalendarSize by remember { mutableStateOf(DpSize.Zero) } val visibleMonth = rememberFirstVisibleMonthAfterScroll(monthState) val weeksInVisibleMonth = visibleMonth.weekDays.count() val monthCalendarHeight by animateDpAsState( if (isWeekMode) { weekCalendarSize.height } else { weekCalendarSize.height * weeksInVisibleMonth }, tween(durationMillis = 250), ) val density = LocalDensity.current Box { HorizontalCalendar( modifier = Modifier .height(monthCalendarHeight) .alpha(monthCalendarAlpha) .zIndex(if (isWeekMode) 0f else 1f), state = monthState, dayContent = { day -> val isSelectable = day.position == DayPosition.MonthDate Day( day.date, isSelected = isSelectable && selections.contains(day.date), isSelectable = isSelectable, ) { clicked -> if (selections.contains(clicked)) { selections.remove(clicked) } else { selections.add(clicked) } } }, ) WeekCalendar( modifier = Modifier .wrapContentHeight() .onSizeChanged { val size = density.run { DpSize(it.width.toDp(), it.height.toDp()) } if (weekCalendarSize != size) { weekCalendarSize = size } } .alpha(weekCalendarAlpha) .zIndex(if (isWeekMode) 1f else 0f), state = weekState, dayContent = { day -> val isSelectable = day.position == WeekDayPosition.RangeDate Day( day.date, isSelected = isSelectable && selections.contains(day.date), isSelectable = isSelectable, ) { clicked -> if (selections.contains(clicked)) { selections.remove(clicked) } else { selections.add(clicked) } } }, ) } Spacer(modifier = Modifier.weight(1f)) WeekModeToggle( modifier = Modifier.align(Alignment.CenterHorizontally), isWeekMode = isWeekMode, ) { weekMode -> coroutineScope.launch { if (weekMode) { val targetDate = monthState.firstVisibleMonth.weekDays.last().last().date weekState.scrollToWeek(targetDate) weekState.animateScrollToWeek(targetDate) // Trigger a layout pass for title update } else { val targetMonth = weekState.firstVisibleWeek.days.first().date.yearMonth monthState.scrollToMonth(targetMonth) monthState.animateScrollToMonth(targetMonth) // Trigger a layout pass for title update } isWeekMode = weekMode } } } } @Composable private fun CalendarTitle( isWeekMode: Boolean, monthState: CalendarState, weekState: WeekCalendarState, ) { val visibleMonth = rememberFirstVisibleMonthAfterScroll(monthState) val visibleWeek = rememberFirstVisibleWeekAfterScroll(weekState) MonthAndWeekCalendarTitle( isWeekMode = isWeekMode, currentMonth = if (isWeekMode) visibleWeek.days.first().date.yearMonth else visibleMonth.yearMonth, monthState = monthState, weekState = weekState, ) } object Example9PageSharedComponents { @Composable fun MonthAndWeekCalendarTitle( isWeekMode: Boolean, currentMonth: YearMonth, monthState: CalendarState, weekState: WeekCalendarState, ) { val coroutineScope = rememberCoroutineScope() SimpleCalendarTitle( modifier = Modifier.padding(vertical = 10.dp, horizontal = 8.dp), currentMonth = currentMonth, goToPrevious = { coroutineScope.launch { if (isWeekMode) { val targetDate = weekState.firstVisibleWeek.days.first().date.minusDays(1) weekState.animateScrollToWeek(targetDate) } else { val targetMonth = monthState.firstVisibleMonth.yearMonth.previousMonth monthState.animateScrollToMonth(targetMonth) } } }, goToNext = { coroutineScope.launch { if (isWeekMode) { val targetDate = weekState.firstVisibleWeek.days.last().date.plusDays(1) weekState.animateScrollToWeek(targetDate) } else { val targetMonth = monthState.firstVisibleMonth.yearMonth.nextMonth monthState.animateScrollToMonth(targetMonth) } } }, ) } @Composable fun CalendarHeader(daysOfWeek: List<DayOfWeek>) { Row( modifier = Modifier .fillMaxWidth(), ) { for (dayOfWeek in daysOfWeek) { Text( modifier = Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 15.sp, text = dayOfWeek.displayText(), fontWeight = FontWeight.Medium, ) } } } @Composable fun Day( day: LocalDate, isSelected: Boolean, isSelectable: Boolean, onClick: (LocalDate) -> Unit, ) { Box( modifier = Modifier .aspectRatio(1f) // This is important for square-sizing! .padding(6.dp) .clip(CircleShape) .background(color = if (isSelected) colorResource(R.color.example_1_selection_color) else Color.Transparent) .clickable( enabled = isSelectable, showRipple = !isSelected, onClick = { onClick(day) }, ), contentAlignment = Alignment.Center, ) { val textColor = when { isSelected -> Color.White isSelectable -> Color.Unspecified else -> colorResource(R.color.inactive_text_color) } Text( text = day.dayOfMonth.toString(), color = textColor, fontSize = 14.sp, ) } } @Composable fun WeekModeToggle( modifier: Modifier, isWeekMode: Boolean, weekModeToggled: (isWeekMode: Boolean) -> Unit, ) { // We want the entire content to be clickable, not just the checkbox. Row( modifier = modifier .padding(10.dp) .clip(MaterialTheme.shapes.small) .clickable { weekModeToggled(!isWeekMode) } .padding(10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), ) { Checkbox( checked = isWeekMode, onCheckedChange = null, // Check is handled by parent. colors = CheckboxDefaults.colors(checkedColor = colorResource(R.color.example_1_selection_color)), ) Text(text = stringResource(R.string.week_mode)) } } } @Preview @Composable private fun Example9Preview() { Example9Page() }
13
Kotlin
505
4,651
36de800a6c36a8f142f6432a0992e0ea4ae8a789
13,216
Calendar
MIT License
server/src/test/kotlin/main/GenerateDbMigration.kt
maxtuzz
225,085,025
false
{"TypeScript": 118399, "Kotlin": 59202, "HTML": 1815, "CSS": 358, "Dockerfile": 207}
package main import io.ebean.annotation.Platform import io.ebean.dbmigration.DbMigration /** * Run this to generate migration sql based on changes to domain models */ fun main() { val dbMigration = DbMigration.create() dbMigration.setPlatform(Platform.POSTGRES) dbMigration.setPathToResources("server/src/main/resources") dbMigration.generateMigration() }
22
TypeScript
0
2
60da9d67452bf040d8659a7e4cfb6e237602dc5b
369
tuzhub
Apache License 2.0
archroid-compiler/src/main/java/app/junhyounglee/archroid/compiler/codegen/SourceFileGenerator.kt
cutehackers
194,770,993
false
null
package app.junhyounglee.archroid.compiler.codegen import app.junhyounglee.archroid.compiler.ArchroidProcessor import app.junhyounglee.archroid.compiler.error import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec import java.io.File import java.io.IOException import javax.annotation.processing.ProcessingEnvironment abstract class SourceFileGenerator<ARGS : ClassArgument>(private val processingEnv: ProcessingEnvironment) { @Throws(IOException::class) fun generate(argument: ARGS) { /* * for custom class path can be set like this. * val file = File(folder, argument.getFileName()) * FileSpec.get(argument.className.packageName, klass).writeTo(file) */ val klass = onGenerate(argument) //val filer = processingEnv.filer //FileSpec.get(argument.className.packageName, klass).writeTo(filer) try { val kaptKotlinGeneratedDir = processingEnv.options[ArchroidProcessor.OPTION_KAPT_KOTLIN_GENERATED] if (kaptKotlinGeneratedDir == null) { processingEnv.error("Can't find the target directory for generated Kotlin files.") return } val dirs = File(kaptKotlinGeneratedDir).apply { mkdirs() } FileSpec.get(argument.className.packageName, klass).writeTo(dirs) } catch (e: IOException) { e.printStackTrace() } } abstract fun onGenerate(argument: ARGS): TypeSpec companion object { const val DOCUMENTATION = "Auto generated class from Archroid" internal const val CORE_PACKAGE = "app.junhyounglee.archroid.runtime.core" internal const val VIEW_PACKAGE = "$CORE_PACKAGE.view" internal const val VIEW_CLASS = "RootViewImpl" internal const val ROOT_VIEW_PACKAGE = "android.view" internal const val ROOT_VIEW_CLASS = "ViewGroup" internal const val PRESENTER_PACKAGE = "$CORE_PACKAGE.presenter" internal const val PRESENTER_PROVIDER_CLASS = "PresenterProviders" } }
0
Kotlin
0
0
515d2b91dd7209c34a4c34761f474703d6200430
2,105
Archroid
Apache License 2.0
navigation/src/main/java/com/beetlestance/androidextensions/navigation/data/NavigateOnceDirectionRequest.kt
beetlestance
282,616,603
false
null
package com.devdd.recipe.ui.utils.navigation import androidx.navigation.NavDirections import androidx.navigation.NavOptions import androidx.navigation.fragment.FragmentNavigator data class NavigateOnceDirectionRequest( // directions for navigation val directions: NavDirections, // NavOptions stores special options for navigate actions val navOptions: NavOptions? = null, // Extras that can be passed to FragmentNavigator to enable Fragment specific behavior // such as shared transitions for destination val navigatorExtras: FragmentNavigator.Extras? = null, // Defines the behavior of multiple continuous instances to be allowed or not for a destination. // true: allows continuous instances of a same fragment. // false: do not allow continuous instances of same fragment. val allowMultipleInstance: Boolean = false, // if set to true fragment will be popped from backStack and navigate // else set to false backStackEntry will be used with old arguments if any val updateArguments: Boolean = true )
2
Kotlin
1
9
52514231c13695292826b2872792349590234197
1,064
android-extensions
Apache License 2.0
ChartboostMediation/src/main/java/com/chartboost/chartboostmediationsdk/domain/MetricsEvent.kt
ChartBoost
647,839,758
false
{"Kotlin": 711726, "Ruby": 2509}
/* * Copyright 2023-2024 Chartboost, Inc. * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file. */ package com.chartboost.chartboostmediationsdk.domain /** * The metrics to be collected for an ad lifecycle event. Each entity is a single event that * corresponds to a single partner. * * @property eventType The type of event. * @property partner The partner name. */ data class MetricsEvent( val eventType: EventType, val partner: String, ) { /** * The type of event. */ enum class EventType { INITIALIZATION, PREBID, LOAD, SHOW, CLICK, EXPIRATION, } private val startTimestamp: Long = System.currentTimeMillis() var endTimestamp: Long = 0L var isSuccess: Boolean = false var error: ChartboostMediationError? = null // TODO: Port the other one-off fields from the [[Metrics]] class. fun getDuration() = if (endTimestamp > 0) endTimestamp - startTimestamp else 0 }
0
Kotlin
0
0
18948613638191a0639eb264ec6e39f3d37bf722
1,033
chartboost-mediation-android-sdk
MIT License
kotlinx-coroutines-core/jvm/test/guide/example-flow-15.kt
hltj
151,721,407
false
null
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. package kotlinx.coroutines.guide.flow15 import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") fun foo(): Flow<Int> = flow { for (i in 1..3) { Thread.sleep(100) // pretend we are computing it in CPU-consuming way log("Emitting $i") emit(i) // emit next value } }.flowOn(Dispatchers.Default) // RIGHT way to change context for CPU-consuming code in flow builder fun main() = runBlocking<Unit> { foo().collect { value -> log("Collected $value") } }
1
null
106
255
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
806
kotlinx.coroutines-cn
Apache License 2.0
src/test/kotlin/org/thiyagu/zally/reports/ReporterTest.kt
thiyagu06
384,658,347
false
{"Kotlin": 53809, "HTML": 1660}
package org.thiyagu.zally.reports import org.junit.jupiter.api.Test import kotlin.test.assertTrue class ReporterTest { @Test fun `should successfully generate report in the specific location`() { assertTrue { true } } }
17
Kotlin
1
3
556ced61e8d0298feedb2bd490e37dc9c972dd64
243
zally-gradle-plugin
MIT License
odyssey/odyssey-compose/src/commonMain/kotlin/ru/alexgladkov/odyssey/compose/navigation/ComposeMultistackBuilder.kt
StanislavY
451,101,456
false
null
package ru.alexgladkov.odyssey.compose.navigation import ru.alexgladkov.odyssey.compose.helpers.MutableScreenMap import ru.alexgladkov.odyssey.compose.helpers.ScreenMap import ru.alexgladkov.odyssey.core.destination.DestinationFlow import ru.alexgladkov.odyssey.core.destination.DestinationMultiFlow /** * Compose multi stack builder, declarative helper for navigation graph builder * @see DestinationMultiFlow * @param name - flow name */ class ComposeMultiStackBuilder(val name: String) { private val _destinations: MutableList<DestinationFlow> = mutableListOf() private val _screenMap: MutableScreenMap = hashMapOf() val screenMap: ScreenMap = _screenMap fun addFlow(destinationFlow: DestinationFlow, map: ScreenMap) { _destinations.add(destinationFlow) _screenMap.putAll(map) } fun build(): DestinationMultiFlow = DestinationMultiFlow(name, _destinations) } fun ComposeMultiStackBuilder.tab( name: String, block: ComposeFlowBuilder.() -> Unit ) { val builder = ComposeFlowBuilder(name) val destinationFlow = builder.apply(block).build() addFlow(destinationFlow, builder.screenMap) }
0
Kotlin
0
0
b25d71a63ae8040b8fe40a9f494be3fcf1f8e8b2
1,158
odyssey
MIT License
feature/push/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/push/service/impl/NotificationSettingsServiceImpl.kt
ls1intum
537,104,541
false
null
package de.tum.informatics.www1.artemis.native_app.feature.push.service.impl import de.tum.informatics.www1.artemis.native_app.core.data.NetworkResponse import de.tum.informatics.www1.artemis.native_app.core.data.cookieAuth import de.tum.informatics.www1.artemis.native_app.core.data.performNetworkCall import de.tum.informatics.www1.artemis.native_app.core.data.service.impl.KtorProvider import de.tum.informatics.www1.artemis.native_app.feature.push.ui.model.PushNotificationSetting import io.ktor.client.call.body import io.ktor.client.request.get import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.appendPathSegments import io.ktor.http.contentType internal class NotificationSettingsServiceImpl(private val ktorProvider: KtorProvider) : de.tum.informatics.www1.artemis.native_app.feature.push.service.NotificationSettingsService { private companion object { private val pushNotificationSettingsResourcePathSegments = listOf("api", "notification-settings") } override suspend fun getNotificationSettings( serverUrl: String, authToken: String ): NetworkResponse<List<PushNotificationSetting>> { return performNetworkCall { ktorProvider.ktorClient.get(serverUrl) { url { appendPathSegments(pushNotificationSettingsResourcePathSegments) } contentType(ContentType.Application.Json) cookieAuth(authToken) }.body() } } override suspend fun updateNotificationSettings( newSettings: List<PushNotificationSetting>, serverUrl: String, authToken: String ): NetworkResponse<List<PushNotificationSetting>> { return performNetworkCall { ktorProvider.ktorClient.put(serverUrl) { url { appendPathSegments(pushNotificationSettingsResourcePathSegments) } contentType(ContentType.Application.Json) cookieAuth(authToken) setBody(newSettings) }.body() } } }
2
Kotlin
0
2
466a1c60c3b2f9a9b57c4a98adac0361e4c711c3
2,169
artemis-android
Apache License 2.0
app/src/main/java/com/elementary/tasks/core/analytics/Traces.kt
naz013
165,067,747
false
{"Kotlin": 2971145, "HTML": 20925}
package com.elementary.tasks.core.analytics import android.content.Context import com.elementary.tasks.R import com.elementary.tasks.core.utils.Module import com.elementary.tasks.core.utils.SuperUtil import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.crashlytics.setCustomKeys import com.google.firebase.ktx.Firebase import org.slf4j.LoggerFactory object Traces { var reportingEnabled: Boolean = true var logger: Logger = FileLogger() fun log(message: String) { logger.info(message) } fun d(message: String) { logger.debug(message) } fun setUpKeys(context: Context) { Firebase.crashlytics.setCustomKeys { key("has_google_play_services", SuperUtil.isGooglePlayServicesAvailable(context)) key("is_tablet", context.resources.getBoolean(R.bool.is_tablet)) key("is_chrome_os", Module.isChromeOs(context)) key("has_location", Module.hasLocation(context)) key("has_camera", Module.hasCamera(context)) key("has_telephony", Module.hasTelephony(context)) } } fun logEvent(message: String) { logger.info(message) if (reportingEnabled) { Firebase.crashlytics.log(message) } } } interface Logger { fun info(message: String) fun debug(message: String) } class FileLogger( private val logger: org.slf4j.Logger = LoggerFactory.getLogger("FileLogger") ) : Logger { override fun info(message: String) { logger.info(message) } override fun debug(message: String) { logger.debug(message) } }
0
Kotlin
3
6
a6eecfda739be05a4b84e7d47284cd9e2bc782d6
1,525
reminder-kotlin
Apache License 2.0
app/src/main/java/com/tharunbirla/librecuts/MainActivity.kt
tharunbirla
873,590,113
false
{"Kotlin": 41883}
package com.tharunbirla.librecuts import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.tharunbirla.librecuts.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var requestPermissionsLauncher: ActivityResultLauncher<Array<String>> private val selectVideoLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> if (uri != null) { Log.d("VideoSelection", "Video selected: $uri") navigateToEditingScreen(uri) } else { Log.e("VideoSelectionError", "No video selected") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupPermissions() binding.addVideoButton.setOnClickListener { if (arePermissionsGranted()) { Log.d("ButtonClick", "Permissions granted, launching video selection.") selectVideo() } else { Log.w("PermissionCheck", "Permissions not granted, showing request dialog.") showPermissionRequestDialog() } } } private fun setupPermissions() { requestPermissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> val allGranted = permissions.values.all { it } if (allGranted) { Log.d("PermissionResult", "All permissions granted.") showToast("Permissions granted") } else { Log.w("PermissionResult", "Some permissions were denied.") showToast("Some permissions were denied") } } if (!arePermissionsGranted()) { Log.i("PermissionSetup", "Requesting permissions.") showPermissionRequestDialog() } } private fun arePermissionsGranted(): Boolean { return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> { checkPermissions( Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_IMAGES ) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { checkPermissions( Manifest.permission.READ_EXTERNAL_STORAGE ) } else -> { checkPermissions( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ) } } } private fun checkPermissions(vararg permissions: String): Boolean { return permissions.all { permission -> ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED }.also { result -> Log.d("PermissionCheck", "Permissions checked: $result") } } private fun showPermissionRequestDialog() { Log.i("PermissionDialog", "Displaying permission request dialog.") MaterialAlertDialogBuilder(this) .setTitle("Permissions Required") .setMessage("This app needs permissions to access media files and show notifications.") .setPositiveButton("Grant") { _, _ -> requestPermissions() } .setNegativeButton("Cancel") { dialog, _ -> Log.i("PermissionDialog", "User canceled the permission request.") dialog.dismiss() } .setCancelable(false) .show() } private fun requestPermissions() { val permissions = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> { arrayOf( Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_VIDEO, Manifest.permission.READ_MEDIA_IMAGES ) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) } else -> { arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ) } } Log.d("PermissionRequest", "Requesting permissions: ${permissions.joinToString()}") requestPermissionsLauncher.launch(permissions) } private fun selectVideo() { Log.d("VideoSelection", "Launching video selector.") selectVideoLauncher.launch("video/*") } private fun navigateToEditingScreen(videoUri: Uri) { Log.d("Navigation", "Navigating to editing screen with URI: $videoUri") val intent = Intent(this, VideoEditingActivity::class.java) intent.putExtra("VIDEO_URI", videoUri) startActivity(intent) } private fun showToast(message: String) { Log.d("ToastMessage", "Showing toast: $message") Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
0
Kotlin
1
1
dad8766e1511c46ddd3499453058d7a501b9868d
5,954
LibreCuts
MIT License
common/src/commonMain/kotlin/entity/DiscordComponent.kt
kordlib
202,856,399
false
null
@file:Generate( INT_KORD_ENUM, name = "ComponentType", docUrl = "https://discord.com/developers/docs/interactions/message-components#component-object-component-types", entries = [ Entry("ActionRow", intValue = 1, kDoc = "A container for other components."), Entry("Button", intValue = 2, kDoc = "A button object."), Entry("StringSelect", intValue = 3, kDoc = "A select menu for picking from defined text options."), Entry("TextInput", intValue = 4, kDoc = "A text input object."), Entry("UserSelect", intValue = 5, kDoc = "Select menu for users."), Entry("RoleSelect", intValue = 6, kDoc = "Select menu for roles."), Entry("MentionableSelect", intValue = 7, kDoc = "Select menu for mentionables (users and roles)."), Entry("ChannelSelect", intValue = 8, kDoc = "Select menu for channels."), ], ) @file:Generate( INT_KORD_ENUM, name = "ButtonStyle", kDoc = "Style of a [button][dev.kord.common.entity.ComponentType.Button].", docUrl = "https://discord.com/developers/docs/interactions/message-components#button-object-button-styles", entries = [ Entry("Primary", intValue = 1, kDoc = "Blurple."), Entry("Secondary", intValue = 2, kDoc = "Grey."), Entry("Success", intValue = 3, kDoc = "Green."), Entry("Danger", intValue = 4, kDoc = "Red."), Entry("Link", intValue = 5, kDoc = "Grey, navigates to a URL."), ], ) @file:Generate( INT_KORD_ENUM, name = "TextInputStyle", kDoc = "Style of a [text·input][dev.kord.common.entity.ComponentType.TextInput].", docUrl = "https://discord.com/developers/docs/interactions/message-components#text-input-object-text-input-styles", entries = [ Entry("Short", intValue = 1, kDoc = "A single-line input."), Entry("Paragraph", intValue = 2, kDoc = "A multi-line input."), ], ) package dev.kord.common.entity import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.OptionalBoolean import dev.kord.common.entity.optional.OptionalInt import dev.kord.ksp.Generate import dev.kord.ksp.Generate.EntityType.INT_KORD_ENUM import dev.kord.ksp.Generate.Entry import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.* /** * Represent a [interactable component within a message sent in Discord](https://discord.com/developers/docs/interactions/message-components#what-are-components). * * @property type the [ComponentType] of the component * @property emoji an [DiscordPartialEmoji] that appears on the button (if the component is a button) * @property customId a developer-defined identifier for the button, max 100 characters * @property url a url for link-style buttons * @property disabled whether the button is disabled, default `false` * @property components a list of child components (for action rows) * @property options the select menu options * @property placeholder the placeholder text for the select menu * @property minValues the minimum amount of [options] allowed * @property maxValues the maximum amount of [options] allowed * @property minLength the minimum input length for a text input, min 0, max 4000. * @property maxLength the maximum input length for a text input, min 1, max 4000. * @property required whether this component is required to be filled, default false. * @property value a pre-filled value for this component, max 4000 characters. * @property channelTypes List of channel types to include in the channel select component ([ComponentType.ChannelSelect]) */ @Serializable(with = DiscordComponent.Serializer::class) public sealed class DiscordComponent { public abstract val type: ComponentType public abstract val label: Optional<String> public abstract val emoji: Optional<DiscordPartialEmoji> @SerialName("custom_id") public abstract val customId: Optional<String> public abstract val url: Optional<String> public abstract val disabled: OptionalBoolean public abstract val components: Optional<List<DiscordComponent>> public abstract val options: Optional<List<DiscordSelectOption>> public abstract val placeholder: Optional<String> @SerialName("min_values") public abstract val minValues: OptionalInt @SerialName("max_values") public abstract val maxValues: OptionalInt @SerialName("min_length") public abstract val minLength: OptionalInt @SerialName("max_length") public abstract val maxLength: OptionalInt public abstract val required: OptionalBoolean public abstract val value: Optional<String> @SerialName("channel_types") public abstract val channelTypes: Optional<List<ChannelType>> internal object Serializer : JsonContentPolymorphicSerializer<DiscordComponent>(DiscordComponent::class) { override fun selectDeserializer(element: JsonElement): KSerializer<out DiscordComponent> { val componentType = element.jsonObject["type"]?.jsonPrimitive?.intOrNull ?: error("Missing component type ID!") return if (componentType == ComponentType.TextInput.value) { DiscordTextInputComponent.serializer() } else { DiscordChatComponent.serializer() } } } } @Serializable public data class DiscordChatComponent( override val type: ComponentType, val style: Optional<ButtonStyle> = Optional.Missing(), override val label: Optional<String> = Optional.Missing(), override val emoji: Optional<DiscordPartialEmoji> = Optional.Missing(), @SerialName("custom_id") override val customId: Optional<String> = Optional.Missing(), override val url: Optional<String> = Optional.Missing(), override val disabled: OptionalBoolean = OptionalBoolean.Missing, override val components: Optional<List<DiscordComponent>> = Optional.Missing(), override val options: Optional<List<DiscordSelectOption>> = Optional.Missing(), override val placeholder: Optional<String> = Optional.Missing(), @SerialName("min_values") override val minValues: OptionalInt = OptionalInt.Missing, @SerialName("max_values") override val maxValues: OptionalInt = OptionalInt.Missing, @SerialName("min_length") override val minLength: OptionalInt = OptionalInt.Missing, @SerialName("max_length") override val maxLength: OptionalInt = OptionalInt.Missing, override val required: OptionalBoolean = OptionalBoolean.Missing, override val value: Optional<String> = Optional.Missing(), @SerialName("channel_types") override val channelTypes: Optional<List<ChannelType>> = Optional.Missing(), ) : DiscordComponent() @Serializable public data class DiscordTextInputComponent( override val type: ComponentType, public val style: Optional<TextInputStyle> = Optional.Missing(), override val label: Optional<String> = Optional.Missing(), override val emoji: Optional<DiscordPartialEmoji> = Optional.Missing(), @SerialName("custom_id") override val customId: Optional<String> = Optional.Missing(), override val url: Optional<String> = Optional.Missing(), override val disabled: OptionalBoolean = OptionalBoolean.Missing, override val components: Optional<List<DiscordComponent>> = Optional.Missing(), override val options: Optional<List<DiscordSelectOption>> = Optional.Missing(), override val placeholder: Optional<String> = Optional.Missing(), @SerialName("min_values") override val minValues: OptionalInt = OptionalInt.Missing, @SerialName("max_values") override val maxValues: OptionalInt = OptionalInt.Missing, @SerialName("min_length") override val minLength: OptionalInt = OptionalInt.Missing, @SerialName("max_length") override val maxLength: OptionalInt = OptionalInt.Missing, override val required: OptionalBoolean = OptionalBoolean.Missing, override val value: Optional<String> = Optional.Missing(), @SerialName("channel_types") override val channelTypes: Optional<List<ChannelType>> = Optional.Missing(), ) : DiscordComponent()
54
null
82
922
e99c5c583229d20e69632aae39cee47da637abef
8,178
kord
MIT License
feature/teacher/impl/src/main/java/com/turtleteam/impl/data/repository/TeacherRepositoryImpl.kt
Egor-Liadsky
711,194,733
false
{"Kotlin": 188247}
package com.turtleteam.impl.data.repository import com.turtleteam.api.BaseRepository import com.turtleteam.api.data.repository.TeacherRepository import com.turtleteam.api.models.GroupAndTeacher import com.turtleteam.api.models.Schedule import io.ktor.http.HttpMethod import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json class TeacherRepositoryImpl(private val repository: BaseRepository) : TeacherRepository { override suspend fun getSchedule(group: String): Schedule { val response = repository.executeCall( type = HttpMethod.Get, path = "schedule/$group", headers = mapOf("Content-Type" to "application/json"), ) return Json.decodeFromString(response) } override suspend fun getTeachers(): GroupAndTeacher { val response = repository.executeCall( type = HttpMethod.Get, path = "schedule/list", headers = mapOf("Content-Type" to "application/json"), ) return Json.decodeFromString(response) } }
0
Kotlin
0
0
bbf8d1a4220fd781fb2ca007b7b7774e7bbb725d
1,068
TurtleAppAndroid
Apache License 2.0
src/nativeMain/kotlin/fr/amoya/ktaglib/platformdependent/file/NativeFileReader.kt
moya-a
363,263,644
false
null
package fr.amoya.ktaglib.platformdependent.file /* * fr.amoya.ktaglib.file * As a part of the Project k-taglib * @Author <NAME> : <<EMAIL>> * Created on 30/04/2021 */ class NativeFileReader : FileReader { override val size: Long get() = -1L override val cursor: Long get() = 0L override fun load(filename: String) { TODO("Not yet implemented") } override fun readNBytes(size: String): ByteArray { TODO("Not yet implemented") } override fun readEntireFile(): Sequence<Byte> { TODO("Not yet implemented") } override fun close() { TODO("Not yet implemented") } }
0
Kotlin
0
1
d3dd69285fa3d1d1efc35e22d5766f5a24a7f248
622
k-taglib
MIT License
src/test/kotlin/dev/shtanko/algorithms/leetcode/CountVowelsPermutationTest.kt
ashtanko
203,993,092
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.TestFactory abstract class CountVowelsPermutationTest<out T : CountVowelsPermutationStrategy>(private val strategy: T) { @TestFactory fun `count vowel permutation strategies test`() = listOf( 1 to 5, 2 to 10, 5 to 68, ).map { (input, expected) -> DynamicTest.dynamicTest("dp $strategy count vowel permutation of $input then get $expected") { Assertions.assertEquals(expected, strategy.perform(input)) } } } class CountVowelsPermutationBottomUpTest : CountVowelsPermutationTest<CountVowelsPermutation.BottomUp>(CountVowelsPermutation.BottomUp()) class CountVowelsPermutationOptimizedSpaceTest : CountVowelsPermutationTest<CountVowelsPermutation.OptimizedSpace>(CountVowelsPermutation.OptimizedSpace()) class CountVowelsPermutationTopDownTest : CountVowelsPermutationTest<CountVowelsPermutation.TopDown>(CountVowelsPermutation.TopDown())
3
Kotlin
0
18
dafb14ab0e1739d0ce9ad481a46c522689dab6b0
1,663
kotlab
Apache License 2.0
app/src/main/java/com/dolar/mycoffee/entity/NetworkError.kt
Colibri91
452,211,546
false
{"Kotlin": 39023}
package com.dolar.mycoffee.entity /** * Created by R. Mert Dolar on 7.01.2022. */ data class NetworkError(val errorCode: Int, val error : String? = "", val error_description : String? = "")
0
Kotlin
0
0
7e1cfc3b59ee80c97ed63764a0f11db442972066
240
CoffeeCompose
Apache License 2.0
basic_apps/motivation_generator/app/src/main/java/com/example/motivationgenerator/views/SplashActivity.kt
LucasGeek
235,174,423
false
null
package com.example.motivationgenerator.views import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.example.motivationgenerator.R import com.example.motivationgenerator.util.MotivationConstants import com.example.motivationgenerator.util.SecurityPreferences import kotlinx.android.synthetic.main.activity_splash.* class SplashActivity : AppCompatActivity(), View.OnClickListener { private lateinit var mSecurity: SecurityPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) mSecurity = SecurityPreferences(this) btnSave.setOnClickListener(this) verifyUserName() } override fun onClick(v: View) { when (v.id) { R.id.btnSave -> handleSave() } } private fun handleSave() { val name: String = editName.text.toString() if (name.isNullOrEmpty()) { Toast.makeText(this, getString(R.string.informe_seu_nome), Toast.LENGTH_LONG).show() } else { mSecurity.storeString(MotivationConstants.KEY.PERSON_NAME, name) changeActvity() } } private fun verifyUserName() { val userName = mSecurity.getStoredString(MotivationConstants.KEY.PERSON_NAME) if(userName.isNotEmpty()) { changeActvity() } editName.setText(userName) } private fun changeActvity() { val intent: Intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } }
0
Kotlin
0
0
c4885d49adbd0cd6af461ca5a954bf9f28ce002e
1,705
Android-Native-APPS
MIT License
kmongo-data/src/main/kotlin/org/litote/kmongo/DataRegistry.kt
Litote
58,964,537
false
null
/* * Copyright (C) 2018 Litote * * 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.litote.jackson.data import kotlin.reflect.KClass /** * Give the same behaviour than @[JacksonData] to the specified KClass array. * Useful if you can't annotate directly the target classes. */ @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE) @Retention(AnnotationRetention.SOURCE) @MustBeDocumented annotation class JacksonDataRegistry( /** * List of data classes. */ val value: Array<KClass<*>>, /** * Set to internal visibility the generated classes. */ val internal: Boolean = false )
42
null
74
797
4ee6939272ca54a342955130ae6d98eb947ace01
1,137
kmongo
Apache License 2.0
ui/developer/settings/src/commonMain/kotlin/app/tivi/settings/developer/DevSettingsPresenter.kt
chrisbanes
100,624,553
false
null
// Copyright 2019, Google LLC, <NAME> and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.settings.developer import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import app.tivi.screens.DevLogScreen import app.tivi.screens.DevSettingsScreen import app.tivi.settings.TiviPreferences import app.tivi.settings.toggle import com.slack.circuit.retained.collectAsRetainedState import com.slack.circuit.runtime.CircuitContext import com.slack.circuit.runtime.Navigator import com.slack.circuit.runtime.presenter.Presenter import com.slack.circuit.runtime.screen.Screen import me.tatarka.inject.annotations.Assisted import me.tatarka.inject.annotations.Inject @Inject class DevSettingsUiPresenterFactory( private val presenterFactory: (Navigator) -> DevSettingsPresenter, ) : Presenter.Factory { override fun create( screen: Screen, navigator: Navigator, context: CircuitContext, ): Presenter<*>? = when (screen) { is DevSettingsScreen -> presenterFactory(navigator) else -> null } } @Inject class DevSettingsPresenter( @Assisted private val navigator: Navigator, private val preferences: TiviPreferences, ) : Presenter<DevSettingsUiState> { @Composable override fun present(): DevSettingsUiState { val hideArtwork by remember { preferences.observeDeveloperHideArtwork() } .collectAsRetainedState(false) fun eventSink(event: DevSettingsUiEvent) { when (event) { DevSettingsUiEvent.NavigateUp -> navigator.pop() DevSettingsUiEvent.NavigateLog -> navigator.goTo(DevLogScreen) DevSettingsUiEvent.ToggleHideArtwork -> preferences::developerHideArtwork.toggle() } } return DevSettingsUiState( hideArtwork = hideArtwork, eventSink = ::eventSink, ) } }
21
null
857
6,290
1f8049e7f5898d6bd295c73fc6f1ed887e38d572
1,867
tivi
Apache License 2.0
lib/src/main/kotlin/com/gshcherb/fixedtabs/FixedTabsDataSetObserver.kt
gshcherb
144,211,549
false
null
package com.gshcherb.fixedtabs import android.database.DataSetObserver import androidx.viewpager.widget.ViewPager class FixedTabsDataSetObserver( private val tabsLayout: FixedTabsLayout, private val viewPager: ViewPager ) : DataSetObserver() { override fun onChanged() { super.onChanged() viewPager.adapter?.run { tabsLayout.fillTabs(viewPager, count) } } override fun onInvalidated() { super.onInvalidated() viewPager.adapter?.run { tabsLayout.fillTabs(viewPager, count) } } }
1
null
1
1
5162492de4bd3c61cf3e86cd7255a142d374e6cc
545
fixedtabslayout
Apache License 2.0
core/ui-kmp/src/androidMain/kotlin/org/michaelbel/movies/ui/compose/iconbutton/PasswordIcon.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.ui.compose.iconbutton import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import org.michaelbel.movies.ui.accessibility.MoviesContentDescription import org.michaelbel.movies.ui.icons.MoviesIcons import org.michaelbel.movies.ui.preview.DevicePreviews import org.michaelbel.movies.ui.preview.provider.BooleanPreviewParameterProvider import org.michaelbel.movies.ui.theme.AmoledTheme import org.michaelbel.movies.ui.theme.MoviesTheme @Composable fun PasswordIcon( state: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton( onClick = onClick, modifier = modifier ) { Image( imageVector = if (state) MoviesIcons.Visibility else MoviesIcons.VisibilityOff, contentDescription = stringResource(if (state) MoviesContentDescription.PasswordIcon else MoviesContentDescription.PasswordOffIcon), colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onPrimaryContainer) ) } } @Composable @DevicePreviews private fun PasswordIconPreview( @PreviewParameter(BooleanPreviewParameterProvider::class) state: Boolean ) { MoviesTheme { PasswordIcon( state = state, onClick = {}, modifier = Modifier.background(MaterialTheme.colorScheme.primaryContainer) ) } } @Composable @Preview private fun PasswordIconAmoledPreview( @PreviewParameter(BooleanPreviewParameterProvider::class) state: Boolean ) { AmoledTheme { PasswordIcon( state = state, onClick = {}, modifier = Modifier.background(MaterialTheme.colorScheme.primaryContainer) ) } }
7
null
31
186
e7b74544e4951a2fd49cc02d7858fb8df89c0eae
2,106
movies
Apache License 2.0
common-ui/src/main/java/com/skydoves/common_ui/adapters/TvListAdapter.kt
skydoves
225,837,633
false
null
/* * Designed and developed by 2019 skydoves (<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.skydoves.common_ui.adapters import android.view.View import com.skydoves.baserecyclerviewadapter.BaseAdapter import com.skydoves.baserecyclerviewadapter.SectionRow import com.skydoves.common_ui.R import com.skydoves.common_ui.viewholders.TvListViewHolder import com.skydoves.entity.entities.Tv /** TvFavouriteListAdapter is an adapter class for binding [Tv] items. */ class TvListAdapter( private val delegate: TvListViewHolder.Delegate ) : BaseAdapter() { init { addSection(ArrayList<Tv>()) } fun addTvList(tvs: List<Tv>) { val section = sections()[0] section.addAll(tvs) notifyItemRangeInserted(section.size - tvs.size + 1, tvs.size) } override fun layout(sectionRow: SectionRow) = R.layout.item_tv override fun viewHolder(layout: Int, view: View) = TvListViewHolder(view, delegate) }
4
Kotlin
52
353
f9ef645bc86a9c13ab01624a7e6d21269c128b31
1,449
GoldMovies
Apache License 2.0