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
platform/lang-impl/src/com/intellij/ide/util/scopeChooser/CoroutineScopeModel.kt
sprigogin
93,194,179
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.util.scopeChooser import com.intellij.ide.DataManager import com.intellij.ide.util.treeView.WeighedItem import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.impl.Utils import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import com.intellij.openapi.application.readAction import com.intellij.openapi.diagnostic.getOrLogException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.ListSeparator import com.intellij.openapi.util.text.StringUtil import com.intellij.platform.util.coroutines.sync.OverflowSemaphore import com.intellij.psi.search.PredefinedSearchScopeProvider import com.intellij.psi.search.SearchScope import com.intellij.psi.search.SearchScopeProvider import com.intellij.util.ui.EDT import kotlinx.coroutines.* import kotlinx.coroutines.channels.BufferOverflow import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.await import java.util.concurrent.CopyOnWriteArrayList import java.util.function.Predicate internal class CoroutineScopeModel internal constructor( private val project: Project, private val coroutineScope: CoroutineScope, options: Set<ScopeOption>, ) : AbstractScopeModel { private val semaphore = OverflowSemaphore(permits = 1, overflow = BufferOverflow.DROP_OLDEST) private val listeners = CopyOnWriteArrayList<ScopeModelListener>() private val options = mutableSetOf<ScopeOption>().apply { addAll(options) } private var filter: (ScopeDescriptor) -> Boolean = { true } override fun setOption(option: ScopeOption, value: Boolean) { if (value) { options.add(option) } else { options.remove(option) } } override fun addScopeModelListener(listener: ScopeModelListener) { listeners += listener } override fun removeScopeModelListener(listener: ScopeModelListener) { listeners -= listener } override fun setFilter(filter: (ScopeDescriptor) -> Boolean) { this.filter = filter } override fun refreshScopes(dataContext: DataContext?) { val givenDataContext = dataContext?.let { Utils.createAsyncDataContext(it) } var earlyDataContextPromise: Promise<DataContext>? = null if (givenDataContext == null && EDT.isCurrentThreadEdt()) { // We need to capture the data context from focus as early as possible, // because focus might change very soon (important when invoking a dialog, e.g., Find in Files). earlyDataContextPromise = dataContextFromFocusPromise() } coroutineScope.launch( start = CoroutineStart.UNDISPATCHED, context = ModalityState.any().asContextElement(), ) { semaphore.withPermit { yield() // dispatch runCatching { val effectiveDataContext: DataContext = when { givenDataContext != null -> givenDataContext earlyDataContextPromise != null -> earlyDataContextPromise.await() else -> dataContextFromFocusPromise().await() } fireScopesUpdated(getScopeDescriptors(effectiveDataContext, filter)) }.getOrLogException(LOG) } } } private fun dataContextFromFocusPromise(): Promise<DataContext> = DataManager.getInstance().dataContextFromFocusAsync .then { Utils.createAsyncDataContext(it) } private fun fireScopesUpdated(scopesSnapshot: ScopesSnapshot) { listeners.forEach { it.scopesUpdated(scopesSnapshot) } } override suspend fun getScopes(dataContext: DataContext): ScopesSnapshot = getScopeDescriptors(dataContext, filter) @Deprecated("Slow and blocking, use getScopes() in a suspending context, or addScopeModelListener() and refreshScopes()") override fun getScopesImmediately(dataContext: DataContext): ScopesSnapshot = ScopeModel.getScopeDescriptors(project, dataContext, options, filter) private suspend fun getScopeDescriptors( dataContext: DataContext, filter: Predicate<in ScopeDescriptor>, ): ScopesSnapshot { val predefinedScopes = PredefinedSearchScopeProvider.getInstance().getPredefinedScopesSuspend( project, dataContext, options.contains(ScopeOption.LIBRARIES), options.contains(ScopeOption.SEARCH_RESULTS), options.contains(ScopeOption.FROM_SELECTION), options.contains(ScopeOption.USAGE_VIEW), options.contains(ScopeOption.EMPTY_SCOPES) ) return doProcessScopes(dataContext, predefinedScopes, filter) } private suspend fun doProcessScopes( dataContext: DataContext, predefinedScopes: List<SearchScope>, filter: Predicate<in ScopeDescriptor>, ): ScopesSnapshot { val resultScopes = mutableListOf<ScopeDescriptor>() val resultSeparators: HashMap<String, ListSeparator> = HashMap() for (searchScope in predefinedScopes) { val scopeDescriptor = ScopeDescriptor(searchScope) if (filter.test(scopeDescriptor)) { resultScopes.add(scopeDescriptor) } } for (provider in ScopeDescriptorProvider.EP_NAME.extensionList) { val scopes = readAction { provider.getScopeDescriptors(project, dataContext) } for (descriptor in scopes) { if (filter.test(descriptor)) { resultScopes.add(descriptor) } } } for (provider in SearchScopeProvider.EP_NAME.extensionList) { val separatorName = provider.displayName if (separatorName.isNullOrEmpty()) continue val scopes = readAction { provider.getSearchScopes(project, dataContext) } if (scopes.isEmpty()) continue val scopeSeparator = ScopeSeparator(separatorName) if (filter.test(scopeSeparator)) { resultScopes.add(scopeSeparator) } var isFirstScope = false for (scope in scopes.sortedWith(comparator)) { val scopeDescriptor = ScopeDescriptor(scope) if (filter.test(scopeDescriptor)) { if (!isFirstScope) { isFirstScope = true resultSeparators[scope.displayName] = ListSeparator(separatorName) } resultScopes.add(scopeDescriptor) } } } return ScopesSnapshotImpl(resultScopes, resultSeparators) } } private val comparator = Comparator { o1: SearchScope, o2: SearchScope -> val w1 = o1.weight val w2 = o2.weight if (w1 == w2) return@Comparator StringUtil.naturalCompare(o1.displayName, o2.displayName) w1.compareTo(w2) } private val SearchScope.weight: Int get() = if (this is WeighedItem) weight else Int.MAX_VALUE private val LOG = logger<CoroutineScopeModel>()
1
null
1
1
f1b733c79fd134e6646f28d1dc99af144c942785
6,734
intellij-community
Apache License 2.0
trixnity-client/trixnity-client-repository-room/src/androidUnitTest/kotlin/net/folivo/trixnity/client/store/repository/room/RoomRepositoryTransactionManagerTest.kt
benkuly
330,904,570
false
{"Kotlin": 4183229, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1275}
package net.folivo.trixnity.client.store.repository.room import io.kotest.matchers.shouldBe import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class RoomRepositoryTransactionManagerTest { private lateinit var db: TrixnityRoomDatabase private lateinit var dao: GlobalAccountDataDao private lateinit var tm: RoomRepositoryTransactionManager @Before fun before() { db = buildTestDatabase() dao = db.globalAccountData() // using this table as a random example tm = RoomRepositoryTransactionManager(db) } @Test fun `Should not lock when writing`() = runTest { tm.writeTransaction { testWrite(key = "bar") testRead() tm.writeTransaction { testWrite(key = "foo") testRead() } } } @Test fun `Should allow simultaneous transactions when writing`() = runTest { val calls = 10 val callCount = MutableStateFlow(0) repeat(calls) { i -> launch { callCount.value++ tm.writeTransaction { callCount.first { it == calls } testWrite(key = i.toString()) } } } } @Test fun `Should allow simultaneous writes`() = runTest { val calls = 10 val callCount = MutableStateFlow(0) tm.writeTransaction { coroutineScope { repeat(calls) { i -> launch { callCount.value++ callCount.first { it == calls } testWrite(key = i.toString()) } } } } } @Test fun `Should not lock when reading`() = runTest { tm.readTransaction { testRead() tm.readTransaction { testRead() } } } @Test fun `Should rollback on exception`() = runTest { try { tm.writeTransaction { testWrite("1") throw RuntimeException("dino") } } catch (_: Exception) { } tm.writeTransaction { testWrite("2") } tm.readTransaction { testRead("1") }.size shouldBe 0 tm.readTransaction { testRead("2") }.size shouldBe 1 } private suspend fun testRead(key: String = "foo") = dao.getAllByType(type = key) private suspend fun testWrite(key: String) { val entity = RoomGlobalAccountData(type = key, key = "789xyz", event = "hello world") dao.insert(entity) } }
0
Kotlin
3
29
af79f86aa21c4a956ce7a0e7f1fbbe2df28c26bc
3,011
trixnity
Apache License 2.0
app/src/main/java/com/kenkoro/taurus/client/feature/orders/presentation/screen/editor/order/composables/OrderEditorTextFields.kt
kenkoro
746,982,789
false
{"Kotlin": 272290, "JavaScript": 64}
package com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.composables import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import com.kenkoro.taurus.client.R import com.kenkoro.taurus.client.core.local.LocalContentHeight import com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.composables.util.OrderDetailItem import com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.states.OrderDetails import com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.util.OrderEditorScreenNavigator import com.kenkoro.taurus.client.feature.orders.presentation.screen.editor.order.util.OrderEditorScreenShared @Composable fun OrderEditorTextFields( modifier: Modifier = Modifier, details: OrderDetails, navigator: OrderEditorScreenNavigator, shared: OrderEditorScreenShared, ) { val focusManager = LocalFocusManager.current val contentHeight = LocalContentHeight.current val lazyListState = rememberLazyListState() val orderDetailItems = listOf( OrderDetailItem( state = details.customerState, dropDownTitle = stringResource(id = R.string.order_editor_customer), ), OrderDetailItem( state = details.titleState, dropDownTitle = stringResource(id = R.string.order_editor_title), ), OrderDetailItem( state = details.modelState, dropDownTitle = stringResource(id = R.string.order_editor_model), ), OrderDetailItem( state = details.sizeState, dropDownTitle = stringResource(id = R.string.order_editor_size), ), OrderDetailItem( state = details.colorState, dropDownTitle = stringResource(id = R.string.order_editor_color), ), OrderDetailItem( state = details.categoryState, dropDownTitle = stringResource(id = R.string.order_editor_category), ), ) LazyColumn( modifier = modifier, state = lazyListState, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top, ) { items(orderDetailItems) { OrderDetailDropDown( navigator = navigator, state = it.state, dropDownTitle = it.dropDownTitle, onChangeBehaviorOfOrderDetailsSearch = shared.changeBehaviorOfOrderDetailsSearch, ) Spacer(modifier = Modifier.height(contentHeight.extraMedium)) } item { Spacer(modifier = Modifier.height(contentHeight.medium)) OrderQuantity( quantityState = details.quantityState, onImeAction = { focusManager.clearFocus() }, ) Spacer(modifier = Modifier.height(contentHeight.extraMedium)) } } }
4
Kotlin
0
4
f14526cccbf81ab247cae532709efe57b63b71f5
3,166
taurus
Apache License 2.0
java/ql/integration-tests/kotlin/all-platforms/extractor_crash/code/C.kt
github
143,040,428
false
null
class C {}
1,149
null
1492
7,510
5108799224a667d9acb2a1a28ff45e680e76e13c
13
codeql
MIT License
src/main/kotlin/craicoverflow89/kraql/components/database.kt
CraicOverflow89
214,449,896
false
null
package craicoverflow89.kraql.components import craicoverflow89.kraql.KraQLApplication import craicoverflow89.kraql.KraQLReservedCreateException import craicoverflow89.kraql.queries.KraQLQueryLexer import craicoverflow89.kraql.queries.KraQLQueryParser import org.antlr.v4.runtime.ANTLRInputStream import org.antlr.v4.runtime.CommonTokenStream import java.io.File class KraQLDatabase(val name: String, private val accountList: ArrayList<KraQLAccount> = arrayListOf(), private val tableList: ArrayList<KraQLTable> = arrayListOf()) { // Debug: IGNORE SAVES private var debugSaveIgnore = false fun addAccount(name: String, password: String, permissions: HashMap<KraQLAccountPermission, Boolean>? = null): KraQLAccount { // Reserved Name if(KraQLApplication.isReserved(name)) throw KraQLReservedCreateException(name) // Create Account val account = KraQLAccount(this, name, password, permissions ?: hashMapOf()) // Add Account accountList.add(account) // Return Account return account } fun addTable(name: String): KraQLTable { // Reserved Name if(KraQLApplication.isReserved(name)) throw KraQLReservedCreateException(name) // Create Table val table = KraQLTable(this, name) // Add Table tableList.add(table) // Return Table return table } fun addTable(name: String, fieldList: ArrayList<KraQLTableField>): KraQLTable { // Reserved Name if(KraQLApplication.isReserved(name)) throw KraQLReservedCreateException(name) // Create Table val table = KraQLTable(this, name, fieldList) // Add Table tableList.add(table) // Return Table return table } fun deleteTable(tableName: String) { // Find Table val table = tableList.firstOrNull { it.name == tableName } ?: throw KraQLTableNotFoundException(tableName) // Delete Table tableList.remove(table) // Save Database save() } fun getAccount(name: String) = accountList.firstOrNull { it.name == name } ?: throw KraQLAccountNotFoundException(name) fun getAccounts() = accountList fun getDebugSaveIgnore() = debugSaveIgnore fun getTable(name: String) = tableList.firstOrNull { it.name == name } ?: throw KraQLTableNotFoundException(name) fun getTables() = tableList fun query(value: String): KraQLQueryResult { // Parse Query val lexer = KraQLQueryLexer(ANTLRInputStream(value)) val parser = KraQLQueryParser(CommonTokenStream(lexer)) val query = parser.query().result // Invoke Query return query.invoke(this) } fun save() { // Debug Ignore if(debugSaveIgnore) return // TEMP INVOKE KraQLApplication.saveDatabase(this, "C:/Users/jamie/Software/Kotlin/KraQL/data/") } fun setDebugSaveIgnore(value: Boolean) { debugSaveIgnore = value } fun toFile() = ArrayList<String>().apply { // Database Data add("$name:${tableList.size}") // NOTE: might want to add other settings to the above // Table Data /*tableList.forEach { addAll(it.toFile()) }*/ } override fun toString() = "{name: $name, tables: ${if(tableList.isEmpty()) "none" else "[" + tableList.joinToString {it.name} + "]"}}" } class KraQLDatabaseNotFoundException: Exception("The path to the database was invalid!")
0
Kotlin
0
0
e8ccb0564a2ce83d725c11c72eb5785a6683848f
3,570
KraQL
MIT License
app/src/main/java/com/example/learning3/ui/theme/themes/PurpleTheme.kt
KrishnarajaSagar
673,030,916
false
null
package com.example.learning3.ui.theme.themes import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import com.example.learning3.ui.theme.colors.purple_theme_dark_background import com.example.learning3.ui.theme.colors.purple_theme_dark_error import com.example.learning3.ui.theme.colors.purple_theme_dark_errorContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_inverseOnSurface import com.example.learning3.ui.theme.colors.purple_theme_dark_inversePrimary import com.example.learning3.ui.theme.colors.purple_theme_dark_inverseSurface import com.example.learning3.ui.theme.colors.purple_theme_dark_onBackground import com.example.learning3.ui.theme.colors.purple_theme_dark_onError import com.example.learning3.ui.theme.colors.purple_theme_dark_onErrorContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_onPrimary import com.example.learning3.ui.theme.colors.purple_theme_dark_onPrimaryContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_onSecondary import com.example.learning3.ui.theme.colors.purple_theme_dark_onSecondaryContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_onSurface import com.example.learning3.ui.theme.colors.purple_theme_dark_onSurfaceVariant import com.example.learning3.ui.theme.colors.purple_theme_dark_onTertiary import com.example.learning3.ui.theme.colors.purple_theme_dark_onTertiaryContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_outline import com.example.learning3.ui.theme.colors.purple_theme_dark_outlineVariant import com.example.learning3.ui.theme.colors.purple_theme_dark_primary import com.example.learning3.ui.theme.colors.purple_theme_dark_primaryContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_scrim import com.example.learning3.ui.theme.colors.purple_theme_dark_secondary import com.example.learning3.ui.theme.colors.purple_theme_dark_secondaryContainer import com.example.learning3.ui.theme.colors.purple_theme_dark_surface import com.example.learning3.ui.theme.colors.purple_theme_dark_surfaceTint import com.example.learning3.ui.theme.colors.purple_theme_dark_surfaceVariant import com.example.learning3.ui.theme.colors.purple_theme_dark_tertiary import com.example.learning3.ui.theme.colors.purple_theme_dark_tertiaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_background import com.example.learning3.ui.theme.colors.purple_theme_light_error import com.example.learning3.ui.theme.colors.purple_theme_light_errorContainer import com.example.learning3.ui.theme.colors.purple_theme_light_inverseOnSurface import com.example.learning3.ui.theme.colors.purple_theme_light_inversePrimary import com.example.learning3.ui.theme.colors.purple_theme_light_inverseSurface import com.example.learning3.ui.theme.colors.purple_theme_light_onBackground import com.example.learning3.ui.theme.colors.purple_theme_light_onError import com.example.learning3.ui.theme.colors.purple_theme_light_onErrorContainer import com.example.learning3.ui.theme.colors.purple_theme_light_onPrimary import com.example.learning3.ui.theme.colors.purple_theme_light_onPrimaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_onSecondary import com.example.learning3.ui.theme.colors.purple_theme_light_onSecondaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_onSurface import com.example.learning3.ui.theme.colors.purple_theme_light_onSurfaceVariant import com.example.learning3.ui.theme.colors.purple_theme_light_onTertiary import com.example.learning3.ui.theme.colors.purple_theme_light_onTertiaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_outline import com.example.learning3.ui.theme.colors.purple_theme_light_outlineVariant import com.example.learning3.ui.theme.colors.purple_theme_light_primary import com.example.learning3.ui.theme.colors.purple_theme_light_primaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_scrim import com.example.learning3.ui.theme.colors.purple_theme_light_secondary import com.example.learning3.ui.theme.colors.purple_theme_light_secondaryContainer import com.example.learning3.ui.theme.colors.purple_theme_light_surface import com.example.learning3.ui.theme.colors.purple_theme_light_surfaceTint import com.example.learning3.ui.theme.colors.purple_theme_light_surfaceVariant import com.example.learning3.ui.theme.colors.purple_theme_light_tertiary import com.example.learning3.ui.theme.colors.purple_theme_light_tertiaryContainer public val PurpleLightColors = lightColorScheme( primary = purple_theme_light_primary, onPrimary = purple_theme_light_onPrimary, primaryContainer = purple_theme_light_primaryContainer, onPrimaryContainer = purple_theme_light_onPrimaryContainer, secondary = purple_theme_light_secondary, onSecondary = purple_theme_light_onSecondary, secondaryContainer = purple_theme_light_secondaryContainer, onSecondaryContainer = purple_theme_light_onSecondaryContainer, tertiary = purple_theme_light_tertiary, onTertiary = purple_theme_light_onTertiary, tertiaryContainer = purple_theme_light_tertiaryContainer, onTertiaryContainer = purple_theme_light_onTertiaryContainer, error = purple_theme_light_error, errorContainer = purple_theme_light_errorContainer, onError = purple_theme_light_onError, onErrorContainer = purple_theme_light_onErrorContainer, background = purple_theme_light_background, onBackground = purple_theme_light_onBackground, surface = purple_theme_light_surface, onSurface = purple_theme_light_onSurface, surfaceVariant = purple_theme_light_surfaceVariant, onSurfaceVariant = purple_theme_light_onSurfaceVariant, outline = purple_theme_light_outline, inverseOnSurface = purple_theme_light_inverseOnSurface, inverseSurface = purple_theme_light_inverseSurface, inversePrimary = purple_theme_light_inversePrimary, surfaceTint = purple_theme_light_surfaceTint, outlineVariant = purple_theme_light_outlineVariant, scrim = purple_theme_light_scrim, ) public val PurpleDarkColors = darkColorScheme( primary = purple_theme_dark_primary, onPrimary = purple_theme_dark_onPrimary, primaryContainer = purple_theme_dark_primaryContainer, onPrimaryContainer = purple_theme_dark_onPrimaryContainer, secondary = purple_theme_dark_secondary, onSecondary = purple_theme_dark_onSecondary, secondaryContainer = purple_theme_dark_secondaryContainer, onSecondaryContainer = purple_theme_dark_onSecondaryContainer, tertiary = purple_theme_dark_tertiary, onTertiary = purple_theme_dark_onTertiary, tertiaryContainer = purple_theme_dark_tertiaryContainer, onTertiaryContainer = purple_theme_dark_onTertiaryContainer, error = purple_theme_dark_error, errorContainer = purple_theme_dark_errorContainer, onError = purple_theme_dark_onError, onErrorContainer = purple_theme_dark_onErrorContainer, background = purple_theme_dark_background, onBackground = purple_theme_dark_onBackground, surface = purple_theme_dark_surface, onSurface = purple_theme_dark_onSurface, surfaceVariant = purple_theme_dark_surfaceVariant, onSurfaceVariant = purple_theme_dark_onSurfaceVariant, outline = purple_theme_dark_outline, inverseOnSurface = purple_theme_dark_inverseOnSurface, inverseSurface = purple_theme_dark_inverseSurface, inversePrimary = purple_theme_dark_inversePrimary, surfaceTint = purple_theme_dark_surfaceTint, outlineVariant = purple_theme_dark_outlineVariant, scrim = purple_theme_dark_scrim, )
4
Kotlin
1
8
e1c3b5a59d3c91451210bcf3a5a3b4e9b3859ca6
7,704
NotesAppCompose
Apache License 2.0
apps/etterlatte-behandling/src/main/kotlin/metrics/OppgaveMetrikkerDao.kt
navikt
417,041,535
false
{"Kotlin": 4087916, "TypeScript": 876879, "Handlebars": 19431, "Shell": 9939, "HTML": 1776, "CSS": 598, "Dockerfile": 520}
package no.nav.etterlatte.metrics import no.nav.etterlatte.libs.common.oppgave.Status import no.nav.etterlatte.libs.database.toList import java.sql.ResultSet import java.util.UUID import javax.sql.DataSource class OppgaveMetrikkerDao(private val dataSource: DataSource) { fun hentOppgaveAntall(): OppgaveAntall { val alleOppgaver = hentAlleOppgaver() val aktive = alleOppgaver.filter { !Status.erAvsluttet(it.status) }.size val avsluttet = alleOppgaver.filter { Status.erAvsluttet(it.status) }.size val totalt = aktive + avsluttet return OppgaveAntall( totalt = totalt, aktive = aktive, avsluttet = avsluttet, ) } private fun hentAlleOppgaver(): List<OppgaveMetrikker> { dataSource.connection.use { val statement = it.prepareStatement( """ SELECT id, status FROM oppgave """.trimIndent(), ) return statement.executeQuery().toList { asOppgaveMetrikker() } } } private fun ResultSet.asOppgaveMetrikker(): OppgaveMetrikker { return OppgaveMetrikker( id = getObject("id") as UUID, status = Status.valueOf(getString("status")), ) } } data class OppgaveMetrikker( val id: UUID, val status: Status, ) data class OppgaveAntall( val totalt: Int, val aktive: Int, val avsluttet: Int, )
8
Kotlin
0
5
b5e8a7438c498c3bbd6170cfc4eb9818729ff6f7
1,530
pensjon-etterlatte-saksbehandling
MIT License
EasyRoom/app/src/main/java/pt/ipca/easyroom/screen/PaymentActivity.kt
TheAdventurersOrg
695,132,245
false
{"Kotlin": 112248}
package pt.ipca.easyroom.screen import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import pt.ipca.easyroom.R class PaymentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) } }
0
Kotlin
0
0
88bbd2a69b2e85acdf98e3733c1587c01cb55c96
336
EasyRoom
MIT License
base/build-system/gradle-api/src/main/java/com/android/build/api/sourcesets/AndroidSourceSet.kt
qiangxu1996
301,210,525
false
{"Gradle Kotlin DSL": 2, "Shell": 29, "Markdown": 39, "Batchfile": 10, "Text": 287, "Ignore List": 47, "Java": 4790, "INI": 19, "XML": 1725, "Gradle": 543, "Starlark": 149, "JAR Manifest": 3, "Kotlin": 1462, "Ant Build System": 3, "HTML": 6, "Makefile": 12, "XSLT": 6, "CSS": 10, "Git Attributes": 2, "Protocol Buffer": 35, "Java Properties": 43, "C++": 479, "RenderScript": 32, "C": 32, "Proguard": 29, "JavaScript": 2, "Checksums": 8, "Filterscript": 11, "Prolog": 1, "CMake": 3, "GLSL": 2, "AIDL": 6, "JSON": 53, "PureBasic": 1, "SVG": 201, "YAML": 4, "Python": 9, "Dockerfile": 2, "Emacs Lisp": 1, "FreeMarker": 173, "Fluent": 314}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.sourcesets import org.gradle.api.Action import org.gradle.api.Incubating import org.gradle.api.Named /** * An AndroidSourceSet represents a logical group of Java, aidl and RenderScript sources as well as * Android and non-Android (Java-style) resources. * * This interface is not currently usable. It is a work in progress. */ @Incubating interface AndroidSourceSet : Named { /** * Returns the Java resources which are to be copied into the javaResources output directory. * * @return the java resources. Never returns null. */ val resources: AndroidSourceDirectorySet /** * Configures the Java resources for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the java resources. * * @param action The action to use to configure the javaResources. * @return this */ fun resources(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * Returns the Java source which is to be compiled by the Java compiler into the class output * directory. * * @return the Java source. Never returns null. */ val java: AndroidSourceDirectorySet /** * Configures the Java source for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the Java source. * * @param action The action to use to configure the Java source. * @return this */ fun java(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * Returns the name of the compile configuration for this source set. * */ @Deprecated("use {@link #getImplementationConfigurationName()}") val compileConfigurationName: String /** * Returns the name of the runtime configuration for this source set. * */ @Deprecated("use {@link #getRuntimeOnlyConfigurationName()}") val packageConfigurationName: String /** * Returns the name of the compiled-only configuration for this source set. * */ @Deprecated("use {@link #getCompileOnlyConfigurationName()}") val providedConfigurationName: String /** Returns the name of the api configuration for this source set. */ val apiConfigurationName: String /** * Returns the name of the compileOnly configuration for this source set. */ val compileOnlyConfigurationName: String /** * Returns the name of the implemenation configuration for this source set. */ val implementationConfigurationName: String /** * Returns the name of the implemenation configuration for this source set. */ val runtimeOnlyConfigurationName: String /** * Returns the name of the wearApp configuration for this source set. */ val wearAppConfigurationName: String /** * Returns the name of the annotation processing tool classpath for this source set. */ val annotationProcessorConfigurationName: String /** * The Android Manifest file for this source set. * * @return the manifest. Never returns null. */ val manifest: AndroidSourceFile /** * Configures the location of the Android Manifest for this set. * * * The given action is used to configure the [AndroidSourceFile] which contains the * manifest. * * @param action The action to use to configure the Android Manifest. * @return this */ fun manifest(action: Action<AndroidSourceFile>): AndroidSourceSet /** * The Android Resources directory for this source set. * * @return the resources. Never returns null. */ val res: AndroidSourceDirectorySet /** * Configures the location of the Android Resources for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the resources. * * @param action The action to use to configure the Resources. * @return this */ fun res(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android Assets directory for this source set. * * @return the assets. Never returns null. */ val assets: AndroidSourceDirectorySet /** * Configures the location of the Android Assets for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the assets. * * @param action The action to use to configure the Assets. * @return this */ fun assets(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android AIDL source directory for this source set. * * @return the source. Never returns null. */ val aidl: AndroidSourceDirectorySet /** * Configures the location of the Android AIDL source for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the AIDL source. * * @param action The action to use to configure the AIDL source. * @return this */ fun aidl(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android RenderScript source directory for this source set. * * @return the source. Never returns null. */ val renderscript: AndroidSourceDirectorySet /** * Configures the location of the Android RenderScript source for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the Renderscript source. * * @param action The action to use to configure the Renderscript source. * @return this */ fun renderscript(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android JNI source directory for this source set. * * @return the source. Never returns null. */ val jni: AndroidSourceDirectorySet /** * Configures the location of the Android JNI source for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the JNI source. * * @param action The action to use to configure the JNI source. * @return this */ fun jni(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android JNI libs directory for this source set. * * @return the libs. Never returns null. */ val jniLibs: AndroidSourceDirectorySet /** * Configures the location of the Android JNI libs for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the JNI libs. * * @param action The action to use to configure the JNI libs. * @return this */ fun jniLibs(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * The Android shaders directory for this source set. * * @return the shaders. Never returns null. */ val shaders: AndroidSourceDirectorySet /** * Configures the location of the Android shaders for this set. * * * The given action is used to configure the [AndroidSourceDirectorySet] which contains * the shaders. * * @param action The action to use to configure the shaders. * @return this */ fun shaders(action: Action<AndroidSourceDirectorySet>): AndroidSourceSet /** * Sets the root of the source sets to a given path. * * All entries of the source set are located under this root directory. * * @param path the root directory. * @return this */ fun setRoot(path: String): AndroidSourceSet }
1
null
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
8,435
vmtrace
Apache License 2.0
src/main/kotlin/firebase/admin/firestore/Firestore.kt
theerasan
148,879,943
false
{"Kotlin": 30995, "JavaScript": 19437}
package firebase.admin.firestore /** * The Firestore client represents a Firestore Database and is the entry point for all Firestore operations. * @see <a href="https://cloud.google.com/nodejs/docs/reference/firestore/0.10.x/Firestore">Firestore</a> */ external interface Firestore { val app: dynamic //The app associated with this Firestore service instance fun batch(): WriteBatch //Creates a write batch, used for performing multiple writes as a single atomic operation fun collection(collectionPath: String): CollectionReference }
3
Kotlin
1
12
e937799a04288207347a0204d0d44bc37e62e767
550
kotlin-firebase-interface
MIT License
MomoPlantsParent/app/src/main/java/com/johndev/momoplantsparent/common/dataAccess/OnOrderListener.kt
Johnmorales26
614,629,687
false
{"Kotlin": 249710, "HTML": 7020, "JavaScript": 5252, "CSS": 3780}
package com.johndev.momoplantsparent.common.dataAccess import com.johndev.momoplantsparent.common.entities.OrderEntity interface OnOrderListener { fun onStartChat(orderEntity: OrderEntity) fun onStatusChange(orderEntity: OrderEntity) }
0
Kotlin
0
0
ed586134890c4257a703d92c4890a9b72ebab8ca
247
Momo_Plants
W3C Software Notice and License (2002-12-31)
sykepenger-model/src/main/kotlin/no/nav/helse/person/Aktivitetslogg.kt
navikt
193,907,367
false
null
package no.nav.helse.person import no.nav.helse.hendelser.Hendelseskontekst import no.nav.helse.hendelser.Periode import no.nav.helse.hendelser.Periode.Companion.grupperSammenhengendePerioder import no.nav.helse.person.Aktivitetslogg.Aktivitet.Behov import no.nav.helse.person.Aktivitetslogg.Aktivitet.Etterlevelse import no.nav.helse.person.Aktivitetslogg.Aktivitet.Etterlevelse.TidslinjegrunnlagVisitor.Periode.Companion.dager import no.nav.helse.person.Bokstav.BOKSTAV_A import no.nav.helse.person.Ledd.* import no.nav.helse.person.Ledd.Companion.ledd import no.nav.helse.person.Paragraf.* import no.nav.helse.person.Punktum.Companion.punktum import no.nav.helse.serde.reflection.AktivitetsloggMap import no.nav.helse.utbetalingslinjer.Utbetaling.Utbetalingtype import no.nav.helse.utbetalingstidslinje.Utbetalingstidslinje import no.nav.helse.økonomi.Inntekt import no.nav.helse.økonomi.Prosent import no.nav.helse.økonomi.Økonomi import java.time.LocalDate import java.time.LocalDateTime import java.time.Year import java.time.YearMonth import java.time.format.DateTimeFormatter import java.util.* // Understands issues that arose when analyzing a JSON message // Implements Collecting Parameter in Refactoring by <NAME> // Implements Visitor pattern to traverse the messages class Aktivitetslogg( private var forelder: Aktivitetslogg? = null ) : IAktivitetslogg { internal val aktiviteter = mutableListOf<Aktivitet>() private val kontekster = mutableListOf<Aktivitetskontekst>() // Doesn't need serialization internal fun accept(visitor: AktivitetsloggVisitor) { visitor.preVisitAktivitetslogg(this) aktiviteter.forEach { it.accept(visitor) } visitor.postVisitAktivitetslogg(this) } override fun info(melding: String, vararg params: Any?) { add(Aktivitet.Info(kontekster.toSpesifikk(), String.format(melding, *params))) } override fun warn(melding: String, vararg params: Any?) { add(Aktivitet.Warn(kontekster.toSpesifikk(), String.format(melding, *params))) } override fun behov(type: Behov.Behovtype, melding: String, detaljer: Map<String, Any?>) { add(Behov(type, kontekster.toSpesifikk(), melding, detaljer)) } override fun error(melding: String, vararg params: Any?) { add(Aktivitet.Error(kontekster.toSpesifikk(), String.format(melding, *params))) } override fun severe(melding: String, vararg params: Any?): Nothing { add(Aktivitet.Severe(kontekster.toSpesifikk(), String.format(melding, *params))) throw AktivitetException(this) } override fun juridiskVurdering(melding: String, vurdering: Etterlevelse.Vurderingsresultat) { add(Etterlevelse(kontekster.toSpesifikk(), melding, vurdering)) } private fun add(aktivitet: Aktivitet) { this.aktiviteter.add(aktivitet) forelder?.add(aktivitet) } private fun MutableList<Aktivitetskontekst>.toSpesifikk() = this.map { it.toSpesifikkKontekst() } override fun hasActivities() = info().isNotEmpty() || hasWarningsOrWorse() || behov().isNotEmpty() override fun hasWarningsOrWorse() = warn().isNotEmpty() || hasErrorsOrWorse() override fun hasErrorsOrWorse() = error().isNotEmpty() || severe().isNotEmpty() override fun barn() = Aktivitetslogg(this) override fun toString() = this.aktiviteter.map { it.inOrder() }.joinToString(separator = "\n") { it } override fun aktivitetsteller() = aktiviteter.size override fun kontekst(kontekst: Aktivitetskontekst) { kontekster.add(kontekst) } override fun kontekst(person: Person) { forelder = person.aktivitetslogg kontekst(person as Aktivitetskontekst) } override fun toMap(): Map<String, List<Map<String, Any>>> = AktivitetsloggMap(this).toMap() internal fun logg(vararg kontekst: Aktivitetskontekst): Aktivitetslogg { return Aktivitetslogg(this).also { it.aktiviteter.addAll(this.aktiviteter.filter { aktivitet -> kontekst.any { it in aktivitet } }) } } internal fun logg(vararg kontekst: String): Aktivitetslogg { return Aktivitetslogg(this).also { aktivitetslogg -> aktivitetslogg.aktiviteter.addAll(this.aktiviteter.filter { aktivitet -> kontekst.any { kontekst -> kontekst in aktivitet.kontekster.map { it.kontekstType } } }) } } override fun kontekster() = aktiviteter .groupBy { it.kontekst(null) } .map { Aktivitetslogg(this).apply { aktiviteter.addAll(it.value) } } override fun hendelseskontekster(): Map<String, String> { return kontekster .map(Aktivitetskontekst::toSpesifikkKontekst) .filter { it.kontekstType in MODELL_KONTEKSTER } .map(SpesifikkKontekst::kontekstMap) .fold(mapOf()) { result, kontekst -> result + kontekst } } override fun hendelseskontekst(): Hendelseskontekst = Hendelseskontekst(hendelseskontekster()) private fun info() = Aktivitet.Info.filter(aktiviteter) internal fun warn() = Aktivitet.Warn.filter(aktiviteter) override fun behov() = Behov.filter(aktiviteter) private fun error() = Aktivitet.Error.filter(aktiviteter) private fun severe() = Aktivitet.Severe.filter(aktiviteter) override fun juridiskeVurderinger() = Aktivitet.Etterlevelse.filter(aktiviteter) companion object { private val MODELL_KONTEKSTER: Array<String> = arrayOf("Person", "Arbeidsgiver", "Vedtaksperiode") } class AktivitetException internal constructor(private val aktivitetslogg: Aktivitetslogg) : RuntimeException(aktivitetslogg.toString()) { fun kontekst() = aktivitetslogg.kontekster.fold(mutableMapOf<String, String>()) { result, kontekst -> result.apply { putAll(kontekst.toSpesifikkKontekst().kontekstMap) } } fun aktivitetslogg() = aktivitetslogg } sealed class Aktivitet( private val alvorlighetsgrad: Int, private val label: Char, private var melding: String, private val tidsstempel: String, internal val kontekster: List<SpesifikkKontekst> ) : Comparable<Aktivitet> { private companion object { private val tidsstempelformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") } fun kontekst(): Map<String, String> = kontekst(null) internal fun kontekst(typer: Array<String>?): Map<String, String> = kontekster .filter { typer == null || it.kontekstType in typer } .fold(mapOf()) { result, kontekst -> result + kontekst.kontekstMap } override fun compareTo(other: Aktivitet) = this.tidsstempel.compareTo(other.tidsstempel) .let { if (it == 0) other.alvorlighetsgrad.compareTo(this.alvorlighetsgrad) else it } internal fun inOrder() = label + "\t" + this.toString() override fun toString() = label + " \t" + tidsstempel + " \t" + melding + meldingerString() private fun meldingerString(): String { return kontekster.joinToString(separator = "") { " (${it.melding()})" } } internal abstract fun accept(visitor: AktivitetsloggVisitor) operator fun contains(kontekst: Aktivitetskontekst) = kontekst.toSpesifikkKontekst() in kontekster internal class Info( kontekster: List<SpesifikkKontekst>, private val melding: String, private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(0, 'I', melding, tidsstempel, kontekster) { companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Info> { return aktiviteter.filterIsInstance<Info>() } } override fun accept(visitor: AktivitetsloggVisitor) { visitor.visitInfo(kontekster, this, melding, tidsstempel) } } internal class Warn( kontekster: List<SpesifikkKontekst>, private val melding: String, private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(25, 'W', melding, tidsstempel, kontekster) { companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Warn> { return aktiviteter.filterIsInstance<Warn>() } } override fun accept(visitor: AktivitetsloggVisitor) { visitor.visitWarn(kontekster, this, melding, tidsstempel) } } class Behov( val type: Behovtype, kontekster: List<SpesifikkKontekst>, private val melding: String, private val detaljer: Map<String, Any?> = emptyMap(), private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(50, 'N', melding, tidsstempel, kontekster) { companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Behov> { return aktiviteter.filterIsInstance<Behov>() } internal fun utbetalingshistorikk( aktivitetslogg: IAktivitetslogg, periode: Periode ) { aktivitetslogg.behov( Behovtype.Sykepengehistorikk, "Trenger sykepengehistorikk fra Infotrygd", mapOf( "historikkFom" to periode.start.toString(), "historikkTom" to periode.endInclusive.toString() ) ) } internal fun foreldrepenger(aktivitetslogg: IAktivitetslogg) { aktivitetslogg.behov( Behovtype.Foreldrepenger, "Trenger informasjon om foreldrepengeytelser fra FPSAK" ) } internal fun pleiepenger(aktivitetslogg: IAktivitetslogg, periode: Periode) { aktivitetslogg.behov( Behovtype.Pleiepenger, "Trenger informasjon om pleiepengeytelser fra Infotrygd", mapOf( "pleiepengerFom" to periode.start.toString(), "pleiepengerTom" to periode.endInclusive.toString() ) ) } internal fun omsorgspenger(aktivitetslogg: IAktivitetslogg, periode: Periode) { aktivitetslogg.behov( Behovtype.Omsorgspenger, "Trenger informasjon om omsorgspengerytelser fra Infotrygd", mapOf( "omsorgspengerFom" to periode.start.toString(), "omsorgspengerTom" to periode.endInclusive.toString() ) ) } internal fun opplæringspenger(aktivitetslogg: IAktivitetslogg, periode: Periode) { aktivitetslogg.behov( Behovtype.Opplæringspenger, "Trenger informasjon om opplæringspengerytelser fra Infotrygd", mapOf( "opplæringspengerFom" to periode.start.toString(), "opplæringspengerTom" to periode.endInclusive.toString() ) ) } internal fun institusjonsopphold(aktivitetslogg: IAktivitetslogg, periode: Periode) { aktivitetslogg.behov( Behovtype.Institusjonsopphold, "Trenger informasjon om institusjonsopphold fra Inst2", mapOf( "institusjonsoppholdFom" to periode.start.toString(), "institusjonsoppholdTom" to periode.endInclusive.toString() ) ) } internal fun dødsinformasjon(aktivitetslogg: IAktivitetslogg) { aktivitetslogg.behov( Behovtype.Dødsinfo, "Trenger informasjon om dødsdato fra PDL" ) } internal fun inntekterForSammenligningsgrunnlag( aktivitetslogg: IAktivitetslogg, beregningStart: YearMonth, beregningSlutt: YearMonth ) { aktivitetslogg.behov( Behovtype.InntekterForSammenligningsgrunnlag, "Trenger inntekter for sammenligningsgrunnlag", mapOf( "beregningStart" to beregningStart.toString(), "beregningSlutt" to beregningSlutt.toString() ) ) } internal fun inntekterForSykepengegrunnlag( aktivitetslogg: IAktivitetslogg, beregningStart: YearMonth, beregningSlutt: YearMonth ) { aktivitetslogg.behov( Behovtype.InntekterForSykepengegrunnlag, "Trenger inntekter for sykepengegrunnlag", mapOf( "beregningStart" to beregningStart.toString(), "beregningSlutt" to beregningSlutt.toString() ) ) } internal fun arbeidsforhold(aktivitetslogg: IAktivitetslogg) { aktivitetslogg.behov(Behovtype.ArbeidsforholdV2, "Trenger informasjon om arbeidsforhold") } internal fun dagpenger(aktivitetslogg: IAktivitetslogg, fom: LocalDate, tom: LocalDate) { aktivitetslogg.behov( Behovtype.Dagpenger, "Trenger informasjon om dagpenger", mapOf( "periodeFom" to fom.toString(), "periodeTom" to tom.toString() ) ) } internal fun arbeidsavklaringspenger(aktivitetslogg: IAktivitetslogg, fom: LocalDate, tom: LocalDate) { aktivitetslogg.behov( Behovtype.Arbeidsavklaringspenger, "Trenger informasjon om arbeidsavklaringspenger", mapOf( "periodeFom" to fom.toString(), "periodeTom" to tom.toString() ) ) } internal fun medlemskap(aktivitetslogg: IAktivitetslogg, fom: LocalDate, tom: LocalDate) { aktivitetslogg.behov( Behovtype.Medlemskap, "Trenger informasjon om medlemskap", mapOf( "medlemskapPeriodeFom" to fom.toString(), "medlemskapPeriodeTom" to tom.toString() ) ) } internal fun godkjenning( aktivitetslogg: IAktivitetslogg, periodeFom: LocalDate, periodeTom: LocalDate, skjæringstidspunkt: LocalDate, vedtaksperiodeaktivitetslogg: Aktivitetslogg, periodetype: Periodetype, utbetalingtype: Utbetalingtype, inntektskilde: Inntektskilde, aktiveVedtaksperioder: List<AktivVedtaksperiode>, orgnummereMedAktiveArbeidsforhold: List<String>, arbeidsforholdId: String?, ) { aktivitetslogg.behov( Behovtype.Godkjenning, "Forespør godkjenning fra saksbehandler", mapOf( "periodeFom" to periodeFom.toString(), "periodeTom" to periodeTom.toString(), "skjæringstidspunkt" to skjæringstidspunkt.toString(), "periodetype" to periodetype.name, "utbetalingtype" to utbetalingtype.name, "inntektskilde" to inntektskilde.name, "warnings" to Aktivitetslogg().apply { aktiviteter.addAll(vedtaksperiodeaktivitetslogg.warn()) }.toMap(), "aktiveVedtaksperioder" to aktiveVedtaksperioder.map(AktivVedtaksperiode::toMap), "orgnummereMedAktiveArbeidsforhold" to orgnummereMedAktiveArbeidsforhold, "arbeidsforholdId" to arbeidsforholdId ) ) } } fun detaljer() = detaljer override fun accept(visitor: AktivitetsloggVisitor) { visitor.visitBehov(kontekster, this, type, melding, detaljer, tidsstempel) } enum class Behovtype { Sykepengehistorikk, SykepengehistorikkForFeriepenger, Foreldrepenger, Pleiepenger, Omsorgspenger, Opplæringspenger, Institusjonsopphold, EgenAnsatt, Godkjenning, Simulering, Utbetaling, InntekterForSammenligningsgrunnlag, InntekterForSykepengegrunnlag, @Deprecated("Behovet er ikke i bruk, men beholdes for derserialisering av aktivitetsloggen") Opptjening, Dagpenger, Arbeidsavklaringspenger, Medlemskap, Dødsinfo, ArbeidsforholdV2 } } internal class Error( kontekster: List<SpesifikkKontekst>, private val melding: String, private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(75, 'E', melding, tidsstempel, kontekster) { companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Error> { return aktiviteter.filterIsInstance<Error>() } } override fun accept(visitor: AktivitetsloggVisitor) { visitor.visitError(kontekster, this, melding, tidsstempel) } } internal class Severe( kontekster: List<SpesifikkKontekst>, private val melding: String, private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(100, 'S', melding, tidsstempel, kontekster) { companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Severe> { return aktiviteter.filterIsInstance<Severe>() } } override fun accept(visitor: AktivitetsloggVisitor) { visitor.visitSevere(kontekster, this, melding, tidsstempel) } } class Etterlevelse internal constructor( kontekster: List<SpesifikkKontekst>, private val melding: String, private val vurdering: Vurderingsresultat, private val tidsstempel: String = LocalDateTime.now().format(tidsstempelformat) ) : Aktivitet(100, 'J', melding, tidsstempel, kontekster) { override fun accept(visitor: AktivitetsloggVisitor) { visitor.preVisitEtterlevelse(kontekster, this, melding, vurdering, tidsstempel) vurdering.accept(visitor) visitor.postVisitEtterlevelse(kontekster, this, melding, vurdering, tidsstempel) } internal companion object { fun filter(aktiviteter: List<Aktivitet>) = aktiviteter.filterIsInstance<Etterlevelse>() } class Vurderingsresultat private constructor( private val oppfylt: Boolean, private val versjon: LocalDate, private val paragraf: Paragraf, private val ledd: Ledd, private val punktum: List<Punktum>, private val bokstaver: List<Bokstav> = emptyList(), private val inputdata: Map<Any, Any?>, private val outputdata: Map<Any, Any?> ) { internal fun accept(visitor: AktivitetsloggVisitor) { visitor.visitVurderingsresultat(oppfylt, versjon, paragraf, ledd, punktum, bokstaver, outputdata, inputdata) } override fun toString(): String { return """ Juridisk vurdering: oppfylt: $oppfylt versjon: $versjon paragraf: $paragraf ledd: $ledd input: ${ inputdata.map { (key, value) -> "$key: $value" } } output: ${ outputdata.map { (key, value) -> "$key: $value" } } """ } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Vurderingsresultat || javaClass != other.javaClass) return false return oppfylt == other.oppfylt && versjon == other.versjon && paragraf == other.paragraf && ledd == other.ledd && inputdata == other.inputdata && outputdata == other.outputdata } override fun hashCode(): Int { var result = oppfylt.hashCode() result = 31 * result + versjon.hashCode() result = 31 * result + paragraf.hashCode() result = 31 * result + ledd.hashCode() result = 31 * result + inputdata.hashCode() result = 31 * result + outputdata.hashCode() return result } internal companion object { internal fun filter(aktiviteter: List<Aktivitet>): List<Etterlevelse> { return aktiviteter.filterIsInstance<Etterlevelse>() } /** * Vurdering av medlemskap * * Lovdata: [lenke](https://lovdata.no/dokument/NL/lov/1997-02-28-19/KAPITTEL_2-2#KAPITTEL_2-2) * * @param oppfylt hvorvidt sykmeldte har oppfylt krav til medlemskap i folketrygden */ @Suppress("UNUSED_PARAMETER") internal fun IAktivitetslogg.`§2`(oppfylt: Boolean) {} /** * Vurdering av opptjeningstid * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-2) * * @param oppfylt hvorvidt sykmeldte har oppfylt krav om opptjeningstid * @param skjæringstidspunkt dato som antall opptjeningsdager regnes mot * @param tilstrekkeligAntallOpptjeningsdager antall opptjeningsdager som kreves for at vilkåret skal være [oppfylt] * @param arbeidsforhold hvilke arbeidsforhold det er tatt utgangspunkt i ved beregning av opptjeningstid * @param antallOpptjeningsdager antall opptjeningsdager sykmeldte faktisk har på [skjæringstidspunkt] */ internal fun IAktivitetslogg.`§8-2 ledd 1`( oppfylt: Boolean, skjæringstidspunkt: LocalDate, tilstrekkeligAntallOpptjeningsdager: Int, arbeidsforhold: List<Map<String, Any?>>, antallOpptjeningsdager: Int ) { juridiskVurdering( "", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2020, 6, 12), paragraf = PARAGRAF_8_2, ledd = 1.ledd, punktum = 1.punktum, inputdata = mapOf( "skjæringstidspunkt" to skjæringstidspunkt, "tilstrekkeligAntallOpptjeningsdager" to tilstrekkeligAntallOpptjeningsdager, "arbeidsforhold" to arbeidsforhold ), outputdata = mapOf( "antallOpptjeningsdager" to antallOpptjeningsdager ) ) ) } /** * Vurdering av rett til sykepenger ved fylte 70 år * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-3) * * @param oppfylt hvorvidt sykmeldte har fylt 70 år. Oppfylt så lenge sykmeldte ikke er 70 år eller eldre * @param syttiårsdagen dato sykmeldte fyller 70 år * @param vurderingFom fra-og-med-dato [oppfylt]-vurderingen gjelder for * @param vurderingTom til-og-med-dato [oppfylt]-vurderingen gjelder for * @param tidslinjeFom fra-og-med-dato vurderingen gjøres for * @param tidslinjeTom til-og-med-dato vurderingen gjøres for * @param avvisteDager alle dager vurderingen ikke er [oppfylt] for. Tom dersom sykmeldte ikke fyller 70 år mellom [tidslinjeFom] og [tidslinjeTom] */ internal fun IAktivitetslogg.`§8-3 ledd 1 punktum 2`( oppfylt: Boolean, syttiårsdagen: LocalDate, vurderingFom: LocalDate, vurderingTom: LocalDate, tidslinjeFom: LocalDate, tidslinjeTom: LocalDate, avvisteDager: List<LocalDate> ) { juridiskVurdering( "", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2011, 12, 16), paragraf = PARAGRAF_8_3, ledd = 1.ledd, punktum = 2.punktum, inputdata = mapOf( "syttiårsdagen" to syttiårsdagen, "vurderingFom" to vurderingFom, "vurderingTom" to vurderingTom, "tidslinjeFom" to tidslinjeFom, "tidslinjeTom" to tidslinjeTom ), outputdata = mapOf( "avvisteDager" to avvisteDager.grupperSammenhengendePerioder() ) ) ) } /** * Vurdering av krav til minimum inntekt * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-3) * * @param oppfylt hvorvidt sykmeldte har inntekt lik eller større enn minimum inntekt * @param skjæringstidspunkt dato som minimum inntekt settes ut fra * @param grunnlagForSykepengegrunnlag total inntekt på tvers av alle relevante arbeidsgivere * @param minimumInntekt beløpet som settes basert på [skjæringstidspunkt], og som vurderes mot [grunnlagForSykepengegrunnlag] */ internal fun IAktivitetslogg.`§8-3 ledd 2 punktum 1`( oppfylt: Boolean, skjæringstidspunkt: LocalDate, grunnlagForSykepengegrunnlag: Inntekt, minimumInntekt: Inntekt ) { juridiskVurdering("", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2011, 12, 16), paragraf = PARAGRAF_8_3, ledd = 2.ledd, punktum = 1.punktum, inputdata = mapOf( "skjæringstidspunkt" to skjæringstidspunkt, "grunnlagForSykepengegrunnlag" to grunnlagForSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig }, "minimumInntekt" to minimumInntekt.reflection { årlig, _, _, _ -> årlig } ), outputdata = emptyMap() ) ) } /** * Vurdering av maksimalt sykepengegrunnlag * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-10) * * @param oppfylt alltid oppfylt * @param funnetRelevant dersom hjemlen slår inn ved at [grunnlagForSykepengegrunnlag] blir begrenset til [maksimaltSykepengegrunnlag] * @param maksimaltSykepengegrunnlag maksimalt årlig beløp utbetaling skal beregnes ut fra * @param skjæringstidspunkt dato [maksimaltSykepengegrunnlag] settes ut fra * @param grunnlagForSykepengegrunnlag total inntekt på tvers av alle relevante arbeidsgivere */ internal fun IAktivitetslogg.`§8-10 ledd 2 punktum 1`( oppfylt: Boolean, funnetRelevant: Boolean, maksimaltSykepengegrunnlag: Inntekt, skjæringstidspunkt: LocalDate, grunnlagForSykepengegrunnlag: Inntekt ) { juridiskVurdering( "", Vurderingsresultat( oppfylt, versjon = LocalDate.of(2020, 1, 1), PARAGRAF_8_10, LEDD_2, 1.punktum, inputdata = mapOf( "maksimaltSykepengegrunnlag" to maksimaltSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig }, "skjæringstidspunkt" to skjæringstidspunkt, "grunnlagForSykepengegrunnlag" to grunnlagForSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig } ), outputdata = mapOf( "funnetRelevant" to funnetRelevant ) ) ) } //TODO: Hvordan skal denne kunne legges inn??? @Suppress("UNUSED_PARAMETER") internal fun IAktivitetslogg.`§8-10 ledd 3`(oppfylt: Boolean) {} internal fun IAktivitetslogg.`§8-11 første ledd`() { juridiskVurdering( "", Vurderingsresultat( oppfylt = true, paragraf = PARAGRAF_8_11, ledd = LEDD_1, punktum = 1.punktum, versjon = FOLKETRYGDLOVENS_OPPRINNELSESDATO, inputdata = emptyMap(), outputdata = emptyMap() ) ) } /** * Vurdering av maksimalt antall sykepengedager * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-12) * * @param oppfylt **true** dersom vedtaksperioden ikke inneholder [avvisteDager] som følge av at man har nådd [maksdato] * @param fom første NAV-dag i et helt sykepengeforløp dersom vilkåret er [oppfylt], ellers første avviste dag * @param tom hittil siste NAV-dag i et helt sykepengeforløp dersom vilkåret er [oppfylt], ellers siste avviste dag * @param tidslinjegrunnlag tidslinje det tas utgangspunkt i når man beregner [gjenståendeSykedager], [forbrukteSykedager] og [maksdato] * @param gjenståendeSykedager antall gjenstående sykepengedager ved siste utbetalte dag. 0 dersom vilkåret ikke er [oppfylt] * @param forbrukteSykedager antall forbrukte sykepengedager * @param maksdato dato for opphør av rett til sykepenger * @param avvisteDager dager vilkåret ikke er [oppfylt] for */ internal fun IAktivitetslogg.`§8-12 ledd 1 punktum 1`( oppfylt: Boolean, fom: LocalDate, tom: LocalDate, tidslinjegrunnlag: List<Utbetalingstidslinje>, beregnetTidslinje: Utbetalingstidslinje, gjenståendeSykedager: Int, forbrukteSykedager: Int, maksdato: LocalDate, avvisteDager: List<LocalDate> ) { juridiskVurdering( "§8-12 ledd 1", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2021, 5, 21), paragraf = PARAGRAF_8_12, ledd = 1.ledd, punktum = 1.punktum, inputdata = mapOf( "fom" to fom, "tom" to tom, "tidslinjegrunnlag" to tidslinjegrunnlag.map { TidslinjegrunnlagVisitor(it).dager() }, "beregnetTidslinje" to TidslinjegrunnlagVisitor(beregnetTidslinje).dager() ), outputdata = mapOf( "gjenståendeSykedager" to gjenståendeSykedager, "forbrukteSykedager" to forbrukteSykedager, "maksdato" to maksdato, "avvisteDager" to avvisteDager.grupperSammenhengendePerioder() ) ) ) } /** * Vurdering av ny rett til sykepenger * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-12) * * Merk: ikke noe oppfylt-parameter, da denne alltid er oppfylt, fordi vurderingen kun gjøres når ny rett til sykepenger oppnås * @param dato dato vurdering av hjemmel gjøres * @param tilstrekkeligOppholdISykedager antall dager med opphold i ytelsen som nødvendig for å oppnå ny rett til sykepenger * @param tidslinjegrunnlag alle tidslinjer det tas utgangspunkt i ved bygging av [beregnetTidslinje] * @param beregnetTidslinje tidslinje det tas utgangspunkt i ved utbetaling for aktuell vedtaksperiode */ internal fun IAktivitetslogg.`§8-12 ledd 2`( dato: LocalDate, tilstrekkeligOppholdISykedager: Int, tidslinjegrunnlag: List<Utbetalingstidslinje>, beregnetTidslinje: Utbetalingstidslinje ) { juridiskVurdering( "§8-12 ledd 2", Vurderingsresultat( oppfylt = true, versjon = LocalDate.of(2021, 5, 21), paragraf = PARAGRAF_8_12, ledd = 2.ledd, punktum = (1..2).punktum, inputdata = mapOf( "dato" to dato, "tilstrekkeligOppholdISykedager" to tilstrekkeligOppholdISykedager, "tidslinjegrunnlag" to tidslinjegrunnlag.map { TidslinjegrunnlagVisitor(it).dager() }, "beregnetTidslinje" to TidslinjegrunnlagVisitor(beregnetTidslinje).dager() ), outputdata = emptyMap() ) ) } /** * Vurdering av graderte sykepenger * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-13) * * @param oppfylt **true** dersom uføregraden er minst 20% * @param avvisteDager dager som ikke møter kriterie for [oppfylt] */ internal fun IAktivitetslogg.`§8-13 ledd 1`(oppfylt: Boolean, avvisteDager: List<LocalDate>) { juridiskVurdering( "", Vurderingsresultat( oppfylt = oppfylt, paragraf = PARAGRAF_8_13, ledd = LEDD_1, punktum = (1..2).punktum, versjon = FOLKETRYGDLOVENS_OPPRINNELSESDATO, inputdata = mapOf("avvisteDager" to avvisteDager), outputdata = emptyMap() ) ) } /** * Fastsettelse av dekningsgrunnlag * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-16) * * Merk: Alltid oppfylt * * @param dekningsgrad hvor stor andel av inntekten det ytes sykepenger av * @param inntekt inntekt for aktuell arbeidsgiver * @param dekningsgrunnlag maks dagsats før reduksjon til 6G og reduksjon for sykmeldingsgrad */ internal fun IAktivitetslogg.`§8-16 ledd 1`( dekningsgrad: Double, inntekt: Double, dekningsgrunnlag: Double ) { juridiskVurdering( "", Vurderingsresultat( true, versjon = FOLKETRYGDLOVENS_OPPRINNELSESDATO, paragraf = PARAGRAF_8_16, ledd = LEDD_1, punktum = 1.punktum, inputdata = mapOf( "dekningsgrad" to dekningsgrad, "inntekt" to inntekt ), outputdata = mapOf( "dekningsgrunnlag" to dekningsgrunnlag ) ) ) } /** * Vurdering av når * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-16) * * Merk: Alltid oppfylt * * @param arbeidsgiverperiode alle arbeidsgiverperiode-dager * @param førsteNavdag første dag NAV skal utbetale */ internal fun IAktivitetslogg.`§8-17 ledd 1 bokstav a`( arbeidsgiverperiode: List<LocalDate>, førsteNavdag: LocalDate ) { juridiskVurdering( "", Vurderingsresultat( oppfylt = true, versjon = LocalDate.of(2018, 1, 1), paragraf = PARAGRAF_8_17, ledd = LEDD_1, punktum = 1.punktum, bokstaver = listOf(BOKSTAV_A), inputdata = mapOf( "førsteNavdag" to førsteNavdag, "arbeidsgiverperioder" to arbeidsgiverperiode.grupperSammenhengendePerioder().map { mapOf("fom" to it.start, "tom" to it.endInclusive) } ), outputdata = emptyMap() ) ) } @Suppress("UNUSED_PARAMETER") internal fun IAktivitetslogg.`§8-17 ledd 2`(oppfylt: Boolean) {} //Legges inn på ferie/permisjonsdager i utbetalingstidslinje, med periodene av ferie/permisjon som input @Suppress("UNUSED_PARAMETER") internal fun IAktivitetslogg.`§8-28 ledd 3 bokstav a`( oppfylt: Boolean, inntekter: List<Inntektshistorikk.Skatt>, inntekterSisteTreMåneder: List<Inntektshistorikk.Skatt>, grunnlagForSykepengegrunnlag: Inntekt ) { } /** * Fastsettelse av sykepengegrunnlaget * * Lovdata: [lenke](https://lovdata.no/lov/1997-02-28-19/%C2%A78-30) * * Merk: Alltid oppfylt * * @param grunnlagForSykepengegrunnlagPerArbeidsgiver beregnet inntekt per arbeidsgiver * @param grunnlagForSykepengegrunnlag beregnet inntekt på tvers av arbeidsgivere */ internal fun IAktivitetslogg.`§8-30 ledd 1`( grunnlagForSykepengegrunnlagPerArbeidsgiver: Map<String, Inntekt>, grunnlagForSykepengegrunnlag: Inntekt ) { val beregnetMånedsinntektPerArbeidsgiver = grunnlagForSykepengegrunnlagPerArbeidsgiver .mapValues { it.value.reflection { _, månedlig, _, _ -> månedlig } } juridiskVurdering( "", Vurderingsresultat( oppfylt = true, versjon = LocalDate.of(2019, 1, 1), paragraf = PARAGRAF_8_30, ledd = LEDD_1, punktum = 1.punktum, inputdata = mapOf( "beregnetMånedsinntektPerArbeidsgiver" to beregnetMånedsinntektPerArbeidsgiver ), outputdata = mapOf( "grunnlagForSykepengegrunnlag" to grunnlagForSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig } ) ) ) } internal fun IAktivitetslogg.`§8-30 ledd 2 punktum 1`( oppfylt: Boolean, maksimaltTillattAvvikPåÅrsinntekt: Prosent, grunnlagForSykepengegrunnlag: Inntekt, sammenligningsgrunnlag: Inntekt, avvik: Prosent ) { juridiskVurdering("Vurdering av avviksprosent ved inntektsvurdering", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2017, 4, 5), paragraf = PARAGRAF_8_30, ledd = 2.ledd, punktum = 1.punktum, inputdata = mapOf( "maksimaltTillattAvvikPåÅrsinntekt" to maksimaltTillattAvvikPåÅrsinntekt.prosent(), "grunnlagForSykepengegrunnlag" to grunnlagForSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig }, "sammenligningsgrunnlag" to sammenligningsgrunnlag.reflection { årlig, _, _, _ -> årlig } ), outputdata = mapOf( "avvik" to avvik.prosent() ) )) } internal fun IAktivitetslogg.`§8-33 ledd 1`() {} @Suppress("UNUSED_PARAMETER") internal fun IAktivitetslogg.`§8-33 ledd 3`( grunnlagForFeriepenger: Int, opptjeningsår: Year, prosentsats: Double, alder: Int, feriepenger: Double ) { } internal fun IAktivitetslogg.`§8-51 ledd 2`( oppfylt: Boolean, skjæringstidspunkt: LocalDate, grunnlagForSykepengegrunnlag: Inntekt, minimumInntekt: Inntekt ) { juridiskVurdering("", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2011, 12, 16), paragraf = PARAGRAF_8_51, ledd = LEDD_2, punktum = 1.punktum, inputdata = mapOf( "skjæringstidspunkt" to skjæringstidspunkt, "grunnlagForSykepengegrunnlag" to grunnlagForSykepengegrunnlag.reflection { årlig, _, _, _ -> årlig }, "minimumInntekt" to minimumInntekt.reflection { årlig, _, _, _ -> årlig } ), outputdata = emptyMap() ) ) } internal fun IAktivitetslogg.`§8-51 ledd 3`( oppfylt: Boolean, maksSykepengedagerOver67: Int, gjenståendeSykedager: Int, forbrukteSykedager: Int, maksdato: LocalDate ) { juridiskVurdering( "", Vurderingsresultat( oppfylt = oppfylt, versjon = LocalDate.of(2011, 12, 16), paragraf = PARAGRAF_8_51, ledd = LEDD_3, punktum = 1.punktum, inputdata = mapOf( "maksSykepengedagerOver67" to maksSykepengedagerOver67 ), outputdata = mapOf( "gjenståendeSykedager" to gjenståendeSykedager, "forbrukteSykedager" to forbrukteSykedager, "maksdato" to maksdato ) ) ) } } } private class TidslinjegrunnlagVisitor(utbetalingstidslinje: Utbetalingstidslinje) : UtbetalingsdagVisitor { private val navdager = mutableListOf<Periode>() private var forrigeDato: LocalDate? = null private class Periode( val fom: LocalDate, var tom: LocalDate, val dagtype: String ) { companion object { fun List<Periode>.dager() = map { mapOf( "fom" to it.fom, "tom" to it.tom, "dagtype" to it.dagtype ) } } } init { utbetalingstidslinje.accept(this) } fun dager() = navdager.dager() override fun visit(dag: Utbetalingstidslinje.Utbetalingsdag.NavDag, dato: LocalDate, økonomi: Økonomi) { visit(dato, "NAVDAG") } override fun visit(dag: Utbetalingstidslinje.Utbetalingsdag.NavHelgDag, dato: LocalDate, økonomi: Økonomi) { visit(dato, "NAVDAG") } override fun visit(dag: Utbetalingstidslinje.Utbetalingsdag.Fridag, dato: LocalDate, økonomi: Økonomi) { if (forrigeDato != null && forrigeDato?.plusDays(1) == dato) visit(dato, "FRIDAG") } private fun visit(dato: LocalDate, dagtype: String) { forrigeDato = dato if (navdager.isEmpty() || dagtype != navdager.last().dagtype || navdager.last().tom.plusDays(1) != dato) { navdager.add(Periode(dato, dato, dagtype)) } else { navdager.last().tom = dato } } } } internal data class AktivVedtaksperiode( val orgnummer: String, val vedtaksperiodeId: UUID, val periodetype: Periodetype ) { fun toMap() = mapOf<String, Any>( "orgnummer" to orgnummer, "vedtaksperiodeId" to vedtaksperiodeId.toString(), "periodetype" to periodetype.name ) } } } interface IAktivitetslogg { fun info(melding: String, vararg params: Any?) fun warn(melding: String, vararg params: Any?) fun behov(type: Behov.Behovtype, melding: String, detaljer: Map<String, Any?> = emptyMap()) fun error(melding: String, vararg params: Any?) fun severe(melding: String, vararg params: Any?): Nothing fun juridiskVurdering(melding: String, vurdering: Etterlevelse.Vurderingsresultat) fun hasActivities(): Boolean fun hasWarningsOrWorse(): Boolean fun hasErrorsOrWorse(): Boolean fun aktivitetsteller(): Int fun behov(): List<Behov> fun juridiskeVurderinger(): List<Etterlevelse> fun barn(): Aktivitetslogg fun kontekst(kontekst: Aktivitetskontekst) fun kontekst(person: Person) fun kontekster(): List<IAktivitetslogg> fun hendelseskontekster(): Map<String, String> fun hendelseskontekst(): Hendelseskontekst fun toMap(): Map<String, List<Map<String, Any>>> } internal interface AktivitetsloggVisitor { fun preVisitAktivitetslogg(aktivitetslogg: Aktivitetslogg) {} fun visitInfo( kontekster: List<SpesifikkKontekst>, aktivitet: Aktivitetslogg.Aktivitet.Info, melding: String, tidsstempel: String ) { } fun visitWarn( kontekster: List<SpesifikkKontekst>, aktivitet: Aktivitetslogg.Aktivitet.Warn, melding: String, tidsstempel: String ) { } fun visitBehov( kontekster: List<SpesifikkKontekst>, aktivitet: Behov, type: Behov.Behovtype, melding: String, detaljer: Map<String, Any?>, tidsstempel: String ) { } fun visitError( kontekster: List<SpesifikkKontekst>, aktivitet: Aktivitetslogg.Aktivitet.Error, melding: String, tidsstempel: String ) { } fun visitSevere( kontekster: List<SpesifikkKontekst>, aktivitet: Aktivitetslogg.Aktivitet.Severe, melding: String, tidsstempel: String ) { } fun preVisitEtterlevelse( kontekster: List<SpesifikkKontekst>, aktivitet: Etterlevelse, melding: String, vurderingsresultat: Etterlevelse.Vurderingsresultat, tidsstempel: String ) { } fun visitVurderingsresultat( oppfylt: Boolean, versjon: LocalDate, paragraf: Paragraf, ledd: Ledd, punktum: List<Punktum>, bokstaver: List<Bokstav>, outputdata: Map<Any, Any?>, inputdata: Map<Any, Any?> ) { } fun postVisitEtterlevelse( kontekster: List<SpesifikkKontekst>, aktivitet: Etterlevelse, melding: String, vurderingsresultat: Etterlevelse.Vurderingsresultat, tidsstempel: String ) { } fun postVisitAktivitetslogg(aktivitetslogg: Aktivitetslogg) {} } interface Aktivitetskontekst { fun toSpesifikkKontekst(): SpesifikkKontekst } class SpesifikkKontekst(internal val kontekstType: String, internal val kontekstMap: Map<String, String> = mapOf()) { internal fun melding() = kontekstType + kontekstMap.entries.joinToString(separator = "") { " ${it.key}: ${it.value}" } override fun equals(other: Any?) = this === other || other is SpesifikkKontekst && this.kontekstMap == other.kontekstMap override fun hashCode() = kontekstMap.hashCode() }
0
Kotlin
2
3
9572b362ab94daa6a730331c309a1cdc0ec25e3e
55,407
helse-spleis
MIT License
app/src/main/java/com/maheshgaya/android/basicnote/adapter/NoteListAdapter.kt
maheshgaya
100,090,225
false
null
package com.maheshgaya.android.basicnote.adapter import android.app.Activity import android.content.Context import android.content.Intent import android.support.v4.app.ActivityOptionsCompat import android.support.v7.widget.RecyclerView import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.maheshgaya.android.basicnote.R import com.maheshgaya.android.basicnote.model.Note import com.maheshgaya.android.basicnote.ui.note.NoteActivity import com.maheshgaya.android.basicnote.ui.note.NoteFragment import com.maheshgaya.android.basicnote.util.fromHtml import com.maheshgaya.android.basicnote.util.toDate /** * Created by <NAME> on 8/13/17. */ class NoteListAdapter(context: Context?, list:MutableList<Note>, main:Boolean = true): RecyclerView.Adapter<NoteListAdapter.ViewHolder>(), View.OnClickListener { /** mutable list of notes */ private var mList = list /** context */ private var mContext = context private var mMain = main init { setHasStableIds(true) } /** * bind the view holder */ override fun onBindViewHolder(holder: ViewHolder?, position: Int) { //sets title and body for the corresponding note holder?.setNote(mList[position]) //set onClickListener holder?.noteCardView?.setOnClickListener(this) holder?.noteCardView?.tag = position } override fun getItemCount(): Int = mList.size fun getItem(position: Int): Note = mList[position] override fun getItemId(position: Int): Long { return getItem(position).hashCode().toLong() } /** * Creates the view holder by inflating the list item layout */ override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent!!.context) // Inflate the custom layout and return a new holder instance return ViewHolder(inflater.inflate(R.layout.list_item_note, parent, false)) } /** * Handles onClick events */ override fun onClick(view: View?) { when (view!!.id){ R.id.item_note_cardview -> { val intent = Intent(mContext as Activity, NoteActivity::class.java) val position= view.tag as Int intent.putExtra(NoteFragment.NOTE_KEY, mList[position]) intent.putExtra(NoteFragment.NOTE_MAIN, mMain) val options = ActivityOptionsCompat.makeSceneTransitionAnimation(mContext as Activity, view, mContext?.getString(R.string.transition_item_note)) mContext!!.startActivity(intent, options.toBundle()) } } } /** * ViewHolder to contain the item view */ inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView){ private var context: Context = itemView!!.context /** Outer layout of the card */ var noteCardView:View = itemView!!.findViewById(R.id.item_note_cardview) /** Title textview */ var noteTitleTextView:TextView = itemView!!.findViewById(R.id.item_note_title) /** Body textview */ var noteBodyTextView:TextView = itemView!!.findViewById(R.id.item_note_body) /** Last edited */ var lastEditedTextView: TextView = itemView!!.findViewById(R.id.item_note_last_edited) /** * Sets text for note's title and body * @param note Note model */ fun setNote(note: Note){ noteTitleTextView.text = note.title.fromHtml(mode = Html.FROM_HTML_MODE_COMPACT).trim() val body = note.body.fromHtml().trim() noteBodyTextView.text = body noteBodyTextView.hint = if (body.isEmpty()) mContext?.getString(R.string.no_body_text) else "" lastEditedTextView.text = note.lastEdited.toDate(context = context) } } }
0
Kotlin
0
0
64bb47191252fb5b4419d9704b67216d28a68170
3,975
BasicNote
The Unlicense
feature/details/src/main/java/at/marki/moviedb/feature/details/ui/MovieHeadlineInformation.kt
markini
867,015,327
false
{"Kotlin": 161660}
package at.marki.moviedb.feature.details.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement.spacedBy import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface 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.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import at.marki.moviedb.core.designsystems.ThemePreviews import at.marki.moviedb.core.designsystems.theme.AppTheme import at.marki.moviedb.core.model.Movie import kotlinx.datetime.Clock import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toLocalDateTime import java.time.format.DateTimeFormatter @Composable internal fun MovieHeadlineInformation( movie: Movie, modifier: Modifier = Modifier, ) { Column( modifier = modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, ) { MovieDate(movie = movie) Spacer(modifier = Modifier.height(10.dp)) MovieTitle(movie = movie) Spacer(modifier = Modifier.height(8.dp)) Genres(movie = movie) } } @Composable private fun MovieDate( movie: Movie, modifier: Modifier = Modifier, ) { Row( modifier = modifier, horizontalArrangement = Arrangement.Center, ) { Text( text = movie.releaseDate?.let { formatLocalDate(it) }.orEmpty(), style = MaterialTheme.typography.bodyLarge, ) Text( text = ".", style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 6.dp), ) Text( text = movie.runtime?.formatRuntime().orEmpty(), style = MaterialTheme.typography.bodyLarge, ) } } fun formatLocalDate(date: LocalDate): String { val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") return date.toJavaLocalDate().format(formatter) } fun Int.formatRuntime(): String { val hours = this / 60 val minutes = this % 60 return "$hours h $minutes min" } @Composable private fun MovieTitle( movie: Movie, modifier: Modifier = Modifier, ) { Text( text = buildAnnotatedString { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append(movie.title.orEmpty()) } append(" (${movie.releaseDate?.year})") }, modifier = modifier, style = MaterialTheme.typography.titleLarge, fontSize = 30.sp, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis, ) } @Composable private fun Genres( movie: Movie, modifier: Modifier = Modifier, ) { Row( modifier = modifier, horizontalArrangement = spacedBy(8.dp), ) { movie.genres.forEach { GenreChip( text = it, ) } } } @Composable internal fun GenreChip( text: String, modifier: Modifier = Modifier, ) { Card( modifier = modifier, colors = CardDefaults.cardColors( containerColor = Color(0xFFF0F1F1), contentColor = MaterialTheme.colorScheme.onBackground, ), ) { Text( text = text, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier .padding(horizontal = 10.dp, vertical = 4.dp), ) } } @ThemePreviews @Composable private fun MovieHeadlineInformationPreview() { AppTheme { Surface { MovieHeadlineInformation( movie = Movie( id = 1, title = "Demolition Man", rating = 4.0, revenue = 1000000, releaseDate = Clock.System.now() .toLocalDateTime(TimeZone.currentSystemDefault()).date, posterUrl = "", runtime = 120, overview = "Overview", reviews = 100, budget = 1000000, language = "en", genres = listOf("Action", "Adventure"), director = null, cast = emptyList(), ), ) } } }
1
Kotlin
1
0
08ffa932d59c9e010d81b27ddbc7d00c07ade2d7
5,206
MovieDatabase
Apache License 2.0
src/org/magiclib/LunaWrapper.kt
MagicLibStarsector
583,789,919
false
{"Markdown": 4, "Text": 4, "Ant Build System": 2, "JSON": 15, "XML": 17, "Ignore List": 2, "Java": 119, "Kotlin": 78, "YAML": 1, "Shell": 2, "HTML": 2435, "SVG": 25, "CSS": 5, "JavaScript": 7, "Batchfile": 1, "Java Properties": 2}
package org.magiclib import lunalib.lunaSettings.LunaSettings /** * There's some bug where having even a soft dependency on LunaLib becomes a hard dependency. * Creating a wrapper class that's onlyl instantiated if LunaLib is present seems to fix it. */ object LunaWrapper { @JvmStatic fun addSettingsListener(listener: LunaWrapperSettingsListener) { LunaSettings.addSettingsListener(object : lunalib.lunaSettings.LunaSettingsListener { override fun settingsChanged(modID: String) { listener.settingsChanged(modID) } }) } @JvmStatic fun getBoolean(modID: String, fieldID: String): Boolean? = LunaSettings.getBoolean(modID, fieldID) @JvmStatic fun getInt(modID: String, fieldID: String): Int? = LunaSettings.getInt(modID, fieldID) } interface LunaWrapperSettingsListener { fun settingsChanged(modID: String) }
16
Java
2
9
8e6e7b6992f322d7172d84967a7e5656d35889af
904
MagicLib
MIT License
Application/src/main/java/com/example/android/bluetoothlegatt/BluetoothLeService.kt
10sunnyside
265,201,357
false
{"Java": 2253185, "Kotlin": 275715, "Assembly": 160}
/* * Copyright (C) 2013 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.example.android.bluetoothlegatt import android.app.Service import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context import android.content.Intent import android.os.Binder import android.os.IBinder import android.util.Log import android.widget.Toast import java.util.UUID import kotlin.experimental.and /** * Service for managing connection and data communication with a GATT server hosted on a * given Bluetooth LE device. */ class BluetoothLeService : Service() { private var mBluetoothManager: BluetoothManager? = null private var mBluetoothAdapter: BluetoothAdapter? = null private var mBluetoothDeviceAddress: String? = null private var mBluetoothDeviceAddress2: String? = null private var mBluetoothGatt: BluetoothGatt? = null private var mBluetoothGatt2: BluetoothGatt? = null private var mConnectionState = STATE_DISCONNECTED private var mConnectionState2 = STATE_DISCONNECTED // Implements callback methods for GATT events that the app cares about. For example, // connection change and services discovered. private val mGattCallback = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { val intentAction: String if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED mConnectionState = STATE_CONNECTED broadcastUpdate(intentAction) Log.i(TAG, "Connected to GATT server.") // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt!!.discoverServices()) } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED mConnectionState = STATE_DISCONNECTED Log.i(TAG, "Disconnected from GATT server.") broadcastUpdate(intentAction) } } override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED) } else { Log.w(TAG, "onServicesDiscovered received: $status") } } override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic) } } override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { //A request to Write has completed if (status == BluetoothGatt.GATT_SUCCESS) { //See if the write was successful Log.e(TAG, "**ACTION_DATA_WRITTEN**$characteristic") broadcastUpdate(ACTION_DATA_WRITTEN, characteristic) //Go broadcast an intent to say we have have written data } } override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { Toast.makeText(applicationContext,characteristic.value.toString(), Toast.LENGTH_LONG).show() broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic) } } private val mGattCallback2 = object : BluetoothGattCallback() { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { val intentAction: String if (newState == BluetoothProfile.STATE_CONNECTED) { intentAction = ACTION_GATT_CONNECTED mConnectionState2 = STATE_CONNECTED broadcastUpdate(intentAction) Log.i(TAG, "Connected to GATT server.") // Attempts to discover services after successful connection. Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt2!!.discoverServices()) } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { intentAction = ACTION_GATT_DISCONNECTED mConnectionState2 = STATE_DISCONNECTED Log.i(TAG, "Disconnected from GATT server.") broadcastUpdate(intentAction) } } override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED) } else { Log.w(TAG, "onServicesDiscovered received: $status") } } override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic) } } override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { //A request to Write has completed if (status == BluetoothGatt.GATT_SUCCESS) { //See if the write was successful Log.e(TAG, "**ACTION_DATA_WRITTEN**$characteristic") broadcastUpdate(ACTION_DATA_WRITTEN, characteristic) //Go broadcast an intent to say we have have written data } } override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { Toast.makeText(applicationContext,characteristic.value.toString(), Toast.LENGTH_LONG).show() broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic) } } private val mBinder = LocalBinder() /** * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after `BluetoothGatt#discoverServices()` completes successfully. * * @return A `List` of supported services. */ val supportedGattServices: List<BluetoothGattService>? get() = if (mBluetoothGatt == null) null else mBluetoothGatt!!.services val supportedGattServices2: List<BluetoothGattService>? get() = if (mBluetoothGatt2 == null) null else mBluetoothGatt2!!.services private fun broadcastUpdate(action: String) { val intent = Intent(action) sendBroadcast(intent) } private fun broadcastUpdate(action: String, characteristic: BluetoothGattCharacteristic) { val intent = Intent(action) // This is special handling for the Heart Rate Measurement profile. Data parsing is // carried out as per profile specifications: // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml if (UUID_HEART_RATE_MEASUREMENT == characteristic.uuid) { val flag = characteristic.properties var format = -1 if (flag and 0x01 != 0) { format = BluetoothGattCharacteristic.FORMAT_UINT16 Log.d(TAG, "Heart rate format UINT16.") } else { format = BluetoothGattCharacteristic.FORMAT_UINT8 Log.d(TAG, "Heart rate format UINT8.") } val heartRate = characteristic.getIntValue(format, 1)!! Log.d(TAG, String.format("Received heart rate: %d", heartRate)) intent.putExtra(EXTRA_DATA, heartRate.toString()) } else { // For all other profiles, writes the data formatted in HEX. val data = characteristic.value val ruuid = characteristic.uuid var data2 ="" var hexData = "" if (data != null && data.size > 0) { val stringBuilder = StringBuilder(data.size) for (byteChar in data){ hexData=hexData+String.format("%02X", byteChar) // stringBuilder.append(String.format("%02X ", byteChar)) //intent.putExtra(EXTRA_DATA, ruuid.toString() + "\n"+ String(data) + "\n" + stringBuilder.toString()) val uByteChar = byteChar.toUByte().toInt() if (uByteChar < 10){ data2 = data2 + "0"+ uByteChar.toString() } else{ data2 = data2 + uByteChar.toString() } } stringBuilder.append(data2) intent.putExtra(EXTRA_DATA, ruuid.toString() + "\n"+ hexData + "\n" + stringBuilder.toString()) } } sendBroadcast(intent) } inner class LocalBinder : Binder() { internal val service: BluetoothLeService get() = this@BluetoothLeService } override fun onBind(intent: Intent): IBinder? { return mBinder } override fun onUnbind(intent: Intent): Boolean { // After using a given device, you should make sure that BluetoothGatt.close() is called // such that resources are cleaned up properly. In this particular example, close() is // invoked when the UI is disconnected from the Service. close() close2() return super.onUnbind(intent) } /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ fun initialize(): Boolean { // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. if (mBluetoothManager == null) { mBluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager if (mBluetoothManager == null) { Log.e(TAG, "Unable to initialize BluetoothManager.") return false } } mBluetoothAdapter = mBluetoothManager!!.adapter if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter.") return false } return true } /** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * `BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)` * callback. */ fun connect(address: String?): Boolean { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.") return false } // Previously connected device. Try to reconnect. /* if (mBluetoothDeviceAddress != null && address == mBluetoothDeviceAddress && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.") if (mBluetoothGatt!!.connect()) { mConnectionState = STATE_CONNECTING return true } else { return false } }*/ //delete auto reconnect for multi val device = mBluetoothAdapter!!.getRemoteDevice(address) if (device == null) { Log.w(TAG, "Device not found. Unable to connect.") return false } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback) Log.d(TAG, "Trying to create a new connection.") mBluetoothDeviceAddress = address mConnectionState = STATE_CONNECTING return true } fun connect2(address: String?): Boolean { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.") return false } // Previously connected device. Try to reconnect. /* if (mBluetoothDeviceAddress != null && address == mBluetoothDeviceAddress && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.") if (mBluetoothGatt!!.connect()) { mConnectionState = STATE_CONNECTING return true } else { return false } }*/ //delete auto reconnect for multi val device = mBluetoothAdapter!!.getRemoteDevice(address) if (device == null) { Log.w(TAG, "Device not found. Unable to connect.") return false } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt2 = device.connectGatt(this, false, mGattCallback2) Log.d(TAG, "Trying to create a new connection.") mBluetoothDeviceAddress2 = address mConnectionState2 = STATE_CONNECTING return true } /** * Disconnects an existing connection or cancel a pending connection. The disconnection result * is reported asynchronously through the * `BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)` * callback. */ fun disconnect() { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt!!.disconnect() } fun disconnect2() { if (mBluetoothAdapter == null || mBluetoothGatt2 == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt2!!.disconnect() } /** * After using a given BLE device, the app must call this method to ensure resources are * released properly. */ fun close() { if (mBluetoothGatt == null) { return } mBluetoothGatt!!.close() mBluetoothGatt = null } fun close2() { if (mBluetoothGatt2 == null) { return } mBluetoothGatt2!!.close() mBluetoothGatt2 = null } /** * Request a read on a given `BluetoothGattCharacteristic`. The read result is reported * asynchronously through the `BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)` * callback. * * @param characteristic The characteristic to read from. */ fun readCharacteristic(characteristic: BluetoothGattCharacteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt!!.readCharacteristic(characteristic) } fun readCharacteristic2(characteristic: BluetoothGattCharacteristic) { if (mBluetoothAdapter == null || mBluetoothGatt2 == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt2!!.readCharacteristic(characteristic) } fun writeCharacteristic(characteristic: BluetoothGattCharacteristic) { try { if (mBluetoothAdapter == null || mBluetoothGatt == null) { //Check that we have access to a Bluetooth radio return } val test = characteristic.properties //Get the properties of the characteristic if (test and BluetoothGattCharacteristic.PROPERTY_WRITE == 0 && test and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE == 0) { //Check that the property is writable return } if (mBluetoothGatt!!.writeCharacteristic(characteristic)) { //Request the BluetoothGatt to do the Write Log.i(TAG, "****************WRITE CHARACTERISTIC SUCCESSFUL**$characteristic")//The request was accepted, this does not mean the write completed /* if(characteristic.getUuid().toString().equalsIgnoreCase(getString(R.string.char_uuid_missed_connection))){ }*/ } else { Log.i(TAG, "writeCharacteristic failed") //Write request was not accepted by the BluetoothGatt } } catch (e: Exception) { Log.i(TAG, e.message) } } fun writeCharacteristic2(characteristic: BluetoothGattCharacteristic) { try { if (mBluetoothAdapter == null || mBluetoothGatt2 == null) { //Check that we have access to a Bluetooth radio return } val test = characteristic.properties //Get the properties of the characteristic if (test and BluetoothGattCharacteristic.PROPERTY_WRITE == 0 && test and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE == 0) { //Check that the property is writable return } if (mBluetoothGatt2!!.writeCharacteristic(characteristic)) { //Request the BluetoothGatt to do the Write Log.i(TAG, "****************WRITE CHARACTERISTIC SUCCESSFUL**$characteristic -- ${mBluetoothGatt2!!.device}")//The request was accepted, this does not mean the write completed /* if(characteristic.getUuid().toString().equalsIgnoreCase(getString(R.string.char_uuid_missed_connection))){ }*/ } else { Log.i(TAG, "writeCharacteristic failed") //Write request was not accepted by the BluetoothGatt } } catch (e: Exception) { Log.i(TAG, e.message) } } /** * Enables or disables notification on a give characteristic. * * @param characteristic Characteristic to act on. * @param enabled If true, enable notification. False otherwise. */ fun setCharacteristicNotification(characteristic: BluetoothGattCharacteristic, enabled: Boolean) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt!!.setCharacteristicNotification(characteristic, enabled) Thread.sleep(2000) // This is specific to Heart Rate Measurement. if (ALERT_LIGHT == characteristic.uuid) { val descriptor = characteristic.getDescriptor( UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)) descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE mBluetoothGatt!!.writeDescriptor(descriptor) } } fun setCharacteristicNotification2(characteristic: BluetoothGattCharacteristic, enabled: Boolean) { if (mBluetoothAdapter == null || mBluetoothGatt2 == null) { Log.w(TAG, "BluetoothAdapter not initialized") return } mBluetoothGatt2!!.setCharacteristicNotification(characteristic, enabled) Thread.sleep(2000) // This is specific to Heart Rate Measurement. if (ALERT_LIGHT == characteristic.uuid) { val descriptor = characteristic.getDescriptor( UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)) descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE mBluetoothGatt2!!.writeDescriptor(descriptor) } } companion object { private val TAG = BluetoothLeService::class.java!!.getSimpleName() private val STATE_DISCONNECTED = 0 private val STATE_CONNECTING = 1 private val STATE_CONNECTED = 2 val ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED" val ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED" val ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED" val ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE" val ACTION_DATA_WRITTEN = "com.example.bluetooth.le.ACTION_DATA_WRITTEN" val EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA" val UUID_HEART_RATE_MEASUREMENT = UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT) val ALERT_LIGHT = UUID.fromString(SampleGattAttributes.ALERT_LIGHT) } }
1
null
1
1
c813429cb6906916e5142a84571e1e0d7819d446
22,086
SunnyFive_Application
Apache License 2.0
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/SingleInterestTargetingOptionResponse.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * Pinterest REST API * Pinterest's REST API * * The version of the OpenAPI document: 5.12.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.server.api.model import com.google.gson.annotations.SerializedName import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude /** * * @param id * @param name * @param childInterests * @param level */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class SingleInterestTargetingOptionResponse ( val id: kotlin.String? = null, val name: kotlin.String? = null, val childInterests: kotlin.Array<kotlin.String>? = null, val level: kotlin.Int? = null ) { }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
893
pinterest-sdk
MIT License
app/src/main/java/com/pcm/gallery/model/ModelAlbum.kt
piyush-malaviya
126,628,682
false
null
package com.pcm.gallery.model import android.os.Parcel import android.os.Parcelable data class ModelAlbum(var id: String, var name: String, var count: Int, var type: Int, var path: String) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readInt(), parcel.readInt(), parcel.readString()) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(name) parcel.writeInt(count) parcel.writeInt(type) parcel.writeString(path) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ModelAlbum> { override fun createFromParcel(parcel: Parcel): ModelAlbum { return ModelAlbum(parcel) } override fun newArray(size: Int): Array<ModelAlbum?> { return arrayOfNulls(size) } } }
0
Kotlin
0
2
eca315de491c31e5825a5753c21b78b32bb06747
1,095
Gallery
Apache License 2.0
SerawaziApplication/app/src/main/java/com/greenrevive/serawaziapplication/ui/LevelTwoCongratsActivity.kt
MutindaVictoria
718,561,733
false
{"Kotlin": 107697}
package com.greenrevive.serawaziapplication.ui import android.content.Intent import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.animation.AnimationUtils import com.greenrevive.serawaziapplication.R import com.greenrevive.serawaziapplication.databinding.ActivityLevelTwoCongratsBinding class LevelTwoCongratsActivity : AppCompatActivity() { lateinit var binding: ActivityLevelTwoCongratsBinding private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityLevelTwoCongratsBinding.inflate(layoutInflater) val view=binding.root super.onCreate(savedInstanceState) val animation = AnimationUtils.loadAnimation(this, R.anim.front_to_back_movement) // binding.imageView6.startAnimation(animation) binding.ivPurpleBackground.startAnimation(animation) setContentView(binding.root) initializeMediaPlayer() } private fun initializeMediaPlayer() { mediaPlayer = MediaPlayer.create(this, R.raw.coinsound) mediaPlayer.isLooping = true mediaPlayer.start() } override fun onResume() { super.onResume() binding.tvPlayLevel3.setOnClickListener { mediaPlayer.stop() startActivity(Intent(this,SelectALevelActivity::class.java)) } } }
0
Kotlin
0
0
3e68806907fa0489274d5625a35d220ffb79c9a0
1,423
Serawazi-Mobile
MIT License
app/src/main/java/com/dk/piley/model/remote/backup/ContentDispositionHeaders.kt
justdeko
511,233,835
false
{"Kotlin": 487127, "Shell": 2624}
package com.dk.piley.model.remote.backup import java.time.Instant /** * Content disposition headers returned from an api response of a backup * * @property filename the backup file name * @property lastModified last modification date of the backup */ data class ContentDispositionHeaders( val filename: String?, val lastModified: Instant? )
7
Kotlin
1
7
9cb1ad0b427f9a34bcde0d238c65fcae22cf50be
356
piley
Apache License 2.0
services/csm.cloud.user.user/src/main/kotlin/com/bosch/pt/csm/cloud/usermanagement/user/user/command/handler/DeleteUserCommandHandler.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2022 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.usermanagement.user.user.command.handler import com.bosch.pt.csm.cloud.common.api.UserId import com.bosch.pt.csm.cloud.usermanagement.common.translation.Key.USER_VALIDATION_ERROR_SYSTEM_USER_MUST_NOT_BE_MODIFIED import com.bosch.pt.csm.cloud.usermanagement.user.eventstore.UserContextLocalEventBus import com.bosch.pt.csm.cloud.usermanagement.user.picture.api.DeleteProfilePictureOfUserCommand import com.bosch.pt.csm.cloud.usermanagement.user.picture.command.handler.DeleteProfilePictureCommandHandler import com.bosch.pt.csm.cloud.usermanagement.user.user.api.DeleteUserAfterSkidDeletionCommand import com.bosch.pt.csm.cloud.usermanagement.user.user.command.snapshotstore.UserSnapshot import com.bosch.pt.csm.cloud.usermanagement.user.user.command.snapshotstore.UserSnapshotStore import org.springframework.beans.factory.annotation.Value import org.springframework.security.access.prepost.PreAuthorize import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class DeleteUserAfterSkidDeletionCommandHandler( private val eventBus: UserContextLocalEventBus, private val profilePictureCommandHandler: DeleteProfilePictureCommandHandler, private val snapshotStore: UserSnapshotStore, @Value("\${system.user.identifier}") private val systemUserIdentifier: UserId ) { @PreAuthorize("@userAuthorizationComponent.isCurrentUserSystemUser()") @Transactional fun handle(command: DeleteUserAfterSkidDeletionCommand) = snapshotStore .findOrFail(command.identifier) .toCommandHandler() .checkPrecondition { isNotSystemUser(it) } .onFailureThrow(USER_VALIDATION_ERROR_SYSTEM_USER_MUST_NOT_BE_MODIFIED) .emitTombstone() .also { // TODO: In the future, this will happen AFTER the user has been deleted as a // consequence, not a pre-requisite. This can happen in an event listener then. On the // other hand, the profile picture snapshot is deleted in the user snapshot store // anyway. Do we need this call here to raise the event? Or can we skip is? profilePictureCommandHandler.handle( DeleteProfilePictureOfUserCommand(command.identifier, false)) } .to(eventBus) private fun isNotSystemUser(it: UserSnapshot) = it.identifier != systemUserIdentifier }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,646
bosch-pt-refinemysite-backend
Apache License 2.0
internal/test-utils-core/src/androidMain/kotlin/com/github/panpf/sketch/test/utils/TestNewMutateDrawable.kt
panpf
14,798,941
false
null
/* * Copyright (C) 2024 panpf <[email protected]> * * 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.test.utils import android.graphics.drawable.Drawable import androidx.appcompat.graphics.drawable.DrawableWrapperCompat class TestNewMutateDrawable(drawable: Drawable) : DrawableWrapperCompat(drawable) { override fun mutate(): TestNewMutateDrawable { val mutateDrawable = drawable?.mutate() return if (mutateDrawable != null && mutateDrawable !== drawable) { TestNewMutateDrawable(drawable = mutateDrawable) } else { this } } }
8
null
309
2,057
89784530da0de6085a5b08f810415147cb3165cf
1,142
sketch
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/switch/App.kt
xlj44400
248,655,590
true
{"Kotlin": 1516065, "HTML": 1503}
package samples.switch import kotlinx.css.* import react.* import react.dom.* import styled.* object SwitchStyles : StyleSheet("switch", isStatic = true) { val container by css {} val basic by css { descendants(".ant-switch") { marginBottom = 8.px } } val text by css {} val loading by css {} val disabled by css {} val size by css {} } class SwitchApp : RComponent<RProps, RState>() { override fun RBuilder.render() { h2 { +"Switch" } styledDiv { css { +SwitchStyles.container } basic() text() loading() disabled() size() } } } fun RBuilder.switchApp() = child(SwitchApp::class) {}
0
Kotlin
0
0
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
747
kotlin-js-wrappers
Apache License 2.0
app/src/main/java/com/algo/phantoms/algo_phantoms/fragments/SignUpFragment.kt
Algo-Phantoms
331,979,177
false
null
package com.algo.phantoms.algo_phantoms.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.algo.phantoms.algo_phantoms.FragmentChangeInterface import com.algo.phantoms.algo_phantoms.R import com.algo.phantoms.algo_phantoms.activities.MainActivity import com.algo.phantoms.algo_phantoms.databinding.FragmentSignUpBinding class SignUpFragment : Fragment() { companion object { private lateinit var binding: FragmentSignUpBinding private lateinit var fragmentChangeInterface: FragmentChangeInterface } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_sign_up, container, false) binding = FragmentSignUpBinding.bind(view) return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) fragmentChangeInterface = context as FragmentChangeInterface binding.signUpButton.setOnClickListener { MainActivity.start(requireContext()) } binding.signInText.setOnClickListener { fragmentChangeInterface.changeFragment(SignInFragment()) } } }
14
Kotlin
34
52
32c1db8d26042b25f0b0a2bbdba09ace0c6c6b9b
1,382
Algo-Phantoms-Android
Apache License 2.0
app/src/main/java/io/github/zmunm/insight/viewmodel/TopRatedViewModel.kt
zmunm
317,224,320
false
null
package io.github.zmunm.insight.viewmodel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import dagger.hilt.android.lifecycle.HiltViewModel import io.github.zmunm.insight.ui.adapter.paging.GamePagingSource import io.github.zmunm.insight.ui.base.BaseViewModel import javax.inject.Inject @HiltViewModel class TopRatedViewModel @Inject constructor( gamePagingSource: GamePagingSource, ) : BaseViewModel() { val pager = gamePagingSource .getPager() .cachedIn(viewModelScope) }
0
Kotlin
2
5
b9b1f0aa330e68665f94b8dc198669525aa79002
525
insight
MIT License
app/src/main/kotlin/com/rin/compose/kitty/MainActivity.kt
chachako
342,547,917
false
{"Kotlin": 141013}
/* * Copyright 2021 The Android Open Source Project * Copyright 2021 RinOrz (凛) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Github home page: https://github.com/RinOrz */ package com.rin.compose.kitty import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat.setDecorFitsSystemWindows import com.rin.compose.kitty.ui.KittyApp import com.rin.compose.kitty.ui.theme.MyTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setDecorFitsSystemWindows(window, false) setContent { MyTheme { KittyApp() } } } }
1
Kotlin
1
8
566e88f637b73fd85ddd93039c1f666890fd5c1b
1,287
compose-kitty
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/assessments/restclient/communityapi/CommunityOffenderDto.kt
ministryofjustice
289,880,556
false
null
package uk.gov.justice.digital.assessments.restclient.communityapi data class CommunityOffenderDto( var offenderId: Long? = null, val firstName: String? = null, val middleNames: List<String>? = null, val surname: String? = null, val previousSurname: String? = null, val dateOfBirth: String, val gender: String? = null, val otherIds: IDs? = null, val offenderAliases: List<OffenderAlias>? = null, val contactDetails: ContactDetails? = null, val offenderProfile: OffenderProfile? = null ) data class OffenderProfile( val ethnicity: String? = null, val disabilities: List<Disability>? = null, val offenderLanguages: OffenderLanguages? = null, val genderIdentity: String? = null, ) data class OffenderLanguages(val primaryLanguage: String? = null, val requiresInterpreter: Boolean) data class Disability( val disabilityType: DisabilityType, ) data class DisabilityType( val code: String? = null, val description: String? = null ) data class ContactDetails( val emailAddresses: List<String>? = null, val phoneNumbers: List<Phone>? = null, val addresses: List<Address>? = null ) data class Address( val addressNumber: String? = null, val buildingName: String? = null, val status: Type? = null, val county: String? = null, val district: String? = null, val postcode: String? = null, val streetName: String? = null, val town: String? = null, val telephoneNumber: String? = null, ) data class Type( val code: String? = null, val description: String? = null, ) data class Phone( val number: String? = null, val type: String? = null ) data class OffenderAlias( val firstName: String? = null, val surname: String? = null, val dateOfBirth: String? = null, ) data class IDs( val crn: String? = null, val pncNumber: String? = null, val croNumber: String? = null, val niNumber: String? = null, val nomsNumber: String? = null, val immigrationNumber: String? = null )
2
Kotlin
1
1
9a85b22bde5ba94c6cd2c915e224253eb2130ee7
1,947
hmpps-assessments-api
MIT License
src/main/kotlin/uk/gov/justice/digital/assessments/restclient/communityapi/CommunityOffenderDto.kt
ministryofjustice
289,880,556
false
null
package uk.gov.justice.digital.assessments.restclient.communityapi data class CommunityOffenderDto( var offenderId: Long? = null, val firstName: String? = null, val middleNames: List<String>? = null, val surname: String? = null, val previousSurname: String? = null, val dateOfBirth: String, val gender: String? = null, val otherIds: IDs? = null, val offenderAliases: List<OffenderAlias>? = null, val contactDetails: ContactDetails? = null, val offenderProfile: OffenderProfile? = null ) data class OffenderProfile( val ethnicity: String? = null, val disabilities: List<Disability>? = null, val offenderLanguages: OffenderLanguages? = null, val genderIdentity: String? = null, ) data class OffenderLanguages(val primaryLanguage: String? = null, val requiresInterpreter: Boolean) data class Disability( val disabilityType: DisabilityType, ) data class DisabilityType( val code: String? = null, val description: String? = null ) data class ContactDetails( val emailAddresses: List<String>? = null, val phoneNumbers: List<Phone>? = null, val addresses: List<Address>? = null ) data class Address( val addressNumber: String? = null, val buildingName: String? = null, val status: Type? = null, val county: String? = null, val district: String? = null, val postcode: String? = null, val streetName: String? = null, val town: String? = null, val telephoneNumber: String? = null, ) data class Type( val code: String? = null, val description: String? = null, ) data class Phone( val number: String? = null, val type: String? = null ) data class OffenderAlias( val firstName: String? = null, val surname: String? = null, val dateOfBirth: String? = null, ) data class IDs( val crn: String? = null, val pncNumber: String? = null, val croNumber: String? = null, val niNumber: String? = null, val nomsNumber: String? = null, val immigrationNumber: String? = null )
2
Kotlin
1
1
9a85b22bde5ba94c6cd2c915e224253eb2130ee7
1,947
hmpps-assessments-api
MIT License
templates/release-0.26/src/main/java/com/badoo/ribs/template/node/foo_bar/routing/RoutingDependencyResolver.kt
SavinMike
207,783,264
true
{"Kotlin": 1024041}
package com.badoo.ribs.template.node.foo_bar.routing import com.badoo.ribs.template.node.foo_bar.FooBar internal class RoutingDependencyResolver( val dependency: FooBar.Dependency ) /**: LinksItemDetail.Dependency, LinksItemDetail.RootDependency by dependency, LinksItemDetail.TreeDependency by dependency, **/ { }
0
Kotlin
0
0
1a7ff1f3c4e89055349424cc1f093af5ee29a425
356
RIBs
Apache License 2.0
src/main/kotlin/io/newm/kogmios/protocols/messages/MsgFindIntersect.kt
projectNEWM
469,781,993
false
{"Kotlin": 334342, "Shell": 26}
package io.newm.kogmios.protocols.messages import io.newm.kogmios.protocols.model.FindIntersect import kotlinx.coroutines.CompletableDeferred import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Acquire a point of intersection for syncing the blockchain */ @Serializable @SerialName("FindIntersect") data class MsgFindIntersect( @SerialName("args") val args: FindIntersect, @SerialName("mirror") override val mirror: String, @kotlinx.serialization.Transient val completableDeferred: CompletableDeferred<MsgFindIntersectResponse> = CompletableDeferred(), ) : JsonWspRequest() // JSON Example // { // "type": "jsonwsp/request", // "version": "1.0", // "servicename": "ogmios", // "methodname": "FindIntersect", // "args": { // "points": [ // { // "slot": 18446744073709552000, // "hash": "c248757d390181c517a5beadc9c3fe64bf821d3e889a963fc717003ec248757d" // } // ] // } // }
0
Kotlin
0
4
f47c5b7b8363cfa504cf280e88f638cd1997fdfe
997
kogmios
Apache License 2.0
app/src/main/java/com/example/forage/ui/viewmodel/ForageableViewModel.kt
JordanMarcelino
472,825,286
true
{"Kotlin": 29114}
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.forage.ui.viewmodel import androidx.lifecycle.* import com.example.forage.data.ForageableDao import com.example.forage.model.Forageable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import java.lang.IllegalArgumentException /** * Shared [ViewModel] to provide data to the [ForageableListFragment], [ForageableDetailFragment], * and [AddForageableFragment] and allow for interaction the the [ForageableDao] */ class ForageableViewModel( private val forageableDao: ForageableDao ) : ViewModel() { val forageables = liveData { forageableDao.getForageable().collectLatest { emit(it) } } fun getForageable(id : Long) = liveData{ forageableDao.getForageable(id).collect { emit(it) } } fun addForageable( name: String, address: String, inSeason: Boolean, notes: String ) { if(isValidEntry(name, address)) { val forageable = Forageable( name = name, address = address, inSeason = inSeason, notes = notes ) viewModelScope.launch { forageableDao.insert(forageable) } } if (name.isBlank()) throw IllegalArgumentException("Insert a valid name") if (address.isBlank()) throw IllegalArgumentException("Insert a valid addres") } fun updateForageable( id: Long, name: String, address: String, inSeason: Boolean, notes: String ) { if(isValidEntry(name, address)) { val forageable = Forageable( id = id, name = name, address = address, inSeason = inSeason, notes = notes ) viewModelScope.launch(Dispatchers.IO) { forageableDao.update(forageable) } } if (name.isBlank()) throw IllegalArgumentException("Insert a valid name") if (address.isBlank()) throw IllegalArgumentException("Insert a valid addres") } fun deleteForageable(forageable: Forageable) { viewModelScope.launch(Dispatchers.IO) { forageableDao.delete(forageable) } } fun isValidEntry(name: String, address: String): Boolean { return name.isNotBlank() && address.isNotBlank() } }
0
Kotlin
0
0
c39d654b4f2b76ede088c74e6138fb332d938238
3,151
android-basics-kotlin-forage-app
Apache License 2.0
app/src/main/java/dev/efantini/yaat/ui/home/elements/NumberBox.kt
PizzaMarinara
489,516,976
false
null
package dev.efantini.yaat.ui.home.elements import androidx.compose.material.Text import androidx.compose.runtime.Composable @Composable fun NumberBox(number: String) { Text(text = "Boom, here's a number: $number") }
0
Kotlin
0
1
f412b59d58119e3cb2dd48c717497f7aad3b108d
222
yaat
MIT License
app/src/debug/kotlin/jp/co/yumemi/android/code_check/organisms/demo_menu_view/DemoMenuViewAdapter.kt
tshion
707,962,901
false
{"Kotlin": 102011}
package jp.co.yumemi.android.code_check.organisms.demo_menu_view import android.view.ViewGroup import android.view.ViewGroup.LayoutParams import android.view.ViewGroup.LayoutParams.MATCH_PARENT import androidx.core.util.Consumer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import jp.co.yumemi.android.code_check.R import jp.co.yumemi.android.code_check.molecules.demo_menu_item.DemoMenuItemView import jp.co.yumemi.android.code_check.molecules.demo_menu_item.DemoMenuItemViewData /** * 操作デモのメニューを表示するためのAdapter * * @param onTapListener リスト項目タップ時に実行するリスナー */ class DemoMenuViewAdapter( private val onTapListener: Consumer<DemoMenuItemViewData>, ) : ListAdapter<DemoMenuItemViewData, DemoMenuItemView.ViewHolder>(diffs) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int, ): DemoMenuItemView.ViewHolder { val context = parent.context return DemoMenuItemView(context).apply { layoutParams = LayoutParams( MATCH_PARENT, context.resources.getDimensionPixelSize(R.dimen.molecule_demo_menu_item_height), ) }.let { DemoMenuItemView.ViewHolder(it) } } override fun onBindViewHolder(holder: DemoMenuItemView.ViewHolder, position: Int) { val data = getItem(position) holder.view.setup(data) if (data.isEnabled) { holder.view.setOnClickListener { onTapListener.accept(data) } } else { holder.view.setOnClickListener(null) } } companion object { private val diffs = object : DiffUtil.ItemCallback<DemoMenuItemViewData>() { override fun areItemsTheSame( oldItem: DemoMenuItemViewData, newItem: DemoMenuItemViewData, ) = oldItem.original.id == newItem.original.id override fun areContentsTheSame( oldItem: DemoMenuItemViewData, newItem: DemoMenuItemViewData, ) = oldItem == newItem } } }
24
Kotlin
0
0
2c5717242d8364d640eedce72680af673966a6c1
2,072
yumemi-inc_android-engineer-codecheck
Apache License 2.0
library/src/main/kotlin/com/mmoczkowski/pfd/ModifierExt.kt
mmoczkowski
698,899,991
false
{"Kotlin": 57978}
/* * Copyright (C) 2023 Miłosz Moczkowski * * 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.mmoczkowski.pfd import androidx.compose.ui.Modifier import androidx.compose.ui.layout.layout internal fun Modifier.relativeOffset(x: Float = 0f, y: Float = 0f) = layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.placeRelative( x = (placeable.width * x).toInt(), y = (placeable.height * y).toInt() ) } }
0
Kotlin
1
17
3f01da4ddd692543fa26fd2656c70b09bf0c0b13
1,064
PrimaryFlightDisplay
Apache License 2.0
panel-kotlin/src/main/java/com/effective/android/panel/interfaces/OnScrollOutsideBorder.kt
uni7corn
266,576,506
false
null
package com.effective.android.panel.interfaces interface OnScrollOutsideBorder { fun canLayoutOutsideBorder(): Boolean val outsideHeight: Int }
0
Kotlin
1
0
ac4f611f12d6c44e70b1fc7e1bb4ecebe9a6ea60
152
emoji_keyboard
Apache License 2.0
responses/src/commonMain/kotlin/ru/krindra/vkkt/responses/video/VideoStopStreamingResponse.kt
krindra
780,080,411
false
{"Kotlin": 1336107}
package ru.krindra.vkkt.responses.video import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.krindra.vkkt.objects.video.* /** * @param uniqueViewers */ @Serializable data class VideoStopStreamingResponse ( @SerialName("unique_viewers") val uniqueViewers: Int? = null, )
0
Kotlin
0
1
58407ea02fc9d971f86702f3b822b33df65dd3be
319
VKKT
MIT License
solar/src/main/java/com/chiksmedina/solar/linear/videoaudiosound/RecordCircle.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.linear.videoaudiosound 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 com.chiksmedina.solar.linear.VideoAudioSoundGroup val VideoAudioSoundGroup.RecordCircle: ImageVector get() { if (_recordCircle != null) { return _recordCircle!! } _recordCircle = Builder( name = "RecordCircle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 12.0f) moveToRelative(-10.0f, 0.0f) arcToRelative(10.0f, 10.0f, 0.0f, true, true, 20.0f, 0.0f) arcToRelative(10.0f, 10.0f, 0.0f, true, true, -20.0f, 0.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(12.0f, 12.0f) moveToRelative(-4.0f, 0.0f) arcToRelative(4.0f, 4.0f, 0.0f, true, true, 8.0f, 0.0f) arcToRelative(4.0f, 4.0f, 0.0f, true, true, -8.0f, 0.0f) } } .build() return _recordCircle!! } private var _recordCircle: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,088
SolarIconSetAndroid
MIT License
src/test/kotlin/org/wagham/db/scopes/players.kt
ilregnodiwagham
540,862,397
false
null
package org.wagham.db.scopes import io.kotest.matchers.ints.shouldBeGreaterThan import kotlinx.coroutines.flow.count import org.wagham.db.KabotMultiDBClient import org.wagham.db.KabotMultiDBClientTest fun KabotMultiDBClientTest.testPlayers( client: KabotMultiDBClient, guildId: String ) { "getAllPlayers should be able to get all the players" { val players = client.playersScope.getAllPlayers(guildId) players.count() shouldBeGreaterThan 0 } }
0
Kotlin
0
0
855e69e26c30a8a392c5bef6f1b6b6e1eece4031
479
kabot-db-connector
MIT License
cloudopt-next-web/src/main/kotlin/net/cloudopt/next/web/constant/PriorityConstant.kt
cloudoptlab
117,033,346
false
{"Kotlin": 438045, "HTML": 4325, "Python": 163, "Handlebars": 149, "FreeMarker": 148, "CSS": 23}
package net.cloudopt.next.web.constant class PriorityConstant { companion object{ /** * The default and minimum priority that is assigned to a route. */ const val MIN_PRIORITY = 0 /** * The maximum priority that a route can have. */ const val MAX_PRIORITY = 9 } }
3
Kotlin
49
335
b6d8f934357a68fb94ef511109a1a6043af4b5b6
341
cloudopt-next
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SelectionActionType.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class SelectionActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = SelectionAction( dataObject = actionDTO.getObject(0), dataList = actionDTO.getList(0), ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, parameters = 1, ) companion object { private const val TYPE = "show_selection" private const val FUNCTION_NAME = "showSelection" } }
18
Kotlin
100
749
72abafd7e3bbe68647a109cb4d5a1d3b97a73d31
676
HTTP-Shortcuts
MIT License
libkt/src/main/java/io/awesdroid/libkt/common/utils/Utils.kt
awesdroid
172,074,154
false
null
package io.awesdroid.libkt.common.utils import com.google.gson.GsonBuilder import com.google.gson.JsonParser import org.json.JSONObject /** * @author Awesdroid */ val Any.TAG: String get() { val tag = javaClass.simpleName return tag.takeIf { it.isNotEmpty() }?.let { if (it.length <= 20) it else it.substring(0, 20) } ?: javaClass.name.takeIf {it.isNotEmpty()}?.let { if (it.length <= 20) it else it.takeLast(20) } ?: "Any" } val prettyJsonString: (String) -> String = { jsonStr -> val jsonElement = JsonParser().parse(jsonStr) GsonBuilder().setPrettyPrinting().create().toJson(jsonElement) } val prettyJsonObject: (JSONObject) -> String = { json -> val jso = JsonParser().parse(json.toString()).asJsonObject GsonBuilder().setPrettyPrinting().create().toJson(jso) }
0
Kotlin
0
0
1d92c378e34af887ee686c3efcfdcfda31cdb061
835
awes-libkt
Apache License 2.0
module-about/src/main/java/com/orange/ods/module/about/ui/OdsAboutViewModel.kt
Orange-OpenSource
440,548,737
false
null
/* * Software Name: Orange Design System * SPDX-FileCopyrightText: Copyright (c) Orange SA * SPDX-License-Identifier: MIT * * This software is distributed under the MIT licence, * the text of which is available at https://opensource.org/license/MIT/ * or see the "LICENSE" file for more details. * * Software description: Android library of reusable graphical components */ package com.orange.ods.module.about.ui import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.orange.ods.module.about.ui.configuration.OdsAboutConfiguration internal class OdsAboutViewModel : ViewModel() { var configuration: OdsAboutConfiguration? by mutableStateOf(null) }
75
null
7
17
5500dbcee3693342533a5a63bdc45b7a752ed0e6
785
ods-android
MIT License
app/src/main/java/com/wk/sunnyweather/logic/Repository.kt
wkkkkk123
689,496,031
false
{"Kotlin": 1879}
package com.wk.sunnyweather.logic object Repository { }
0
Kotlin
0
0
c47adcf64abe14be29b79564a53264ab4a323b82
56
SunnyWeather
Apache License 2.0
notifications/src/main/java/com/sensorberg/notifications/sdk/internal/storage/DelayedActionDao.kt
sensorberg
143,707,474
false
null
package com.sensorberg.notifications.sdk.internal.storage import androidx.room.* import com.sensorberg.notifications.sdk.internal.model.DelayedActionModel @Dao internal abstract class DelayedActionDao { @Query("SELECT * FROM table_delayed_actions WHERE instanceId = :instanceId") abstract fun get(instanceId: String): DelayedActionModel @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(action: DelayedActionModel) @Delete abstract fun delete(action: DelayedActionModel) }
0
Kotlin
0
4
e70fd025feea71ec3becab297809b8af9936658a
496
notifications-sdk-android
MIT License
domain/src/test/java/com/amaringo/domain/centers/CentersUseCaseTest.kt
AdrianMarinGonzalez
329,634,066
false
null
package com.amaringo.domain.centers import com.amaringo.domain.base.Subscriber import com.amaringo.domain.model.CategoryDataDTO import com.amaringo.domain.model.CenterDetailDTO import io.reactivex.Observable import io.reactivex.Single import org.junit.Before import org.junit.Test import org.koin.core.component.inject import org.koin.core.context.loadKoinModules import org.koin.core.qualifier.named import org.koin.dsl.module import org.mockito.BDDMockito.given import org.mockito.Mockito.* import java.lang.Exception class CentersUseCaseTest : BaseUseCaseTest() { val testModule = module { single<CentersRepository> { mock(CentersRepository::class.java) } single(qualifier = named("CategoryDataDTOSubscriber")) { mock(Subscriber::class.java) as Subscriber<CategoryDataDTO> } single(qualifier = named("CenterDetailDTOSubscriber")) { mock(Subscriber::class.java) as Subscriber<CenterDetailDTO> } single { CentersUseCase(get(), get()) } } @Before fun before() { loadKoinModules(testModule) } @Test fun `geCenters should retrieve zone categories from repository`() { val mockDTO = CategoryDataDTO("category", emptyList()) val mockZone = "mockZone" val mockRepositoryResponse = Observable.just(mockDTO) val stubRepository: CentersRepository by inject() `when`(stubRepository.getCenters(mockZone)).thenReturn(mockRepositoryResponse) val mockSubscriber: Subscriber<CategoryDataDTO> by inject(qualifier = named("CategoryDataDTOSubscriber")) val sut: CentersUseCase by inject() sut.getCategories(mockZone, mockSubscriber) verify(stubRepository).getCenters(mockZone) verify(mockSubscriber, times(1)).onNext(mockDTO) } @Test fun `geCenter should retrieve center from repository`() { val mockDTO = CenterDetailDTO("title", "schedule", "address", "description") val mockUrl = "mockUrl" val mockRepositoryResponse = Single.just(mockDTO) val mockRepository: CentersRepository by inject() `when`(mockRepository.getCenter(mockUrl)).thenReturn(mockRepositoryResponse) val mockSubscriber: Subscriber<CenterDetailDTO> by inject(qualifier = named("CenterDetailDTOSubscriber")) val sut: CentersUseCase by inject() sut.getCenter(mockUrl, mockSubscriber) verify(mockRepository).getCenter(mockUrl) verify(mockSubscriber, times(1)).onNext(mockDTO) } @Test(expected = Exception::class) fun `geCenter should call onError when repository call fails`() { val mockUrl = "mockUrl" val mockRepository: CentersRepository by inject() given(mockRepository.getCenter(mockUrl)).willAnswer { throw Exception() } val mockSubscriber: Subscriber<CenterDetailDTO> by inject(qualifier = named("CenterDetailDTOSubscriber")) val sut: CentersUseCase by inject() sut.getCenter(mockUrl, mockSubscriber) verify(mockRepository).getCenter(mockUrl) verify(mockSubscriber, times(1)).onError(any(Exception::class.java)) } }
0
Kotlin
0
0
23375a1c62cdce702d81b65f1b70e0c198bd144b
3,209
CAM-care
The Unlicense
lib/src/main/java/org/altbeacon/beacon/BeaconRegion.kt
AltBeacon
22,342,877
false
{"Java": 782435, "Kotlin": 42700}
package org.altbeacon.beacon class BeaconRegion(uniqueId: String, beaconParser: BeaconParser?, identifiers: List<Identifier>, bluetoothAddress: String?): Region(uniqueId, beaconParser, identifiers, bluetoothAddress, 3) { constructor(uniqueId: String, beaconParser: BeaconParser, id1: String?, id2: String?, id3: String?) : this(uniqueId, beaconParser, listOf(Identifier.parse(id1), Identifier.parse(id2), Identifier.parse(id3)), null) { } constructor(uniqueId: String, macAddress: String) : this(uniqueId, null, arrayListOf(), macAddress) { } }
165
Java
836
2,840
ae4ce8ad11dd961e6d20b17ea0c1a39107c49c61
562
android-beacon-library
Apache License 2.0
app/src/main/java/com/github/kimhun456/memoapplication/data/source/local/MemoDao.kt
kimhun456
370,786,400
false
null
package com.github.kimhun456.memoapplication.data.source.local import com.github.kimhun456.memoapplication.data.entity.MemoEntity import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Single interface MemoDao { fun addMemo(memo: MemoEntity): Completable fun removeMemo(memo: MemoEntity): Completable fun updateMemo(memo: MemoEntity): Completable fun getMemo(id: Long): Single<MemoEntity> fun getAllMemos(): Flowable<List<MemoEntity>> }
0
Kotlin
0
0
3fd0827a1df7b465fa7c0b8bdde9a7d86b0beae9
523
Memo
MIT License
app/src/main/java/ru/maxim/barybians/ui/fragment/profile/ProfileViewModel.kt
maximborodkin
286,116,912
false
null
package ru.maxim.barybians.ui.fragment.profile class ProfileViewModel // application: Application, // postRepository: PostRepository, // private val userRepository: UserRepository, // val userId: Int //) : FeedViewModel(application, postRepository) { // // private val _user: MutableStateFlow<User?> = MutableStateFlow(null) // val user: StateFlow<User?> = _user.asStateFlow() // // override fun initialLoading() { // loadUser() // } // // fun loadUser() = viewModelScope.launch { // internalIsLoading.postValue(true) // try { // _user.emit(userRepository.getUserById(userId)) // postRepository.loadPosts(userId) // } catch (e: Exception) { // val errorMessageRes = when (e) { // is NoConnectionException -> R.string.no_internet_connection // is TimeoutException -> R.string.request_timeout // else -> R.string.an_error_occurred_while_loading_profile // } // internalMessageRes.postValue(errorMessageRes) // } finally { // internalIsLoading.postValue(false) // } // } // // fun editStatus(status: String) = viewModelScope.launch { // try { // userRepository.editStatus(status) // } catch (e: Exception) { // val errorMessageRes = when (e) { // is NoConnectionException -> R.string.no_internet_connection // is TimeoutException -> R.string.request_timeout // else -> R.string.unable_to_edit_status // } // internalMessageRes.postValue(errorMessageRes) // } // } // // class ProfileViewModelFactory @AssistedInject constructor( // private val application: Application, // private val postRepository: PostRepository, // private val preferencesManager: PreferencesManager, // private val userRepository: UserRepository, // @Assisted("userId") private val userId: Int // ) : ViewModelProvider.AndroidViewModelFactory(application) { // override fun <T : ViewModel?> create(modelClass: Class<T>): T { // if (modelClass.isAssignableFrom(ProfileViewModel::class.java)) { // val postId = if (userId <= 0) preferencesManager.userId else userId // // @Suppress("UNCHECKED_CAST") // return ProfileViewModel( // application, // postRepository, // userRepository, // postId // ) as T // } // throw IllegalArgumentException("Inappropriate ViewModel class ${modelClass.simpleName}") // } // // @AssistedFactory // interface Factory { // fun create(@Assisted("userId") userId: Int): ProfileViewModelFactory // } // } //}
0
Kotlin
1
4
ef0796735024eaac8b20e650ba3765bb0a536c13
2,861
Barybians-Android-App
MIT License
app/src/main/java/ru/maxim/barybians/ui/fragment/profile/ProfileViewModel.kt
maximborodkin
286,116,912
false
null
package ru.maxim.barybians.ui.fragment.profile class ProfileViewModel // application: Application, // postRepository: PostRepository, // private val userRepository: UserRepository, // val userId: Int //) : FeedViewModel(application, postRepository) { // // private val _user: MutableStateFlow<User?> = MutableStateFlow(null) // val user: StateFlow<User?> = _user.asStateFlow() // // override fun initialLoading() { // loadUser() // } // // fun loadUser() = viewModelScope.launch { // internalIsLoading.postValue(true) // try { // _user.emit(userRepository.getUserById(userId)) // postRepository.loadPosts(userId) // } catch (e: Exception) { // val errorMessageRes = when (e) { // is NoConnectionException -> R.string.no_internet_connection // is TimeoutException -> R.string.request_timeout // else -> R.string.an_error_occurred_while_loading_profile // } // internalMessageRes.postValue(errorMessageRes) // } finally { // internalIsLoading.postValue(false) // } // } // // fun editStatus(status: String) = viewModelScope.launch { // try { // userRepository.editStatus(status) // } catch (e: Exception) { // val errorMessageRes = when (e) { // is NoConnectionException -> R.string.no_internet_connection // is TimeoutException -> R.string.request_timeout // else -> R.string.unable_to_edit_status // } // internalMessageRes.postValue(errorMessageRes) // } // } // // class ProfileViewModelFactory @AssistedInject constructor( // private val application: Application, // private val postRepository: PostRepository, // private val preferencesManager: PreferencesManager, // private val userRepository: UserRepository, // @Assisted("userId") private val userId: Int // ) : ViewModelProvider.AndroidViewModelFactory(application) { // override fun <T : ViewModel?> create(modelClass: Class<T>): T { // if (modelClass.isAssignableFrom(ProfileViewModel::class.java)) { // val postId = if (userId <= 0) preferencesManager.userId else userId // // @Suppress("UNCHECKED_CAST") // return ProfileViewModel( // application, // postRepository, // userRepository, // postId // ) as T // } // throw IllegalArgumentException("Inappropriate ViewModel class ${modelClass.simpleName}") // } // // @AssistedFactory // interface Factory { // fun create(@Assisted("userId") userId: Int): ProfileViewModelFactory // } // } //}
0
Kotlin
1
4
ef0796735024eaac8b20e650ba3765bb0a536c13
2,861
Barybians-Android-App
MIT License
CompetitiveProgramming/02.FasterOutput.kt
Python-Repository-Hub
481,176,683
true
{"Kotlin": 34742, "Java": 172, "Roff": 74}
// Issuing so many println() calls is too slow, // sinc the output in Kotlin is automatically flushed after each line. // A faster way to write many lines from an array or a list // is to use joinToString() function with "\n" as the operator. fun main() { println(a.joinToString("\n")) }
0
null
0
0
d4d5173ab09df8bf284c79d4b4c4d419afbce0f1
295
kotlin-programming
Apache License 2.0
app/src/main/java/com/dreamsoftware/fitflextv/utils/IOneSideMapper.kt
sergio11
534,529,261
false
{"Kotlin": 615931}
package com.dreamsoftware.saborytv.utils interface IOneSideMapper<IN, OUT> { fun mapInToOut(input: IN): OUT fun mapInListToOutList(input: Iterable<IN>): Iterable<OUT> }
0
Kotlin
3
40
4452dcbcf3d4388144a949c65c216de5547c82a6
177
fitflextv_android
Apache License 2.0
app/src/main/java/com/chalkbox/propertyfinder/ads/application/scopes/AdScope.kt
RiversideOtters
250,147,724
false
null
package com.chalkbox.propertyfinder.ads.application.scopes import kotlin.annotation.AnnotationRetention import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) internal annotation class AdScope
0
Kotlin
0
0
92c3be6363c19a68493fd91546e1bd373bc5ae82
212
PropertyFinder-Android
MIT License
confluence-plugin/src/test/git4c/com/networkedassets/git4c/core/CreateTemporaryDocumentationsContentUseCaseTest.kt
rpaasche
321,741,515
true
{"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716}
package com.networkedassets.git4c.core import com.networkedassets.git4c.application.PluginComponents import com.networkedassets.git4c.boundary.CreateTemporaryDocumentationsContentCommand import com.networkedassets.git4c.boundary.outbound.Id import com.networkedassets.git4c.data.MacroLocation import com.networkedassets.git4c.data.MacroSettings import com.networkedassets.git4c.data.PageAndSpacePermissionsForUser import com.networkedassets.git4c.data.RepositoryWithNoAuthorization import com.networkedassets.git4c.test.UseCaseTest import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.test.assertNotNull class CreateTemporaryDocumentationsContentUseCaseTest : UseCaseTest<CreateTemporaryDocumentationsContentUseCase>() { override fun getUseCase(plugin: PluginComponents): CreateTemporaryDocumentationsContentUseCase { return CreateTemporaryDocumentationsContentUseCase(plugin.bussines) } @Test fun `Temporary macro should be created`() { components.database.macroLocationDatabase.put("macro_1", MacroLocation("macro_1", "page_1", "space_2")) components.providers.macroSettingsProvider.put("macro_1", MacroSettings("macro_1", "repository_1", "master", "default_file", null, null)) components.providers.repositoryProvider.put("repository_1", RepositoryWithNoAuthorization("repository_1", "src/test/resources", false)) val permission = PageAndSpacePermissionsForUser("page_1", "space_2", "test", true) components.cache.pageAndSpacePermissionsForUserCache.put(permission.uuid, permission) val answer = useCase.execute(CreateTemporaryDocumentationsContentCommand("macro_1", "master", "test")) assertNotNull(answer.component1()) assertThat(answer.get()).isInstanceOf(Id::class.java) } }
0
Kotlin
0
0
e55391b33cb70d66bbf5f36ba570fb8822f10953
1,812
git4c
Apache License 2.0
client/android/divkit-demo-app/src/main/java/com/yandex/divkit/demo/div/DivViewHolder.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
package com.yandex.divkit.demo.div import android.view.MotionEvent import androidx.recyclerview.widget.FixScrollTouchHelper import androidx.recyclerview.widget.RecyclerView import com.yandex.div.DivDataTag import com.yandex.div.core.DivViewFacade import com.yandex.div.core.state.DivStatePath import com.yandex.div.core.view2.Div2View class DivViewHolder(val view: Div2View) : RecyclerView.ViewHolder(view), FixScrollTouchHelper.ScrollableHolder { private val paths = listOf( DivStatePath.parse("0/footer_card_m/plain/like_icon/filled"), DivStatePath.parse("0/card_subscribe/subscribe"), DivStatePath.parse("0/footer_card_m/plain/likes_count/incremented") ) fun setData(divItem: DivItem) { if (adapterPosition % 2 == 0) { view.setDataWithStates(divItem.data, DivDataTag(divItem.id), paths, false) } else { view.setData(divItem.data, DivDataTag(divItem.id)) } } override fun hasScrollableViewUnder(event: MotionEvent) = (view as? DivViewFacade)?.hasScrollableViewUnder(event) ?: false }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
1,082
divkit
Apache License 2.0
gradle-plugin/src/test/kotlin/konnekt/gradle/KonnektTest.kt
koperagen
324,244,790
false
null
package konnekt.gradle import io.kotest.assertions.asClue import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.shouldBe import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome class KonnektTest : FreeSpec({ val temp = tempdir() val buildFile = temp.newFile("build.gradle.kts") fun GradleRunner.defaultConfig() { withProjectDir(temp) withPluginClasspath() } "reference to Konnekt resolved" { val result = GradleRunner { defaultConfig() buildFile.writeText( """ |import konnekt.gradle.Konnekt | |plugins { | kotlin("jvm") version "1.4.10" | id("io.github.koperagen.konnekt") |} | |group = "org.example" |version = "1.0-SNAPSHOT" | |repositories { | mavenLocal() | mavenCentral() |} | |tasks.create("konnektVersion") { | doLast { | println(Konnekt.ktorVersion) | } |} """.trimMargin() ) withArguments("konnektVersion") } result.asClue { it.task(":konnektVersion")?.outcome shouldBe TaskOutcome.SUCCESS } } })
0
Kotlin
0
0
c9665f8d71f58322051badf95346ba7773ec1983
1,277
konnekt
Apache License 2.0
src/main/kotlin/com/hjk/advent22/Day05.kt
h-j-k
572,485,447
false
null
package com.hjk.advent22 object Day05 { fun part1(input: List<String>): String = process(input) { it.reversed() } fun part2(input: List<String>): String = process(input) { it } private fun process(input: List<String>, mapper: (String) -> String): String { val (stacks, instructions) = input.indexOf("").let { input.take(it) to input.drop(it + 1) } return instructions.mapNotNull(Move::parse).fold(convertStacks(stacks)) { acc, move -> val from = acc[move.from - 1] val to = acc[move.to - 1] acc[move.from - 1] = from.dropLast(move.n) acc[move.to - 1] = to + mapper(from.takeLast(move.n)) acc }.joinToString(separator = "") { it[it.lastIndex].toString() } } private fun convertStacks(stacks: List<String>): MutableList<String> = (1..stacks.last().count { it.isDigit() }) .map { (it - 1) * 4 + 1 } .map { i -> List(stacks.size - 1) { j -> stacks[stacks.lastIndex - 1 - j].getOrNull(i) ?: ' ' }.filter { it.isLetter() }.joinToString(separator = "") }.toMutableList() private data class Move(val n: Int, val from: Int, val to: Int) { companion object { private val pattern = "move (\\d+) from (\\d+) to (\\d+)".toRegex() fun parse(instruction: String): Move? = pattern.matchEntire(instruction)?.destructured ?.let { (n, from, to) -> Move(n = n.toInt(), from = from.toInt(), to = to.toInt()) } } } }
0
Kotlin
0
0
20d94964181b15faf56ff743b8646d02142c9961
1,586
advent22
Apache License 2.0
test-analysis-core/src/test/kotlin/com/saveourtool/save/test/analysis/algorithms/RegressionDetectionTest.kt
saveourtool
300,279,336
false
{"Kotlin": 3427161, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.save.test.analysis.algorithms import com.saveourtool.common.domain.TestResultStatus import com.saveourtool.save.test.analysis.api.TestStatusProvider import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension /** * @see RegressionDetection */ @ExtendWith(MockitoExtension::class) class RegressionDetectionTest { @Test fun `minimum run count of zero should result in a failure`(@Mock testStatusProvider: TestStatusProvider<TestResultStatus>) { assertThatThrownBy { RegressionDetection(minimumRunCount = 0, testStatusProvider) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Minimum run count should be positive: 0") } @Test fun `negative minimum run count should result in a failure`(@Mock testStatusProvider: TestStatusProvider<TestResultStatus>) { assertThatThrownBy { RegressionDetection(minimumRunCount = -1, testStatusProvider) } .isInstanceOf(IllegalArgumentException::class.java) .hasMessage("Minimum run count should be positive: -1") } }
201
Kotlin
3
38
e101105f8e449253d5fbe81ece2668654d08639f
1,278
save-cloud
MIT License
data/src/main/java/com/catscoffeeandkitchen/data/workouts/network/models/WgerExerciseItem.kt
allisonjoycarter
563,490,185
false
null
package com.catscoffeeandkitchen.data.workouts.network.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class WgerExerciseItem( @Json(name = "author_history") val authorHistory: List<String>, val category: Int, @Json(name = "creation_date") val creationDate: String, val description: String, val equipment: List<Int>, @Json(name = "exercise_base") val exerciseBase: Int, val id: Int, val language: Int, val license: Int, @Json(name = "license_author") val licenseAuthor: String, val muscles: List<Int>, @Json(name = "muscles_secondary") val musclesSecondary: List<Int>, val name: String, val uuid: String, val variations: List<Int> )
1
Kotlin
0
0
1c52a737c7d3d55da242719cb1759b166e1182a5
760
FitnessJournal
MIT License
bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/util/BpdmOAuth2ClientFactory.kt
eclipse-tractusx
526,621,398
false
{"Kotlin": 1748824, "Smarty": 133187, "Dockerfile": 3902, "Java": 2019, "Shell": 1221}
/******************************************************************************* * Copyright (c) 2021,2024 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.eclipse.tractusx.bpdm.test.util import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction import org.springframework.web.reactive.function.client.WebClient import java.util.function.Consumer class BpdmOAuth2ClientFactory( private val clientRegistrationRepository: ClientRegistrationRepository, private val oAuth2AuthorizedClientService: OAuth2AuthorizedClientService ){ fun createClient( baseUrl: String, clientRegistrationId: String): WebClient { return WebClient.builder() .baseUrl(baseUrl) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .apply(oauth2Configuration(clientRegistrationRepository, oAuth2AuthorizedClientService, clientRegistrationId)) .build() } private fun oauth2Configuration( clientRegistrationRepository: ClientRegistrationRepository, authorizedClientService: OAuth2AuthorizedClientService, clientRegistrationId: String ): Consumer<WebClient.Builder> { val authorizedClientManager = authorizedClientManager(clientRegistrationRepository, authorizedClientService) val oauth = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) oauth.setDefaultClientRegistrationId(clientRegistrationId) return oauth.oauth2Configuration() } private fun authorizedClientManager( clientRegistrationRepository: ClientRegistrationRepository, authorizedClientService: OAuth2AuthorizedClientService ): OAuth2AuthorizedClientManager { val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build() val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService) authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) return authorizedClientManager } }
26
Kotlin
15
6
c0c0ccfb385772381a06068d648327291d6ff194
3,483
bpdm
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsEhController.kt
az4521
176,152,541
true
{"Kotlin": 2483150}
package eu.kanade.tachiyomi.ui.setting import android.os.Handler import android.text.InputType import android.widget.Toast import androidx.preference.PreferenceScreen import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.setActionButtonEnabled import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.github.salomonbrys.kotson.fromJson import com.google.gson.Gson import com.kizitonwose.time.Interval import com.kizitonwose.time.days import com.kizitonwose.time.hours import com.tfcporciuncula.flow.Preference import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.preference.PreferenceKeys import eu.kanade.tachiyomi.databinding.EhDialogCategoriesBinding import eu.kanade.tachiyomi.databinding.EhDialogLanguagesBinding import eu.kanade.tachiyomi.ui.webview.WebViewActivity import eu.kanade.tachiyomi.util.preference.defaultValue import eu.kanade.tachiyomi.util.preference.entriesRes import eu.kanade.tachiyomi.util.preference.intListPreference import eu.kanade.tachiyomi.util.preference.listPreference import eu.kanade.tachiyomi.util.preference.multiSelectListPreference import eu.kanade.tachiyomi.util.preference.onChange import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preference import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.summaryRes import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.system.toast import exh.EH_SOURCE_ID import exh.EXH_SOURCE_ID import exh.eh.EHentaiUpdateWorker import exh.eh.EHentaiUpdateWorkerConstants import exh.eh.EHentaiUpdaterStats import exh.favorites.FavoritesIntroDialog import exh.favorites.LocalFavoritesStorage import exh.metadata.metadata.EHentaiSearchMetadata import exh.metadata.metadata.base.getFlatMetadataForManga import exh.metadata.nullIfBlank import exh.uconfig.WarnConfigureDialogController import exh.ui.login.LoginController import exh.util.await import exh.util.trans import humanize.Humanize import java.util.Date import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.take import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uy.kohesive.injekt.injectLazy /** * EH Settings fragment */ class SettingsEhController : SettingsController() { private val gson: Gson by injectLazy() private val db: DatabaseHelper by injectLazy() private fun Preference<*>.reconfigure(): Boolean { // Listen for change commit asFlow() .take(1) // Only listen for first commit .onEach { // Only listen for first change commit WarnConfigureDialogController.uploadSettings(router) } .launchIn(scope) // Always return true to save changes return true } override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { title = "E-Hentai" preferenceCategory { title = "E-Hentai Website Account Settings" switchPreference { title = "Enable ExHentai" summaryOff = "Requires login" key = PreferenceKeys.eh_enableExHentai isPersistent = false defaultValue = false preferences.enableExhentai() .asFlow() .onEach { isChecked = it } .launchIn(scope) onChange { newVal -> newVal as Boolean if (!newVal) { preferences.enableExhentai().set(false) true } else { router.pushController( RouterTransaction.with(LoginController()) .pushChangeHandler(FadeChangeHandler()) .popChangeHandler(FadeChangeHandler()) ) false } } } intListPreference { title = "Use Hentai@Home Network" key = PreferenceKeys.eh_enable_hah if (preferences.eh_hathPerksCookies().get().isBlank()) { summary = "Do you wish to load images through the Hentai@Home Network, if available? Disabling this option will reduce the amount of pages you are able to view\nOptions:\n - Any client (Recommended)\n - Default port clients only (Can be slower. Enable if behind firewall/proxy that blocks outgoing non-standard ports.)" entries = arrayOf( "Any client (Recommended)", "Default port clients only" ) entryValues = arrayOf("0", "1") } else { summary = "Do you wish to load images through the Hentai@Home Network, if available? Disabling this option will reduce the amount of pages you are able to view\nOptions:\n - Any client (Recommended)\n - Default port clients only (Can be slower. Enable if behind firewall/proxy that blocks outgoing non-standard ports.)\n - No (Donator only. You will not be able to browse as many pages, enable only if having severe problems.)" entries = arrayOf( "Any client (Recommended)", "Default port clients only", "No(will select Default port clients only if you are not a donator)" ) entryValues = arrayOf("0", "1", "2") } onChange { preferences.useHentaiAtHome().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { title = "Show Japanese titles in search results" summaryOn = "Currently showing Japanese titles in search results. Clear the chapter cache after changing this (in the Advanced section)" summaryOff = "Currently showing English/Romanized titles in search results. Clear the chapter cache after changing this (in the Advanced section)" key = "use_jp_title" defaultValue = false onChange { preferences.useJapaneseTitle().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { title = "Use original images" summaryOn = "Currently using original images" summaryOff = "Currently using resampled images" key = PreferenceKeys.eh_useOrigImages defaultValue = false onChange { preferences.eh_useOriginalImages().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai preference { title = "Watched Tags" summary = "Opens a webview to your E/ExHentai watched tags page" onClick { val intent = if (preferences.enableExhentai().get()) { WebViewActivity.newIntent(activity!!, url = "https://exhentai.org/mytags", title = "ExHentai Watched Tags") } else { WebViewActivity.newIntent(activity!!, url = "https://e-hentai.org/mytags", title = "E-Hentai Watched Tags") } startActivity(intent) } }.dependency = PreferenceKeys.eh_enableExHentai preference { title = "Tag Filtering Threshold" key = PreferenceKeys.eh_tag_filtering_value defaultValue = 0 summary = "You can soft filter tags by adding them to the \"My Tags\" E/ExHentai page with a negative weight. If a gallery has tags that add up to weight below this value, it is filtered from view. This threshold can be set between -9999 and 0. Currently: ${preferences.ehTagFilterValue().get()}" onClick { MaterialDialog(activity!!) .title(text = "Tag Filtering Threshold") .input( inputType = InputType.TYPE_NUMBER_FLAG_SIGNED, waitForPositiveButton = false, allowEmpty = false ) { dialog, number -> val inputField = dialog.getInputField() val value = number.toString().toIntOrNull() if (value != null && value in -9999..0) { inputField.error = null } else { inputField.error = "Must be between -9999 and 0!" } dialog.setActionButtonEnabled(WhichButton.POSITIVE, value != null && value in -9999..0) } .positiveButton(android.R.string.ok) { val value = it.getInputField().text.toString().toInt() preferences.ehTagFilterValue().set(value) summary = "You can soft filter tags by adding them to the \"My Tags\" E/ExHentai page with a negative weight. If a gallery has tags that add up to weight below this value, it is filtered from view. This threshold can be set between 0 and -9999. Currently: $value" preferences.ehTagFilterValue().reconfigure() } .show() } }.dependency = PreferenceKeys.eh_enableExHentai preference { title = "Tag Watching Threshold" key = PreferenceKeys.eh_tag_watching_value defaultValue = 0 summary = "Recently uploaded galleries will be included on the watched screen if it has at least one watched tag with positive weight, and the sum of weights on its watched tags add up to this value or higher. This threshold can be set between 0 and 9999. Currently: ${preferences.ehTagWatchingValue().get()}" onClick { MaterialDialog(activity!!) .title(text = "Tag Watching Threshold") .input( inputType = InputType.TYPE_NUMBER_FLAG_SIGNED, maxLength = 4, waitForPositiveButton = false, allowEmpty = false ) { dialog, number -> val inputField = dialog.getInputField() val value = number.toString().toIntOrNull() if (value != null && value in 0..9999) { inputField.error = null } else { inputField.error = "Must be between 0 and 9999!" } dialog.setActionButtonEnabled(WhichButton.POSITIVE, value != null && value in 0..9999) } .positiveButton(android.R.string.ok) { val value = it.getInputField().text.toString().toInt() preferences.ehTagWatchingValue().set(value) summary = "Recently uploaded galleries will be included on the watched screen if it has at least one watched tag with positive weight, and the sum of weights on its watched tags add up to this value or higher. This threshold can be set between 0 and 9999. Currently: $value" preferences.ehTagWatchingValue().reconfigure() } .show() } }.dependency = PreferenceKeys.eh_enableExHentai preference { title = "Language Filtering" summary = "If you wish to hide galleries in certain languages from the gallery list and searches, select them in the dialog that will popup.\nNote that matching galleries will never appear regardless of your search query.\nTldr checkmarked = exclude" onClick { MaterialDialog(activity!!) .title(text = "Language Filtering") .message(text = "If you wish to hide galleries in certain languages from the gallery list and searches, select them in the dialog that will popup.\nNote that matching galleries will never appear regardless of your search query.\nTldr checkmarked = exclude") .customView(R.layout.eh_dialog_languages, scrollable = true) .positiveButton(android.R.string.ok) { val customView = it.view.contentLayout.customView!! val binding = EhDialogLanguagesBinding.bind(customView) val languages = with(customView) { listOfNotNull( "${binding.japaneseOriginal.isChecked}*${binding.japaneseTranslated.isChecked}*${binding.japaneseRewrite.isChecked}", "${binding.englishOriginal.isChecked}*${binding.englishTranslated.isChecked}*${binding.englishRewrite.isChecked}", "${binding.chineseOriginal.isChecked}*${binding.chineseTranslated.isChecked}*${binding.chineseRewrite.isChecked}", "${binding.dutchOriginal.isChecked}*${binding.dutchTranslated.isChecked}*${binding.dutchRewrite.isChecked}", "${binding.frenchOriginal.isChecked}*${binding.frenchTranslated.isChecked}*${binding.frenchRewrite.isChecked}", "${binding.germanOriginal.isChecked}*${binding.germanTranslated.isChecked}*${binding.germanRewrite.isChecked}", "${binding.hungarianOriginal.isChecked}*${binding.hungarianTranslated.isChecked}*${binding.hungarianRewrite.isChecked}", "${binding.italianOriginal.isChecked}*${binding.italianTranslated.isChecked}*${binding.italianRewrite.isChecked}", "${binding.koreanOriginal.isChecked}*${binding.koreanTranslated.isChecked}*${binding.koreanRewrite.isChecked}", "${binding.polishOriginal.isChecked}*${binding.polishTranslated.isChecked}*${binding.polishRewrite.isChecked}", "${binding.portugueseOriginal.isChecked}*${binding.portugueseTranslated.isChecked}*${binding.portugueseRewrite.isChecked}", "${binding.russianOriginal.isChecked}*${binding.russianTranslated.isChecked}*${binding.russianRewrite.isChecked}", "${binding.spanishOriginal.isChecked}*${binding.spanishTranslated.isChecked}*${binding.spanishRewrite.isChecked}", "${binding.thaiOriginal.isChecked}*${binding.thaiTranslated.isChecked}*${binding.thaiRewrite.isChecked}", "${binding.vietnameseOriginal.isChecked}*${binding.vietnameseTranslated.isChecked}*${binding.vietnameseRewrite.isChecked}", "${binding.notAvailableOriginal.isChecked}*${binding.notAvailableTranslated.isChecked}*${binding.notAvailableRewrite.isChecked}", "${binding.otherOriginal.isChecked}*${binding.otherTranslated.isChecked}*${binding.otherRewrite.isChecked}" ).joinToString("\n") } preferences.eh_settingsLanguages().set(languages) preferences.eh_settingsLanguages().reconfigure() } .show { val customView = this.view.contentLayout.customView!! val binding = EhDialogLanguagesBinding.bind(customView) val settingsLanguages = preferences.eh_settingsLanguages().get().split("\n") val japanese = settingsLanguages[0].split("*").map { it.toBoolean() } val english = settingsLanguages[1].split("*").map { it.toBoolean() } val chinese = settingsLanguages[2].split("*").map { it.toBoolean() } val dutch = settingsLanguages[3].split("*").map { it.toBoolean() } val french = settingsLanguages[4].split("*").map { it.toBoolean() } val german = settingsLanguages[5].split("*").map { it.toBoolean() } val hungarian = settingsLanguages[6].split("*").map { it.toBoolean() } val italian = settingsLanguages[7].split("*").map { it.toBoolean() } val korean = settingsLanguages[8].split("*").map { it.toBoolean() } val polish = settingsLanguages[9].split("*").map { it.toBoolean() } val portuguese = settingsLanguages[10].split("*").map { it.toBoolean() } val russian = settingsLanguages[11].split("*").map { it.toBoolean() } val spanish = settingsLanguages[12].split("*").map { it.toBoolean() } val thai = settingsLanguages[13].split("*").map { it.toBoolean() } val vietnamese = settingsLanguages[14].split("*").map { it.toBoolean() } val notAvailable = settingsLanguages[15].split("*").map { it.toBoolean() } val other = settingsLanguages[16].split("*").map { it.toBoolean() } with(customView) { binding.japaneseOriginal.isChecked = japanese[0] binding.japaneseTranslated.isChecked = japanese[1] binding.japaneseRewrite.isChecked = japanese[2] binding.englishOriginal.isChecked = english[0] binding.englishTranslated.isChecked = english[1] binding.englishRewrite.isChecked = english[2] binding.chineseOriginal.isChecked = chinese[0] binding.chineseTranslated.isChecked = chinese[1] binding.chineseRewrite.isChecked = chinese[2] binding.dutchOriginal.isChecked = dutch[0] binding.dutchTranslated.isChecked = dutch[1] binding.dutchRewrite.isChecked = dutch[2] binding.frenchOriginal.isChecked = french[0] binding.frenchTranslated.isChecked = french[1] binding.frenchRewrite.isChecked = french[2] binding.germanOriginal.isChecked = german[0] binding.germanTranslated.isChecked = german[1] binding.germanRewrite.isChecked = german[2] binding.hungarianOriginal.isChecked = hungarian[0] binding.hungarianTranslated.isChecked = hungarian[1] binding.hungarianRewrite.isChecked = hungarian[2] binding.italianOriginal.isChecked = italian[0] binding.italianTranslated.isChecked = italian[1] binding.italianRewrite.isChecked = italian[2] binding.koreanOriginal.isChecked = korean[0] binding.koreanTranslated.isChecked = korean[1] binding.koreanRewrite.isChecked = korean[2] binding.polishOriginal.isChecked = polish[0] binding.polishTranslated.isChecked = polish[1] binding.polishRewrite.isChecked = polish[2] binding.portugueseOriginal.isChecked = portuguese[0] binding.portugueseTranslated.isChecked = portuguese[1] binding.portugueseRewrite.isChecked = portuguese[2] binding.russianOriginal.isChecked = russian[0] binding.russianTranslated.isChecked = russian[1] binding.russianRewrite.isChecked = russian[2] binding.spanishOriginal.isChecked = spanish[0] binding.spanishTranslated.isChecked = spanish[1] binding.spanishRewrite.isChecked = spanish[2] binding.thaiOriginal.isChecked = thai[0] binding.thaiTranslated.isChecked = thai[1] binding.thaiRewrite.isChecked = thai[2] binding.vietnameseOriginal.isChecked = vietnamese[0] binding.vietnameseTranslated.isChecked = vietnamese[1] binding.vietnameseRewrite.isChecked = vietnamese[2] binding.notAvailableOriginal.isChecked = notAvailable[0] binding.notAvailableTranslated.isChecked = notAvailable[1] binding.notAvailableRewrite.isChecked = notAvailable[2] binding.otherOriginal.isChecked = other[0] binding.otherTranslated.isChecked = other[1] binding.otherRewrite.isChecked = other[2] } } } }.dependency = PreferenceKeys.eh_enableExHentai preference { title = "Front Page Categories" summary = "What categories would you like to show by default on the front page and in searches? They can still be enabled by enabling their filters" onClick { MaterialDialog(activity!!) .title(text = "Front Page Categories") .message(text = "What categories would you like to show by default on the front page and in searches? They can still be enabled by enabling their filters") .customView(R.layout.eh_dialog_categories, scrollable = true) .positiveButton { val customView = it.view.contentLayout.customView!! val binding = EhDialogCategoriesBinding.bind(customView) with(customView) { preferences.eh_EnabledCategories().set( listOf( (!binding.doujinshiCheckbox.isChecked).toString(), (!binding.mangaCheckbox.isChecked).toString(), (!binding.artistCgCheckbox.isChecked).toString(), (!binding.gameCgCheckbox.isChecked).toString(), (!binding.westernCheckbox.isChecked).toString(), (!binding.nonHCheckbox.isChecked).toString(), (!binding.imageSetCheckbox.isChecked).toString(), (!binding.cosplayCheckbox.isChecked).toString(), (!binding.asianPornCheckbox.isChecked).toString(), (!binding.miscCheckbox.isChecked).toString() ).joinToString(",") ) } preferences.eh_EnabledCategories().reconfigure() } .show { val customView = this.view.contentLayout.customView!! val binding = EhDialogCategoriesBinding.bind(customView) with(customView) { val list = preferences.eh_EnabledCategories().get().split(",").map { !it.toBoolean() } binding.doujinshiCheckbox.isChecked = list[0] binding.mangaCheckbox.isChecked = list[1] binding.artistCgCheckbox.isChecked = list[2] binding.gameCgCheckbox.isChecked = list[3] binding.westernCheckbox.isChecked = list[4] binding.nonHCheckbox.isChecked = list[5] binding.imageSetCheckbox.isChecked = list[6] binding.cosplayCheckbox.isChecked = list[7] binding.asianPornCheckbox.isChecked = list[8] binding.miscCheckbox.isChecked = list[9] } } } }.dependency = PreferenceKeys.eh_enableExHentai switchPreference { defaultValue = false key = PreferenceKeys.eh_watched_list_default_state title = "Watched List Filter Default State" summary = "When browsing ExHentai/E-Hentai should the watched list filter be enabled by default" } switchPreference { defaultValue = true key = PreferenceKeys.eh_secure_exh title = "Secure ExHentai/E-Hentai" summary = "Use the HTTPS version of ExHentai/E-Hentai." } listPreference { defaultValue = "auto" key = PreferenceKeys.eh_ehentai_quality summary = "The quality of the downloaded images" title = "Image quality" entries = arrayOf( "Auto", "2400x", "1600x", "1280x", "980x", "780x" ) entryValues = arrayOf( "auto", "ovrs_2400", "ovrs_1600", "high", "med", "low" ) onChange { preferences.imageQuality().reconfigure() } }.dependency = PreferenceKeys.eh_enableExHentai } preferenceCategory { title = "Favorites sync" switchPreference { title = "Disable favorites uploading" summary = "Favorites are only downloaded from ExHentai. Any changes to favorites in the app will not be uploaded. Prevents accidental loss of favorites on ExHentai. Note that removals will still be downloaded (if you remove a favorites on ExHentai, it will be removed in the app as well)." key = PreferenceKeys.eh_readOnlySync defaultValue = false } preference { title = "Show favorites sync notes" summary = "Show some information regarding the favorites sync feature" onClick { activity?.let { FavoritesIntroDialog().show(it) } } } switchPreference { title = "Ignore sync errors when possible" summary = "Do not abort immediately when encountering errors during the sync process. Errors will still be displayed when the sync is complete. Can cause loss of favorites in some cases. Useful when syncing large libraries." key = PreferenceKeys.eh_lenientSync defaultValue = false } preference { title = "Force sync state reset" summary = "Performs a full resynchronization on the next sync. Removals will not be synced. All favorites in the app will be re-uploaded to ExHentai and all favorites on ExHentai will be re-downloaded into the app. Useful for repairing sync after sync has been interrupted." onClick { activity?.let { activity -> MaterialDialog(activity) .title(R.string.eh_force_sync_reset_title) .message(R.string.eh_force_sync_reset_message) .positiveButton(android.R.string.yes) { LocalFavoritesStorage().apply { getRealm().use { it.trans { clearSnapshots(it) } } } activity.toast("Sync state reset", Toast.LENGTH_LONG) } .negativeButton(android.R.string.no) .cancelable(false) .show() } } } } preferenceCategory { title = "Gallery update checker" intListPreference { key = PreferenceKeys.eh_autoUpdateFrequency title = "Time between update batches" entries = arrayOf( "Never update galleries", "1 hour", "2 hours", "3 hours", "6 hours", "12 hours", "24 hours", "48 hours" ) entryValues = arrayOf("0", "1", "2", "3", "6", "12", "24", "48") defaultValue = "0" preferences.eh_autoUpdateFrequency().asFlow() .onEach { newVal -> summary = if (newVal == 0) { "${context.getString(R.string.app_name)} will currently never check galleries in your library for updates." } else { "${context.getString(R.string.app_name)} checks/updates galleries in batches. " + "This means it will wait $newVal hour(s), check ${EHentaiUpdateWorkerConstants.UPDATES_PER_ITERATION} galleries," + " wait $newVal hour(s), check ${EHentaiUpdateWorkerConstants.UPDATES_PER_ITERATION} and so on..." } } .launchIn(scope) onChange { newValue -> val interval = (newValue as String).toInt() EHentaiUpdateWorker.scheduleBackground(context, interval) true } } multiSelectListPreference { key = PreferenceKeys.eh_autoUpdateRestrictions title = "Auto update restrictions" entriesRes = arrayOf(R.string.wifi, R.string.charging) entryValues = arrayOf("wifi", "ac") summaryRes = R.string.pref_library_update_restriction_summary preferences.eh_autoUpdateFrequency().asFlow() .onEach { isVisible = it > 0 } .launchIn(scope) onChange { // Post to event looper to allow the preference to be updated. Handler().post { EHentaiUpdateWorker.scheduleBackground(context) } true } } preference { title = "Show updater statistics" onClick { val progress = MaterialDialog(context) .message(R.string.eh_show_update_statistics_dialog) .cancelable(false) progress.show() GlobalScope.launch(Dispatchers.IO) { val updateInfo = try { val stats = preferences.eh_autoUpdateStats().get().nullIfBlank()?.let { gson.fromJson<EHentaiUpdaterStats>(it) } val statsText = if (stats != null) { "The updater last ran ${Humanize.naturalTime(Date(stats.startTime))}, and checked ${stats.updateCount} out of the ${stats.possibleUpdates} galleries that were ready for checking." } else "The updater has not ran yet." val allMeta = db.getFavoriteMangaWithMetadata().await().filter { it.source == EH_SOURCE_ID || it.source == EXH_SOURCE_ID }.mapNotNull { db.getFlatMetadataForManga(it.id!!).await() ?.raise<EHentaiSearchMetadata>() }.toList() fun metaInRelativeDuration(duration: Interval<*>): Int { val durationMs = duration.inMilliseconds.longValue return allMeta.asSequence().filter { System.currentTimeMillis() - it.lastUpdateCheck < durationMs }.count() } """ $statsText Galleries that were checked in the last: - hour: ${metaInRelativeDuration(1.hours)} - 6 hours: ${metaInRelativeDuration(6.hours)} - 12 hours: ${metaInRelativeDuration(12.hours)} - day: ${metaInRelativeDuration(1.days)} - 2 days: ${metaInRelativeDuration(2.days)} - week: ${metaInRelativeDuration(7.days)} - month: ${metaInRelativeDuration(30.days)} - year: ${metaInRelativeDuration(365.days)} """.trimIndent() } finally { progress.dismiss() } withContext(Dispatchers.Main) { MaterialDialog(context) .title(text = "Gallery updater statistics") .message(text = updateInfo) .positiveButton(android.R.string.ok) .show() } } } } } } }
22
Kotlin
18
471
a72df3df5073300e02054ee75dc990d196cd6db8
35,757
TachiyomiAZ
Apache License 2.0
domain/src/main/java/com/dennytech/domain/base/BaseSuspendUseCase.kt
OlukaDenis
740,856,818
false
{"Kotlin": 55503}
package com.dennytech.domain.base import com.dennytech.domain.dispacher.AppDispatcher import kotlinx.coroutines.withContext /** * A base util class that is invoked runs on the IO thread asynchronously * Returns a coroutine suspend function */ abstract class BaseSuspendUseCase<in Param, Result>( private val dispatcher: AppDispatcher ) where Param : Any { abstract suspend fun run(param: Param? = null): Result suspend operator fun invoke(param: Param? = null): Result = withContext(dispatcher.io) { run(param) } }
0
Kotlin
0
0
b48257019acf0a7739289c62ff5441e12ec5a001
541
pay-dash
The Unlicense
music/src/main/java/academy/compose/music/ui/MusicCatalog.kt
roshanrai06
464,025,442
false
{"Kotlin": 787329}
/* * Copyright 2022 Compose Academy * * 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 academy.compose.music.ui import academy.compose.music.MusicViewModel import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.lifecycle.viewmodel.compose.viewModel @ExperimentalFoundationApi @ExperimentalAnimationApi @ExperimentalMaterialApi @Composable fun MusicCatalog() { val viewModel = viewModel<MusicViewModel>() val state = viewModel.uiState.collectAsState().value MaterialTheme { Dashboard( state = state, handleEvent = viewModel::handleEvent ) } }
0
Kotlin
0
0
ee22b8b47490e62925e7aa4741c469e2fcbb982a
1,397
Compose_Acadmy
Apache License 2.0
app/src/main/java/com/soneso/lumenshine/presentation/settings/ChangeTfaFragment.kt
Soneso
144,008,654
false
null
package com.soneso.lumenshine.presentation.settings import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.NavHostFragment import com.soneso.lumenshine.R import com.soneso.lumenshine.domain.data.ErrorCodes import com.soneso.lumenshine.networking.dto.exceptions.ServerException import com.soneso.lumenshine.presentation.general.LsFragment import com.soneso.lumenshine.util.GeneralUtils import com.soneso.lumenshine.util.LsException import com.soneso.lumenshine.util.Resource import kotlinx.android.synthetic.main.fragment_change_tfa.* /** * A simple [Fragment] subclass. */ class ChangeTfaFragment : LsFragment() { private var shouldAutoPaste: Boolean = false private lateinit var viewModel: ChangeTfaViewModel private lateinit var tfaSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory)[ChangeTfaViewModel::class.java] } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_change_tfa, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupListeners() subscribeToLiveData() } override fun onResume() { super.onResume() val textFromClipboard: String = GeneralUtils.pasteFromClipboard(context!!) if (shouldAutoPaste && textFromClipboard.toIntOrNull() != null) { tfaInputView.trimmedText = textFromClipboard tfaInputView.setSelection(textFromClipboard.length) } } override fun onPause() { super.onPause() shouldAutoPaste = true } private fun setupListeners() { passInput.setOnEditorActionListener { attemptTfaChange() } passNextButton.setOnClickListener { attemptTfaChange() } copyButton.setOnClickListener { showSnackbar(R.string.copied_to_clipboard) context?.let { it1 -> GeneralUtils.copyToClipboard(it1, tfaSecret) } } tfaCancelButton.setOnClickListener { viewFlipper.displayedChild = viewFlipper.indexOfChild(passStepLayout) } tfaInputView.setOnEditorActionListener { attemptConfirmTfa() } tfaNextButton.setOnClickListener { attemptConfirmTfa() } doneButton.setOnClickListener { NavHostFragment.findNavController(this).navigateUp() } } private fun attemptTfaChange() { if (passInput.isValidPassword()) { viewModel.changeTfa(passInput.trimmedText) } } private fun attemptConfirmTfa() { if (tfaInputView.hasValidInput()) { viewModel.confirmTfa(tfaSecret, tfaInputView.trimmedText) } } private fun subscribeToLiveData() { viewModel.liveTfaSecret.observe(this, Observer { renderTfaSecret(it ?: return@Observer) }) viewModel.liveTfaConfirmation.observe(this, Observer { renderTfaConfirmation(it ?: return@Observer) }) } private fun renderTfaSecret(resource: Resource<String, LsException>) { when (resource.state) { Resource.LOADING -> showLoadingView(true) Resource.FAILURE -> { showLoadingView(false) handlePassError(resource.failure()) } Resource.SUCCESS -> { showLoadingView(false) tfaSecret = resource.success() tfaSecretView.text = getString(R.string.lbl_tfa_secret, resource.success()) tfaInputView.trimmedText = "" viewFlipper.displayedChild = viewFlipper.indexOfChild(tfaSecretStepLayout) } } } private fun handlePassError(failure: LsException) { if (failure is ServerException && failure.code == ErrorCodes.LOGIN_WRONG_PASSWORD) { passInput.error = getString(R.string.login_password_wrong) } else { showErrorSnackbar(failure) } } private fun renderTfaConfirmation(resource: Resource<Unit, LsException>) { when (resource.state) { Resource.LOADING -> showLoadingView(true) Resource.FAILURE -> { showLoadingView(false) handleTfaError(resource.failure()) } Resource.SUCCESS -> { showLoadingView(false) viewFlipper.displayedChild = viewFlipper.indexOfChild(successLayout) } } } private fun handleTfaError(failure: LsException) { if (failure is ServerException) { tfaInputView.error = failure.displayMessage } else { showErrorSnackbar(failure) } } }
0
Kotlin
2
1
a088d0107dbe769c2814b199dddea0177a9aabec
5,062
lumenshine-android-wallet
Apache License 2.0
dokka-storybook-plugin/src/main/kotlin/d2/dokka/storybook/model/doc/DocumentableIndexes.kt
komune-io
758,452,540
false
{"Kotlin": 149800, "MDX": 17045, "Makefile": 1682, "JavaScript": 1469, "Dockerfile": 963, "CSS": 102}
package d2.dokka.storybook.model.doc import d2.dokka.storybook.model.doc.tag.Child import d2.dokka.storybook.model.doc.tag.D2Type import d2.dokka.storybook.model.doc.tag.Parent import d2.dokka.storybook.model.doc.utils.d2DocTagExtra import d2.dokka.storybook.model.doc.utils.documentableIn import d2.dokka.storybook.model.doc.utils.isOfType import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.DTypeAlias import org.jetbrains.dokka.model.Documentable import org.jetbrains.dokka.model.WithSupertypes data class DocumentableIndexes( val documentables: Map<DRI, Documentable>, val childToParentMap: Map<DRI, DRI>, val parentToChildMap: Map<DRI, List<DRI>> ) { companion object { fun from(documentables: List<Documentable>): DocumentableIndexes { val documentablesIndex = documentables.associateBy(Documentable::dri).toMutableMap() val (inheritedDocumentables, actualDocumentables) = documentables.partition { it.isOfType(D2Type.INHERIT) } inheritedDocumentables.forEach { documentable -> documentablesIndex[documentable.dri] = documentable.supertypeIn(documentablesIndex) } val childToParentMap = actualDocumentables.buildChildToParentMap() val parentToChildMap = childToParentMap.entries.groupBy({ it.value }, { it.key }) return DocumentableIndexes( documentables = documentablesIndex, childToParentMap = childToParentMap, parentToChildMap = parentToChildMap ) } @Suppress("ThrowsCount") private fun <T: Documentable> T.supertypeIn(index: Map<DRI, Documentable>): Documentable { val superDocumentables = when (this) { is WithSupertypes -> supertypes.values.flatten().mapNotNull { it.typeConstructor.documentableIn(index) } is DTypeAlias -> underlyingType.values.mapNotNull { it.documentableIn(index)?.supertypeIn(index) } else -> throw IllegalArgumentException("'${D2Type.INHERIT.id}' d2 type is not supported for $dri") } return when (superDocumentables.size) { 0 -> throw IllegalArgumentException( "$dri is tagged with '${D2Type.INHERIT.id}' but none of its supertypes are tagged with @d2" ) 1 -> superDocumentables.first().let { if (it.isOfType(D2Type.INHERIT)) { it.supertypeIn(index) } else { it } } else -> throw IllegalArgumentException( "$dri is tagged with '${D2Type.INHERIT.id}' but more than one of its supertypes are tagged with @d2" ) } } private fun Collection<Documentable>.buildChildToParentMap(): Map<DRI, DRI> { val childToParentMap = flatMap { documentable -> val parentDri = documentable.d2DocTagExtra() .firstTagOfTypeOrNull<Parent>() ?.target val childrenDri = documentable.d2DocTagExtra() .filterTagsOfType<Child>() .mapNotNull(Child::target) parentDri?.let { listOf(documentable.dri to it) } .orEmpty() .plus(childrenDri.map { it to documentable.dri }) }.toMap() checkOrphans(childToParentMap) return childToParentMap } private fun Collection<Documentable>.checkOrphans(childToParentMap: Map<DRI, DRI>) { val orphanDocumentables = this.filter { documentable -> documentable.dri !in childToParentMap && documentable !is PageDocumentable && !documentable.isOfType(D2Type.HIDDEN) } if (orphanDocumentables.isNotEmpty()) { throw IllegalArgumentException( "Found ${orphanDocumentables.size} orphan documentables. " + "These documentables must be assigned to a @d2 page in order to be displayed " + "(or to a parent that has a page in its ancestors):\n" + orphanDocumentables.joinToString("\n") { "- ${it.dri.toString().substringBefore("///")}" } ) } } } }
0
Kotlin
0
0
764a1a71b031a78d7ad06025c2ee610ddcde7ac8
4,459
fixers-d2
Apache License 2.0
src/main/kotlin/com/nmote/jwti/web/GoogleLoginController.kt
vnesek
92,741,847
false
null
/* * Copyright 2017. <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.nmote.jwti.web import com.fasterxml.jackson.databind.ObjectMapper import com.github.scribejava.apis.openid.OpenIdOAuth2AccessToken import com.github.scribejava.core.model.OAuthRequest import com.github.scribejava.core.model.Verb import com.github.scribejava.core.oauth.OAuth20Service import com.nmote.jwti.config.GoogleAccount import com.nmote.jwti.model.SocialAccount import com.nmote.jwti.repository.AppRepository import com.nmote.jwti.repository.UserRepository import com.nmote.jwti.service.ScopeService import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.boot.autoconfigure.condition.ConditionalOnBean import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.CookieValue import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import javax.servlet.http.HttpServletResponse @ConditionalOnBean(name = ["googleOAuthService"]) @Controller @RequestMapping("/google") class GoogleLoginController @Autowired constructor( @Qualifier("googleOAuthService") service: OAuth20Service, objectMapper: ObjectMapper, users: UserRepository, apps: AppRepository, tokens: TokenCache, scopes: ScopeService ) : OAuthLoginController<OAuth20Service, OpenIdOAuth2AccessToken>(service, objectMapper, users, apps, tokens, scopes) { @RequestMapping("callback") fun callback( @RequestParam code: String, @CookieValue("authState") authState: String, response: HttpServletResponse ): String { val accessToken = service.getAccessToken(code) as OpenIdOAuth2AccessToken return callback(accessToken, authState, response) } override fun getSocialAccount(accessToken: OpenIdOAuth2AccessToken): SocialAccount<*> { val request = OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v3/userinfo") service.signRequest(accessToken, request) val response = service.execute(request) val responseBody = response.body val account = objectMapper.readValue(responseBody, GoogleAccount::class.java) account.accessToken = accessToken return account } override val authorizationUrl: String get() = service.authorizationUrl }
0
Kotlin
0
1
794592e2074918bb2c8a1c2d4c3154c29a7dba91
2,969
nmote-jwt-issuer
Apache License 2.0
app/src/main/java/com/temtem/interactive/map/temzone/core/validation/model/ValidationResult.kt
Temtem-Interactive-Map
568,136,913
false
null
package com.temtem.interactive.map.temzone.core.validation.model data class ValidationResult( val message: String? = null, val successful: Boolean = message == null, )
0
Kotlin
0
1
338c95ef870b6ead4a58daec914c99583f1dc294
177
Temzone-Android
MIT License
app/src/main/java/com/richarddorian/medialibrary/fragments/SettingsFragment.kt
RichardDorian
378,622,019
false
null
package com.richarddorian.medialibrary.fragments import android.content.Intent import android.os.Bundle import android.provider.DocumentsContract import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import com.richarddorian.medialibrary.MainActivity import com.richarddorian.medialibrary.R import org.w3c.dom.Document class SettingsFragment(private val context: MainActivity) : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_settings, container, false) view.findViewById<Button>(R.id.load_omp_button).setOnClickListener { requestOMPFile() } return view } private lateinit var requestFileIntent: Intent private fun requestOMPFile() { } }
0
Kotlin
0
1
ebb4d8897f7461b24900190e1f367c49412a7ef5
978
MediaLibrary
MIT License
app/src/main/java/com/richarddorian/medialibrary/fragments/SettingsFragment.kt
RichardDorian
378,622,019
false
null
package com.richarddorian.medialibrary.fragments import android.content.Intent import android.os.Bundle import android.provider.DocumentsContract import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import com.richarddorian.medialibrary.MainActivity import com.richarddorian.medialibrary.R import org.w3c.dom.Document class SettingsFragment(private val context: MainActivity) : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_settings, container, false) view.findViewById<Button>(R.id.load_omp_button).setOnClickListener { requestOMPFile() } return view } private lateinit var requestFileIntent: Intent private fun requestOMPFile() { } }
0
Kotlin
0
1
ebb4d8897f7461b24900190e1f367c49412a7ef5
978
MediaLibrary
MIT License
android/feature/spotify/src/main/java/ly/david/musicsearch/android/feature/spotify/internal/SpotifyUiEvent.kt
lydavid
458,021,427
false
{"Kotlin": 1447800, "HTML": 1356155, "Swift": 4205, "Python": 3489, "Shell": 1543, "Ruby": 955}
package ly.david.musicsearch.android.feature.spotify.internal import com.slack.circuit.runtime.CircuitUiEvent import ly.david.musicsearch.core.models.network.MusicBrainzEntity internal sealed interface SpotifyUiEvent : CircuitUiEvent { data object NavigateUp : SpotifyUiEvent data class GoToSearch( val query: String, val entity: MusicBrainzEntity, ) : SpotifyUiEvent }
116
Kotlin
0
17
2bc99d4ce18aff77c121078e661e7878b450ea79
400
MusicSearch
Apache License 2.0
openai-gateway/openai-gateway-core/src/commonMain/kotlin/com/tddworks/openai/gateway/api/internal/AnthropicOpenAIProvider.kt
tddworks
755,029,221
false
{"Kotlin": 328879}
package com.tddworks.openai.gateway.api.internal import com.tddworks.anthropic.api.Anthropic import com.tddworks.anthropic.api.AnthropicConfig import com.tddworks.anthropic.api.AnthropicModel import com.tddworks.anthropic.api.messages.api.* import com.tddworks.openai.api.chat.api.ChatCompletionRequest import com.tddworks.openai.api.chat.api.OpenAIModel import com.tddworks.openai.api.legacy.completions.api.Completion import com.tddworks.openai.api.legacy.completions.api.CompletionRequest import com.tddworks.openai.gateway.api.OpenAIProvider import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.transform import kotlinx.serialization.ExperimentalSerializationApi import com.tddworks.openai.api.chat.api.ChatCompletion as OpenAIChatCompletion import com.tddworks.openai.api.chat.api.ChatCompletionChunk as OpenAIChatCompletionChunk @OptIn(ExperimentalSerializationApi::class) class AnthropicOpenAIProvider( override var id: String = "anthropic", override var name: String = "Anthropic", override var models: List<OpenAIModel> = AnthropicModel.availableModels.map { OpenAIModel(it.value) }, override var config: AnthropicOpenAIProviderConfig, private val client: Anthropic = Anthropic.create( AnthropicConfig( apiKey = config.apiKey, baseUrl = config.baseUrl, anthropicVersion = config.anthropicVersion ) ) ) : OpenAIProvider { /** * Check if the given OpenAIModel is supported by the available models. * @param model The OpenAIModel to check for support. * @return true if the model is supported, false otherwise. */ override fun supports(model: OpenAIModel): Boolean { return models.any { it.value == model.value } } /** * Override function to fetch completions from OpenAI API based on the given ChatCompletionRequest * @param request the ChatCompletionRequest object containing information needed to generate completions * @return OpenAIChatCompletion object containing completions generated from the OpenAI API */ override suspend fun chatCompletions(request: ChatCompletionRequest): OpenAIChatCompletion { val anthropicRequest = request.toAnthropicRequest() return client.create(anthropicRequest).toOpenAIChatCompletion() } /** * A function that streams completions for chat based on the given ChatCompletionRequest * * @param request The ChatCompletionRequest containing the request details * @return A Flow of OpenAIChatCompletionChunk objects representing the completions */ override fun streamChatCompletions(request: ChatCompletionRequest): Flow<OpenAIChatCompletionChunk> { return client.stream( request.toAnthropicRequest().copy( stream = true ) ).filter { it !is ContentBlockStop && it !is Ping }.transform { emit(it.toOpenAIChatCompletionChunk(request.model.value)) } } override suspend fun completions(request: CompletionRequest): Completion { throw UnsupportedOperationException("Not supported") } } fun OpenAIProvider.Companion.anthropic( id: String = "anthropic", config: AnthropicOpenAIProviderConfig, models: List<OpenAIModel> = AnthropicModel.availableModels.map { OpenAIModel(it.value) }, client: Anthropic = Anthropic.create( AnthropicConfig( apiKey = config.apiKey, baseUrl = config.baseUrl, anthropicVersion = config.anthropicVersion ) ) ): OpenAIProvider { return AnthropicOpenAIProvider( id = id, config = config, models = models, client = client ) }
0
Kotlin
0
9
eeef583fb15610e60fbb4df3550f085f4c6f3908
3,770
openai-kotlin
Apache License 2.0
src/main/java/team/_0mods/ecr/common/init/ECManager.kt
0mods
830,371,936
false
{"Kotlin": 209449, "Java": 14183}
@file:JvmName("ECManager") package team._0mods.ecr.common.init import net.minecraftforge.common.MinecraftForge import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext import team._0mods.ecr.api.multiblock.IMultiblock import team._0mods.ecr.api.utils.ecRL import team._0mods.ecr.common.init.registry.ECAnnotationProcessor @JvmName("init") fun initCommon() { val modBus = FMLJavaModLoadingContext.get().modEventBus val forgeBus = MinecraftForge.EVENT_BUS IMultiblock.createMultiBlock("nil".ecRL, arrayOf(arrayOf()), false) ECAnnotationProcessor.init() }
0
Kotlin
0
0
f4d8d199b620d162e44a922e80b0ff4bc118b21f
583
ECR
MIT License
app/src/main/java/com/progix/fridgex/light/fragment/productselection/ProductsFragment.kt
T8RIN
417,568,516
false
{"Kotlin": 454504, "Java": 146}
package com.progix.fridgex.light.fragment.productselection import android.database.Cursor import android.os.Bundle import android.util.Pair import android.view.Menu import android.view.MenuInflater import android.view.View import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import com.google.android.material.transition.MaterialFadeThrough import com.jakewharton.rxbinding4.appcompat.queryTextChangeEvents import com.progix.fridgex.light.R import com.progix.fridgex.light.activity.MainActivity.Companion.mDb import com.progix.fridgex.light.adapter.productselection.ProductsAdapter import com.progix.fridgex.light.application.FridgeXLightApplication.Companion.allProducts import com.progix.fridgex.light.functions.Functions.delayedAction import com.progix.fridgex.light.functions.Functions.searchString import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import kotlinx.coroutines.* import java.util.concurrent.TimeUnit class ProductsFragment : Fragment(R.layout.fragment_products) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) enterTransition = MaterialFadeThrough().apply { duration = resources.getInteger(R.integer.anim_duration).toLong() } exitTransition = MaterialFadeThrough().apply { duration = resources.getInteger(R.integer.anim_duration).toLong() } } lateinit var recycler: RecyclerView private var prodList: ArrayList<String> = ArrayList() private var prodCategory: Int = 0 private var job: Job? = null override fun onViewCreated(v: View, savedInstanceState: Bundle?) { super.onViewCreated(v, savedInstanceState) prodCategory = requireArguments().getInt("prodCat") recycler = v.findViewById(R.id.productsRecycler) val name = arguments?.getString("category") delayedAction(10) { requireActivity().findViewById<Toolbar>(R.id.toolbar).title = name } job?.cancel() job = CoroutineScope(Dispatchers.Main).launch { prodList = coroutine() productsAdapter = ProductsAdapter(requireContext(), prodList, prodCategory) recycler.adapter = productsAdapter } } private suspend fun coroutine(): ArrayList<String> = withContext(Dispatchers.IO) { val name = arguments?.getString("category") val array = ArrayList<String>() val cursor: Cursor = mDb.rawQuery("SELECT * FROM products WHERE category = ?", listOf(name).toTypedArray()) cursor.moveToFirst() while (!cursor.isAfterLast) { array.add(cursor.getString(2)) cursor.moveToNext() } array.sortBy { it } cursor.close() return@withContext array } private var productsAdapter: ProductsAdapter? = null private fun search(s: String?, int: Int?) { if (s!!.isNotEmpty()) { val pairArrayList = ArrayList<Pair<Int, String>>() val list = ArrayList<String>() for (item in allProducts!!) { val temp: Int = searchString(s.lowercase(), item) if (temp != 101) { pairArrayList.add(Pair(temp, item)) } } pairArrayList.sortBy { it.first } for (item in pairArrayList) { list.add(item.second) } recycler.adapter = ProductsAdapter(requireContext(), list, int!!) } else { if (recycler.adapter != productsAdapter) { recycler.adapter = ProductsAdapter(requireContext(), prodList, prodCategory) } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.folder_menu, menu) val myActionMenuItem = menu.findItem(R.id.search_search) val searchView = myActionMenuItem.actionView as SearchView searchView.queryTextChangeEvents() .debounce(350, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { search(it.queryText.toString(), arguments?.getInt("prodCat")) } super.onCreateOptionsMenu(menu, inflater) } }
0
Kotlin
4
30
dd77e17dc0737e1f0a1a2668a9381838ba627fdf
4,436
FridgeXLight
Apache License 2.0
app/src/main/kotlin/com/luishenrique/cutecatsgallery/base/ErrorContent.kt
Louiixx-h
434,039,207
false
{"Kotlin": 19860}
package com.luishenrique.cutecatsgallery.base data class ErrorContent( val message: String, val throwable: Throwable )
0
Kotlin
0
5
175f0a8cbbae9ed2c8707525236b0b9c4ae57372
127
cute-cats-gallery-app
Freetype Project License
api/src/main/kotlin/dev/schlaubi/mikbot/plugin/api/util/ListPaginator.kt
DRSchlaubi
409,332,765
false
{"Kotlin": 343748, "Java": 5154, "Dockerfile": 201, "Shell": 197, "PowerShell": 96}
package dev.schlaubi.musicbot.utils import com.kotlindiscord.kord.extensions.pagination.builders.PaginatorBuilder import dev.kord.core.behavior.UserBehavior import dev.kord.rest.builder.message.EmbedBuilder import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlin.math.ceil /** * Configures this [PaginatorBuilder] to create one page for each [x][chunkSize] elements in [items] * . * * @param user the [PaginatorBuilder.owner] of this paginator * @param items a [List] containing all the items * @param mapper a mapper converting [T] to [String] * @param title a function providing the title for the current page * @param enumerate whether to include element numbers in entries or not * @param additionalConfig additional [PaginatorBuilder] config * @param additionalPageConfig additional [EmbedBuilder] config, applied to each page */ suspend fun <T> PaginatorBuilder.forList( user: UserBehavior, items: List<T>, mapper: suspend (T) -> String, title: suspend (current: Int, total: Int) -> String, chunkSize: Int = 8, enumerate: Boolean = true, additionalConfig: suspend PaginatorBuilder.() -> Unit = {}, additionalPageConfig: suspend EmbedBuilder.() -> Unit = {}, ) = forList(user, items.size, { offset, end -> items.subList(offset, end) }, mapper, title, chunkSize, enumerate, additionalConfig, additionalPageConfig) /** * Configures this [PaginatorBuilder] to create one page for each [x][chunkSize] elements in [items] * . * * @param user the [PaginatorBuilder.owner] of this paginator * @param total the total amount of items * @param items a [Flow] containing all the items * @param mapper a mapper converting [T] to [String] * @param title a function providing the title for the current page * @param enumerate whether to include element numbers in entries or not * @param additionalConfig additional [PaginatorBuilder] config * @param additionalPageConfig additional [EmbedBuilder] config, applied to each page */ suspend fun <T> PaginatorBuilder.forFlow( user: UserBehavior, total: Long, items: Flow<T>, mapper: suspend (T) -> String, title: suspend (current: Int, total: Int) -> String, chunkSize: Int = 8, enumerate: Boolean = true, additionalConfig: suspend PaginatorBuilder.() -> Unit = {}, additionalPageConfig: suspend EmbedBuilder.() -> Unit = {}, ) = forList(user, total.toInt(), { offset, _ -> items.drop(offset).take(chunkSize).toList() }, mapper, title, chunkSize, enumerate, additionalConfig, additionalPageConfig) private suspend fun <T> PaginatorBuilder.forList( user: UserBehavior, size: Int, subList: suspend (offset: Int, limit: Int) -> List<T>, mapper: suspend (T) -> String, title: suspend (current: Int, end: Int) -> String, chunkSize: Int = 8, enumerate: Boolean = true, additionalConfig: suspend PaginatorBuilder.() -> Unit = {}, additionalPageConfig: suspend EmbedBuilder.() -> Unit = {}, ) { owner = user var currentIndexOffset = 0 repeat(ceil(size / chunkSize.toDouble()).toInt()) { val items = subList(currentIndexOffset, currentIndexOffset + chunkSize) addPage(currentIndexOffset, title, items, enumerate, mapper, additionalPageConfig) currentIndexOffset += size } additionalConfig() } private fun <T> PaginatorBuilder.addPage( myOffset: Int, title: suspend (current: Int, end: Int) -> String, items: List<T>, enumerate: Boolean, mapper: suspend (T) -> String, additionalPageConfig: suspend EmbedBuilder.() -> Unit ) { page { this.title = title((myOffset + 1), pages.size) description = items.mapIndexed { index, it -> if (enumerate) { "${index + myOffset + 1}: ${mapper(it)}" } else { mapper(it) } } .joinToString("\n") additionalPageConfig() } }
16
Kotlin
12
36
557b2ca39b7753c35278985815cbe82396fa9f66
4,061
mikbot
MIT License
sample/shared/shared/src/commonMain/kotlin/com/arkivanov/sample/shared/tabs/TabsComponent.kt
arkivanov
437,015,897
false
{"Kotlin": 700677}
package com.arkivanov.sample.shared.tabs import com.arkivanov.decompose.router.stack.ChildStack import com.arkivanov.decompose.value.Value import com.arkivanov.sample.shared.cards.CardsComponent import com.arkivanov.sample.shared.counters.CountersComponent import com.arkivanov.sample.shared.menu.MenuComponent import com.arkivanov.sample.shared.multipane.MultiPaneComponent interface TabsComponent { val stack: Value<ChildStack<*, Child>> fun onMenuTabClicked() fun onCountersTabClicked() fun onCardsTabClicked() fun onMultiPaneTabClicked() sealed class Child { class MenuChild(val component: MenuComponent) : Child() class CountersChild(val component: CountersComponent) : Child() class CardsChild(val component: CardsComponent) : Child() class MultiPaneChild(val component: MultiPaneComponent) : Child() } }
2
Kotlin
84
2,207
8af551e8895951a5082a5d2750335713d673f80b
876
Decompose
Apache License 2.0
common/features/base/src/commonMain/kotlin/ru/tetraquark/ton/explorer/features/base/TextEntryFieldValue.kt
Tetraquark
608,328,051
false
null
package ru.tetraquark.ton.explorer.features.base import com.arkivanov.decompose.value.Value import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import ru.tetraquark.ton.explorer.features.base.decompose.asValue import ru.tetraquark.ton.explorer.lib.entryfield.TextEntryField import ru.tetraquark.ton.explorer.lib.entryfield.ValidationRule class TextEntryFieldValue<E : Any>( coroutineScope: CoroutineScope, initialValue: String, autoValidation: Boolean = false, isEnabled: Boolean = true, validation: ValidationRule<String, E>? = null ) : TextEntryField<E>(initialValue, autoValidation, isEnabled, validation) { val valueValue: Value<String> = valueState.asValue(coroutineScope) val failureValue: Value<OptionalValue<out E>> = errorState.map(::OptionalValue) .stateIn(coroutineScope, SharingStarted.Lazily, OptionalValue(null)).asValue(coroutineScope) val isEnabledValue: Value<Boolean> = super.isEnabled.asValue(coroutineScope) }
0
Kotlin
0
3
7cb84104b8631f0d29cbec82754351bd43a40ed1
1,081
TONSkanner
MIT License
app/src/main/java/com/app/android/ui/main/MainViewModel.kt
akaj-team
119,332,818
false
null
package com.app.android.ui.main import android.support.v7.util.DiffUtil import com.app.android.data.model.Task import com.app.android.data.source.TaskRepository import com.app.android.ui.base.Diff import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject /** * * @author at-vinhhuynh */ class MainViewModel(private val taskRepository: TaskRepository) { internal var progressBarStatus = BehaviorSubject.create<Boolean>() internal val updateListTask = PublishSubject.create<DiffUtil.DiffResult>() internal var tasks = mutableListOf<Task>() internal fun getTasks() = taskRepository.getListTask() .doOnSubscribe { progressBarStatus.onNext(true) } .doFinally { progressBarStatus.onNext(false) } .onErrorReturn { listOf() } .observeOn(Schedulers.computation()) .map { val diff = Diff(tasks, it) .areItemsTheSame { oldItem, newItem -> oldItem.id == newItem.id } .areContentsTheSame { oldItem, newItem -> oldItem.title == newItem.title oldItem.description == newItem.description oldItem.isDone == newItem.isDone oldItem.createTime == newItem.createTime oldItem.updateTime == newItem.updateTime } .calculateDiff() tasks.clear() tasks.addAll(it) updateListTask.onNext(diff) } }
1
Kotlin
0
0
1025483f4c64dc03e2c12d4051e95b2d1083d8f6
1,772
AndroidBaseProject
Apache License 2.0
cinescout/sync/automated/src/main/kotlin/cinescout/sync/automated/model/SyncResult.kt
fardavide
280,630,732
false
null
package cinescout.sync.automated.model import arrow.core.Either import cinescout.error.NetworkError import cinescout.sync.domain.model.FetchScreenplaysResult internal sealed interface SyncResult<out T : Any> { @JvmInline value class Error(val networkError: NetworkError) : SyncResult<Nothing> object Skipped : SyncResult<Nothing> @JvmInline value class Success<out T : Any>(val value: T) : SyncResult<T> } @JvmName("toSyncResult_Unit") internal fun Either<NetworkError, Unit>.toSyncResult(): SyncResult<Unit> = fold(ifLeft = { SyncResult.Error(it) }, ifRight = { SyncResult.Success(Unit) }) @JvmName("toSyncResult_FetchScreenplaysResult") internal fun Either<NetworkError, FetchScreenplaysResult>.toSyncResult(): SyncResult<Int> = fold( ifLeft = { SyncResult.Error(it) }, ifRight = { result -> when (result.fetchedCount) { 0 -> SyncResult.Skipped else -> SyncResult.Success(result.fetchedCount) } } )
8
Kotlin
2
6
dcbd0a0b70d6203a2ba1959b797038564d0f04c4
984
CineScout
Apache License 2.0
app/src/main/java/top/topsea/streamplayer/data/AppDatabase.kt
TopSea
789,758,299
false
{"Kotlin": 64199}
package top.topsea.streamplayer.data import androidx.room.Database import androidx.room.RoomDatabase import top.topsea.streamplayer.data.table.ChatInfo import top.topsea.streamplayer.data.table.ChatInfoDao @Database(entities = [ChatInfo::class], version = 1,) abstract class AppDatabase: RoomDatabase() { abstract fun chatInfoDao(): ChatInfoDao }
0
Kotlin
0
0
18af2b8ab03c30892ee2b99d0a0b253961b694fb
352
StreamPlayer
MIT License
crossdevice/src/main/kotlin/com/google/ambient/crossdevice/sessions/OriginatingSession.kt
google
519,372,420
false
{"Kotlin": 184777}
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ambient.crossdevice.sessions import android.os.Build import androidx.annotation.RequiresApi import com.google.common.util.concurrent.ListenableFuture /** * Describes a Session that is in the process of being transferred to another device. The * originating side of the Session transfer will use this class to initialize the application. */ @RequiresApi(Build.VERSION_CODES.O) interface OriginatingSession : TransferrableSession { /** * Gets communication channel to send initialization messages back and forth between the * originating and receiving device. * * @return The [SessionRemoteConnection] relevant to the transfer. * * @throws SessionException if this session has already completed. This method will also throw an * exception if it is called prior to the Session being ready for initialization. Applications * will notify that they are ready for initialization in * [OriginatingSessionStateCallback.onConnected]. * * @throws SessionException if this session has already completed. */ @Throws(SessionException::class) override fun getStartupRemoteConnection(): SessionRemoteConnection } @RequiresApi(Build.VERSION_CODES.O) internal class OriginatingSessionImpl(session: TransferrableSessionInterface, handleId: String) : OriginatingSession { override val sessionId = session.sessionId private val transferrableSession = TransferrableSessionImpl(session, handleId) override fun getStartupRemoteConnection(): SessionRemoteConnection = transferrableSession.getStartupRemoteConnection() override suspend fun cancelTransfer() = transferrableSession.cancelTransfer() override fun cancelTransferFuture(): ListenableFuture<Unit> = transferrableSession.cancelTransferFuture() }
0
Kotlin
8
81
e0e42d82cf73034a1fdde924e60088e95b47062a
2,365
cross-device-sdk
Apache License 2.0
transmission/src/main/java/com/trendyol/transmission/transformer/dataholder/TransmissionDataHolder.kt
Trendyol
771,942,025
false
{"Kotlin": 70838}
package com.trendyol.transmission.transformer.dataholder import com.trendyol.transmission.Transmission import com.trendyol.transmission.transformer.Transformer import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch interface TransmissionDataHolder<T : Transmission.Data?> { fun getValue(): T fun update(updater: (T) -> @UnsafeVariance T) } internal class TransmissionDataHolderImpl<T : Transmission.Data?>( initialValue: T, publishUpdates: Boolean, transformer: Transformer, typeName: String, ) : TransmissionDataHolder<T> { private val holder = MutableStateFlow(initialValue) override fun getValue(): T { return holder.value } init { transformer.run { storage.updateHolderDataReferenceToTrack(typeName) transformerScope.launch { holder.collect { it?.let { holderData -> storage.updateHolderData(holderData) if (publishUpdates) { transformer.dataChannel.trySend(it) } } } } } } override fun update(updater: (T) -> @UnsafeVariance T) { holder.update(updater) } }
0
Kotlin
0
18
cd12235d6acd3f3ece2c479db52db2f5c0568c51
1,326
transmission
MIT License
domain/src/main/java/com/semicolon/domain/entity/challenge/ChallengeDetailEntity.kt
Walkhub
443,006,389
false
null
package com.semicolon.domain.entity.challenge import com.semicolon.domain.enum.ChallengeGoalType import com.semicolon.domain.enum.ChallengeGoalScope import com.semicolon.domain.enum.ChallengeUserScope import org.threeten.bp.LocalDateTime data class ChallengeDetailEntity( val name: String, val content: String, val goal: Int, val goalType: ChallengeGoalType, val goalScope: ChallengeGoalScope, val userScope: ChallengeUserScope, val award: String, val imageUrl: String, val startAt: LocalDateTime, val endAt: LocalDateTime, val isMine: Boolean, val participantCount: Int, val writerEntity: WriterEntity ) { data class WriterEntity( val id: Int, val name: String, val profileImageUrl: String ) }
30
Kotlin
1
15
c2d85ebb9ae8b200be22e9029dcfdcbfed19e473
780
walkhub_android
MIT License
src/main/kotlin/aws/TablesProvider.kt
JHegarty14
766,650,006
false
{"Kotlin": 74877}
package aws interface TablesProvider { fun getConsumableTables(): List<String>; }
0
Kotlin
0
0
b13a7b4820ac7edf2fabe5c4cbe624d09bb5b058
86
dynamodb-kafka-konnect
MIT License
src/main/kotlin/io/uvera/template/util/extensions/CommonExtensions.kt
uvera
386,930,596
false
null
package io.uvera.template.util.extensions import io.uvera.template.error.dto.ObjectErrorCompact import org.springframework.http.ResponseEntity import org.springframework.validation.ObjectError /* * BindingResult's ObjectError in a compact form */ val List<ObjectError>.compact: List<ObjectErrorCompact> get() = this.map { ObjectErrorCompact(it.defaultMessage ?: "Unknown error", it.code ?: "UnknownException") } /* * Create response entity with empty json response */ object EmptyObject fun ResponseEntity.BodyBuilder.empty(): ResponseEntity<Any> { return this.body(EmptyObject) }
0
Kotlin
0
0
2aee40e3465556994e5cb6f02f5f1daaf530961e
608
spring-boot-kotlin-template
MIT License
day5/src/test/kotlin/day5/ThermalMapKtTest.kt
snv
434,384,799
false
{"Kotlin": 99328}
@file:Suppress("ClassName") package day5 import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test internal class ThermalMapKtTest { enum class ExpandedSampleVents(val coordinates: List<Coordinate>){ LONG_HORIZONTAL(listOf( 0 to 9, 1 to 9, 2 to 9, 3 to 9, 4 to 9, 5 to 9 )), SHORT_HORIZONTAL(listOf( 0 to 9, 1 to 9, 2 to 9 )), VERTICAL(listOf( 7 to 0, 7 to 1, 7 to 2, 7 to 3, 7 to 4 )), DIAGONAL_A(listOf( 1 to 1, 2 to 2, 3 to 3 )), DIAGONAL_B(listOf( 9 to 7, 8 to 8, 7 to 9 )) } enum class SampleVents(val vents: Vents){ LONG_HORIZONTAL((0 to 9) to (5 to 9)), SHORT_HORIZONTAL((0 to 9) to (2 to 9)), VERTICAL((7 to 0) to (7 to 4)), DIAGONAL_A((1 to 1) to (3 to 3)), DIAGONAL_B((9 to 7) to (7 to 9)), } val sampleInput = listOf( ((0 to 9) to (5 to 9)), ((8 to 0) to (0 to 8)), ((9 to 4) to (3 to 4)), ((2 to 2) to (2 to 1)), ((7 to 0) to (7 to 4)), ((6 to 4) to (2 to 0)), ((0 to 9) to (2 to 9)), ((3 to 4) to (1 to 4)), ((0 to 0) to (8 to 8)), ((5 to 5) to (8 to 2)) ) @Test fun `add coordinates to heatmap`() { val heatmap : HeatMap = mutableMapOf() ExpandedSampleVents.SHORT_HORIZONTAL.coordinates .forEach { heatmap += it } println(heatmap.draw()) ExpandedSampleVents.LONG_HORIZONTAL.coordinates .forEach { heatmap += it } println(heatmap.draw()) ExpandedSampleVents.VERTICAL.coordinates .forEach { heatmap += it } println(heatmap.draw()) assertNull(heatmap[9 to 9]) assertEquals(2, heatmap[0 to 9]) assertEquals(2, heatmap[2 to 9]) assertEquals(1, heatmap[3 to 9]) assertEquals(1, heatmap[7 to 2]) assertEquals(1, heatmap[7 to 4]) } @Nested inner class `expand vents` { @Test fun horzontaly() { //act val expandedVents = SampleVents.LONG_HORIZONTAL.vents.expand() //assert assertEquals( ExpandedSampleVents.LONG_HORIZONTAL.coordinates, expandedVents ) } @Test fun vertically() { //arrange val sampleVents : Vents = SampleVents.VERTICAL.vents //act val expandedVents = sampleVents.expand() //assert assertEquals( ExpandedSampleVents.VERTICAL.coordinates, expandedVents ) } } @Test fun `add lines of vents to heatmap`() { val heatmap :HeatMap = mutableMapOf() heatmap += SampleVents.LONG_HORIZONTAL.vents heatmap += SampleVents.SHORT_HORIZONTAL.vents heatmap += SampleVents.VERTICAL.vents //println(heatmap.draw()) assertNull(heatmap[9 to 9]) assertEquals(2, heatmap[0 to 9]) assertEquals(2, heatmap[2 to 9]) assertEquals(1, heatmap[3 to 9]) assertEquals(1, heatmap[7 to 2]) assertEquals(1, heatmap[7 to 4]) } @Test fun `adding diagonal lines`(){ val heatMap :HeatMap = mutableMapOf() heatMap += SampleVents.DIAGONAL_A.vents heatMap += SampleVents.DIAGONAL_B.vents assertTrue { ExpandedSampleVents.DIAGONAL_A.coordinates .all { heatMap.containsKey(it) } and ExpandedSampleVents.DIAGONAL_B.coordinates .all { heatMap.containsKey(it) } } } @Test fun drawHeatMap() { val filtered = sampleInput .also(::println) println(buildHeatMap(filtered).draw()) } @Test fun findHotspots(){ val filtered = sampleInput .filter { (start, end) -> start.first == end.first || start.second == end.second } val hotspots = buildHeatMap(filtered).findHotspots(2) assertEquals(5, hotspots.size) } @Test fun findHotspotsWithDiagonals(){ val filtered = sampleInput val hotspots = buildHeatMap(filtered).findHotspots(2) assertEquals(12, hotspots.size) } }
0
Kotlin
0
0
0a2d94f278defa13b52f37a938a156666314cd13
4,531
adventOfCode21
The Unlicense
main/java/com/example/login_page/entity/Reservation.kt
Wail-Sr
547,840,618
false
{"Kotlin": 72508}
package com.example.login_page.entity import java.io.Serializable data class Reservation( val id_reservation:Int, val id_parking:Int, val id_user:Int, val parkingname:String, val day:String, val open_time:String, val close_time:String, ) : Serializable
0
Kotlin
0
0
3b624307a86536586cdd06a9804ce0e3bb84801a
287
GARRU
MIT License
frontend/src/main/kotlin/component/bootstrap/NavbarBrand.kt
kravent
260,526,771
false
null
package component.bootstrap import react.RClass import styled.styled interface NavbarBrandProps : BootstrapRProps { var `as`: Any var href: Boolean } @Suppress("UnsafeCastFromDynamic") val NavbarBrand: RClass<NavbarBrandProps> = Navbar.asDynamic().Brand val StyledNavbarBrand = styled(NavbarBrand)
0
Kotlin
0
0
e84727363b968e5776ff25698e534d9a9b36f937
309
ramona
MIT License
app/src/main/java/ir/dunijet/wikipedia_m3/activity/MainActivity.kt
Ali-PRGW
791,695,890
false
{"Kotlin": 66312}
package ir.dunijet.wikipedia_m3.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.ViewGroup import android.widget.ImageView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatDelegate import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.GravityCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updateLayoutParams import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import ir.dunijet.wikipedia_m3.R import ir.dunijet.wikipedia_m3.databinding.ActivityMainBinding import ir.dunijet.wikipedia_m3.ext.Constant import ir.dunijet.wikipedia_m3.ext.Keys import ir.dunijet.wikipedia_m3.ext.readPref import ir.dunijet.wikipedia_m3.ext.setNavigationColor import ir.dunijet.wikipedia_m3.ext.showDialog import ir.dunijet.wikipedia_m3.ext.showSnackbar import ir.dunijet.wikipedia_m3.ext.writePref import ir.dunijet.wikipedia_m3.fragments.FragmentExplore import ir.dunijet.wikipedia_m3.fragments.FragmentProfile import ir.dunijet.wikipedia_m3.fragments.FragmentTrend import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var changeThemeButton: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initialize() changeThemeButton.setOnClickListener { toggleTheme() } binding.navigationViewMain.setNavigationItemSelectedListener { when (it.itemId) { // R.id.temenu_writer -> { // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // val dialog = SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE) // dialog.titleText = "Alert!" // dialog.confirmText = "Confirm" // dialog.cancelText = "Cancel" // dialog.contentText = "Wanna be a Writer?" // dialog.setCancelClickListener { // dialog.dismiss() // } // dialog.setConfirmClickListener { // dialog.dismiss() // Toast.makeText(this, "you can be a writer just work :)", Toast.LENGTH_SHORT) // .show() // } // dialog.show() // // } // // R.id.menu_photograph -> { // // // load fragment => // val transaction = supportFragmentManager.beginTransaction() // transaction.add(R.id.frame_main_container, FragmentPhotographer()) // transaction.addToBackStack(null) // transaction.commit() // // // check menu item => // binding.navigationViewMain.menu.getItem(1).isChecked = true // // // close drawer => // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // } // // R.id.menu_vieo_maker -> { // binding.drawerLayoutMain.closeDrawer(GravityCompat.START) // // Snackbar // .make(binding.root, "No Internet!", Snackbar.LENGTH_LONG) // .setAction("Retry") { // Toast.makeText(this, "checking network", Toast.LENGTH_SHORT).show() // } //// .setActionTextColor(ContextCompat.getColor(this, R.color.white)) //// .setBackgroundTint(ContextCompat.getColor(this, R.color.blue)) // .show() // // } R.id.menu_writer -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) val intent = Intent(this, MainActivity3::class.java) startActivity(intent) } // --------------------------------- R.id.menu_open_wikipedia -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) openWebsite("https://www.wikipedia.org/") } R.id.openWikimedia -> { binding.drawerLayoutMain.closeDrawer(GravityCompat.START) openWebsite("https://www.wikimedia.org/") } } true } binding.toolbarMain.setOnMenuItemClickListener { when (it.itemId) { R.id.menu_info -> { showDialog( "About us", "Wikipedia is a free, web-based, collaborative, multilingual encyclopedia project launched in 2001 supported by the non-profit Wikimedia Foundation. \n\nIt is one of the largest and most popular general reference works on the internet. Wikipedia's articles are written collaboratively by volunteers around the world, and almost all of its articles can be edited by anyone with internet access." ) } R.id.menu_writer -> { openWebsite("https://en.wikipedia.org/wiki/Wikipedia:How_to_create_a_page") } } true } binding.bottomNavigationMain.setOnItemSelectedListener { when (it.itemId) { R.id.menu_explore -> { replaceFragment(FragmentExplore()) } R.id.menu_trend -> { replaceFragment(FragmentTrend()) } R.id.menu_profile -> { replaceFragment(FragmentProfile()) } } true } binding.bottomNavigationMain.setOnItemReselectedListener {} } private fun openWebsite(url: String) { val intent = Intent(this, WebViewActivity::class.java) val bundle = Bundle() bundle.putString("title", "be a writer") bundle.putString("url", url) intent.putExtra("url_data", bundle) startActivity(intent) } private fun replaceFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.frame_main_container, fragment) transaction.commit() } fun initTheme() { val theme = runBlocking { readPref(Keys.appTheme) } if (theme == null) { runBlocking { writePref(Keys.appTheme, Constant.light) } AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } else { if (theme == Constant.light) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } } } private fun initialize() { enableEdgeToEdge() ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, windowInsets -> val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) v.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = insets.top bottomMargin = insets.bottom } WindowInsetsCompat.CONSUMED } setNavigationColor() val actionBarDrawerToggle = ActionBarDrawerToggle( this, binding.drawerLayoutMain, binding.toolbarMain, R.string.openDrawer, R.string.closeDrawer ) binding.drawerLayoutMain.addDrawerListener(actionBarDrawerToggle) actionBarDrawerToggle.syncState() replaceFragment(FragmentExplore()) binding.bottomNavigationMain.selectedItemId = R.id.menu_explore changeThemeButton = binding.navigationViewMain.getHeaderView(0).findViewById(R.id.btnChangeTheme) } private fun toggleTheme() { lifecycleScope.launch { val currentTheme = readPref(Keys.appTheme) if (currentTheme == Constant.light) { writePref(Keys.appTheme, Constant.dark) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { writePref(Keys.appTheme, Constant.light) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } } }
0
Kotlin
0
0
78786243765f3c1f2b1fb49b7c980c8cafca60f2
8,886
WikiPedia_Material3
MIT License
app/src/testShared/java/ru/olegivo/afs/RxHelperImpl.kt
olegivo
189,586,349
false
null
/* * Copyright (C) 2020 <NAME> <<EMAIL>> * * This file is part of AFS. * * AFS is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * AFS 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 * AFS. */ package ru.olegivo.afs import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.Single import io.reactivex.observers.BaseTestConsumer import io.reactivex.schedulers.TestScheduler import ru.olegivo.afs.helpers.getSingleValue class RxHelperImpl(private val strategy: RxHelper.SchedulerSubstitutionStrategy) : RxHelper { override val rxSchedulerRule = RxSchedulerRule(strategy = strategy) override val testScheduler: TestScheduler get() = (strategy as RxHelper.SchedulerSubstitutionStrategy.TestSchedulerHolder).testScheduler override fun <T> Single<T>.assertResult(block: (T) -> Unit): Unit = test().andTriggerActions() .assertSuccess { getSingleValue().run(block) } override fun <T> Maybe<T>.assertResult(block: (T) -> Unit): Unit = test().andTriggerActions() .assertSuccess { getSingleValue().run(block) } override fun Completable.assertSuccess(): Unit = test().andTriggerActions() .assertSuccess { } override fun triggerActions() { testScheduler.triggerActions() } private fun <T, U : BaseTestConsumer<T, U>> BaseTestConsumer<T, U>.assertSuccess(block: U.() -> Unit) = this.andTriggerActions() .assertNoErrors() .assertComplete() .run(block) private fun <T> T.andTriggerActions() = this.also { triggerActions() } }
15
Kotlin
0
0
c828167fc361ce32ddd2d4354f450dd052295de9
2,114
AFS
MIT License
src/main/kotlin/com/jeno/reactspringapp/security/RestAuthenticationEntryPoint.kt
JenoDK
399,538,764
false
null
package com.jeno.reactspringapp.security import org.slf4j.LoggerFactory import org.springframework.security.core.AuthenticationException import org.springframework.security.web.AuthenticationEntryPoint import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class RestAuthenticationEntryPoint : AuthenticationEntryPoint { companion object { val LOG = LoggerFactory.getLogger(RestAuthenticationEntryPoint::class.java)!! } override fun commence(request: HttpServletRequest?, response: HttpServletResponse?, e: AuthenticationException?) { LOG.error("Responding with unauthorized error.", e) response!!.sendError(HttpServletResponse.SC_UNAUTHORIZED, e!!.localizedMessage) } }
0
Kotlin
0
1
45c8515d8ac9a28b97c186c5c488604240ba588a
720
react-spring-app
Apache License 2.0
app/src/main/java/cz/cuni/mff/ufal/translator/base/BaseScreen.kt
ufal
479,050,528
false
null
package cz.cuni.mff.ufal.translator.base import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.google.accompanist.insets.ProvideWindowInsets import cz.cuni.mff.ufal.translator.interactors.crashlytics.FirebaseHelper.setFirebaseScreen import cz.cuni.mff.ufal.translator.interactors.crashlytics.Screen import cz.cuni.mff.ufal.translator.interactors.preferences.data.DarkModeSetting import cz.cuni.mff.ufal.translator.ui.theme.LindatTheme import kotlinx.coroutines.flow.StateFlow /** * @author <NAME> */ @Composable fun BaseScreen( screen: Screen, darkModeSetting: StateFlow<DarkModeSetting>, viewModel: IBaseViewModel? = null, content: @Composable () -> Unit ) { if (!LocalInspectionMode.current) { setFirebaseScreen(screen) } val lifecycleOwner = LocalLifecycleOwner.current DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_START) { viewModel?.onStart() } else if (event == Lifecycle.Event.ON_STOP) { viewModel?.onStop() } } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } val state by darkModeSetting.collectAsState() LindatTheme(state) { ProvideWindowInsets { Surface( modifier = Modifier.fillMaxSize(), content = content, ) } } }
7
Kotlin
0
2
e2fb775116e49e441ab0767f1d860088b753707f
1,986
charles-translator-android
MIT License
kaff4-core/src/main/kotlin/net/navatwo/kaff4/streams/image_stream/Aff4BevySink.kt
kaff4
555,850,412
false
{"Kotlin": 419315, "Shell": 649}
package net.navatwo.kaff4.streams.image_stream import net.navatwo.kaff4.io.source import net.navatwo.kaff4.model.rdf.ImageStream import net.navatwo.kaff4.streams.computeLinearHashes import okio.Buffer import okio.FileSystem import okio.Sink import okio.Timeout import okio.buffer import java.nio.ByteBuffer import javax.inject.Inject import javax.inject.Named internal class Aff4BevySink @Inject constructor( @Named("ImageOutput") private val outputFileSystem: FileSystem, private val timeout: Timeout, imageStream: ImageStream, val bevy: Bevy, ) : Sink { private val bevyMaxSize = imageStream.bevyMaxSize private val compressionMethod = imageStream.compressionMethod private var dataPosition = 0L private val dataSink = outputFileSystem.sink(bevy.dataSegment).buffer() private val indexSink = outputFileSystem.sink(bevy.indexSegment).buffer() private val hashSinks = bevy.blockHashes.mapValues { (_, path) -> outputFileSystem.sink(path).buffer() } private val uncompressedChunkBuffer = ByteBuffer.allocateDirect(imageStream.chunkSize) private val compressedChunkBuffer = ByteBuffer.allocateDirect(imageStream.chunkSize) private var bytesWritten = 0L @Volatile private var closed = false override fun write(source: Buffer, byteCount: Long) { check(!closed) { "closed" } require(bytesWritten + byteCount <= bevyMaxSize) { "Can not overflow bevy bytes: $bytesWritten + $byteCount <= $bevyMaxSize" } var bytesRemaining = byteCount while (bytesRemaining > 0L) { timeout.throwIfReached() if (uncompressedChunkBuffer.hasRemaining()) { val bytesFromSource = readRemainingBytesByChunkFromSource(source, bytesRemaining) if (bytesFromSource == -1) break bytesRemaining -= bytesFromSource } if (!uncompressedChunkBuffer.hasRemaining()) { // time to flush! writeBuffersToSinks() } } bytesWritten += byteCount - bytesRemaining } override fun flush() { check(!closed) { "closed" } writeBuffersToSinks() for (sink in sinks()) { sink.flush() } } override fun timeout(): Timeout = timeout override fun close() { if (closed) return synchronized(this) { if (closed) return closed = true } writeBuffersToSinks() for (sink in sinks()) { sink.close() } } private fun readRemainingBytesByChunkFromSource(source: Buffer, bytesRemaining: Long): Int { val initialLimit = uncompressedChunkBuffer.limit() try { val bytesToRead = bytesRemaining.toInt().coerceAtMost(uncompressedChunkBuffer.remaining()) val requiredLimit = uncompressedChunkBuffer.position() + bytesToRead uncompressedChunkBuffer.limit(requiredLimit.coerceAtMost(uncompressedChunkBuffer.capacity())) return source.read(uncompressedChunkBuffer) } finally { uncompressedChunkBuffer.limit(initialLimit) } } private fun writeBuffersToSinks() { if (uncompressedChunkBuffer.remaining() == uncompressedChunkBuffer.limit()) { // Nothing to write, don't bother trying to flush return } timeout.throwIfReached() uncompressedChunkBuffer.limit(uncompressedChunkBuffer.position()) uncompressedChunkBuffer.rewind() compressedChunkBuffer.rewind() compressedChunkBuffer.limit(compressedChunkBuffer.capacity()) val compressedSize = compressionMethod.compress(uncompressedChunkBuffer, compressedChunkBuffer) val bufferToWrite = if (compressedSize >= uncompressedChunkBuffer.limit()) { uncompressedChunkBuffer } else { compressedChunkBuffer } val dataLength = bufferToWrite.limit() indexSink.writeLongLe(dataPosition) indexSink.writeIntLe(dataLength) dataSink.write(bufferToWrite) dataPosition += dataLength bufferToWrite.rewind() val hashes = bufferToWrite.source(timeout).buffer().use { source -> source.computeLinearHashes(bevy.blockHashes.keys) } for ((hashType, hash) in hashes) { val sink = hashSinks.getValue(hashType) sink.write(hash) } uncompressedChunkBuffer.rewind() uncompressedChunkBuffer.limit(uncompressedChunkBuffer.capacity()) } private fun sinks(): Sequence<Sink> = sequence { yield(dataSink) yield(indexSink) yieldAll(hashSinks.values) } }
7
Kotlin
0
1
c88b43a429fbfb3ed735711118e966c42879ced0
4,329
kaff4
MIT License
kmath-core/src/commonMain/kotlin/space/kscience/kmath/expressions/ExpressionWithDefault.kt
SciProgCentre
129,486,382
false
null
/* * Copyright 2018-2023 KMath 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 space.kscience.kmath.expressions public class ExpressionWithDefault<T>( private val origin: Expression<T>, private val defaultArgs: Map<Symbol, T>, ) : Expression<T> { override fun invoke(arguments: Map<Symbol, T>): T = origin.invoke(defaultArgs + arguments) } public fun <T> Expression<T>.withDefaultArgs(defaultArgs: Map<Symbol, T>): ExpressionWithDefault<T> = ExpressionWithDefault(this, defaultArgs) public class DiffExpressionWithDefault<T>( private val origin: DifferentiableExpression<T>, private val defaultArgs: Map<Symbol, T>, ) : DifferentiableExpression<T> { override fun invoke(arguments: Map<Symbol, T>): T = origin.invoke(defaultArgs + arguments) override fun derivativeOrNull(symbols: List<Symbol>): Expression<T>? = origin.derivativeOrNull(symbols)?.withDefaultArgs(defaultArgs) } public fun <T> DifferentiableExpression<T>.withDefaultArgs(defaultArgs: Map<Symbol, T>): DiffExpressionWithDefault<T> = DiffExpressionWithDefault(this, defaultArgs)
91
null
52
600
83d9e1f0afb3024101a2f90a99b54f2a8b6e4212
1,188
kmath
Apache License 2.0
feature/employee/src/main/java/com/niyaj/feature/employee/add_edit/AddEditEmployeeScreen.kt
skniyajali
579,613,644
false
{"Kotlin": 2220123}
package com.niyaj.feature.employee.add_edit import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Divider import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ExposedDropdownMenuBox import androidx.compose.material.ExposedDropdownMenuDefaults import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.MergeType import androidx.compose.material.icons.filled.Accessibility import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.CalendarToday import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Money import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Person4 import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.Star import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.toSize import androidx.compose.ui.window.PopupProperties import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.niyaj.common.tags.EmployeeTestTags.ADD_EDIT_EMPLOYEE_BUTTON import com.niyaj.common.tags.EmployeeTestTags.CREATE_NEW_EMPLOYEE import com.niyaj.common.tags.EmployeeTestTags.EDIT_EMPLOYEE import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_JOINED_DATE_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_MONTHLY_SALARY_ERROR import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_MONTHLY_SALARY_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_NAME_ERROR import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_NAME_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_PHONE_ERROR import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_PHONE_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_POSITION_ERROR import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_POSITION_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_SALARY_TYPE_FIELD import com.niyaj.common.tags.EmployeeTestTags.EMPLOYEE_TYPE_FIELD import com.niyaj.common.utils.toMilliSecond import com.niyaj.common.utils.toSalaryDate import com.niyaj.designsystem.theme.IconSizeExtraLarge import com.niyaj.designsystem.theme.LightColor7 import com.niyaj.designsystem.theme.ProfilePictureSizeLarge import com.niyaj.designsystem.theme.SpaceMedium import com.niyaj.designsystem.theme.SpaceSmall import com.niyaj.model.EmployeeSalaryType import com.niyaj.model.EmployeeType import com.niyaj.ui.components.PhoneNoCountBox import com.niyaj.ui.components.StandardButtonFW import com.niyaj.ui.components.StandardOutlinedTextField import com.niyaj.ui.components.StandardScaffoldNew import com.niyaj.ui.event.UiEvent import com.niyaj.ui.util.Screens import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.result.ResultBackNavigator import com.vanpra.composematerialdialogs.MaterialDialog import com.vanpra.composematerialdialogs.datetime.date.datepicker import com.vanpra.composematerialdialogs.rememberMaterialDialogState import java.time.LocalDate /** * Add/Edit Employee Screen * @author Sk Niyaj Ali * @param employeeId * @param navController * @param viewModel * @param resultBackNavigator * @see AddEditEmployeeViewModel */ @OptIn(ExperimentalMaterialApi::class) @Destination(route = Screens.ADD_EDIT_EMPLOYEE_SCREEN) @Composable fun AddEditEmployeeScreen( employeeId: String = "", navController: NavController, viewModel: AddEditEmployeeViewModel = hiltViewModel(), resultBackNavigator: ResultBackNavigator<String> ) { val scaffoldState = rememberScaffoldState() val dialogState = rememberMaterialDialogState() val phoneError = viewModel.phoneError.collectAsStateWithLifecycle().value val nameError = viewModel.nameError.collectAsStateWithLifecycle().value val salaryError = viewModel.salaryError.collectAsStateWithLifecycle().value val positionError = viewModel.positionError.collectAsStateWithLifecycle().value val enableBtn = listOf(phoneError, nameError, salaryError, positionError).all { it == null } val event = viewModel.eventFlow.collectAsStateWithLifecycle(initialValue = null).value LaunchedEffect(key1 = event) { event?.let { data -> when (data) { is UiEvent.Error -> { resultBackNavigator.navigateBack(data.errorMessage) } is UiEvent.Success -> { resultBackNavigator.navigateBack(data.successMessage) } } } } val title = if (employeeId.isEmpty()) CREATE_NEW_EMPLOYEE else EDIT_EMPLOYEE var expanded by remember { mutableStateOf(false) } var salaryTypeToggled by remember { mutableStateOf(false) } var positionDropdownToggled by remember { mutableStateOf(false) } var textFieldSize by remember { mutableStateOf(Size.Zero) } StandardScaffoldNew( navController = navController, scaffoldState = scaffoldState, title = title, showBackButton = true, showBottomBar = true, selectionCount = 0, showFab = false, floatingActionButton = {}, navActions = {}, bottomBar = { StandardButtonFW( modifier = Modifier .fillMaxWidth() .padding(SpaceMedium) .testTag(ADD_EDIT_EMPLOYEE_BUTTON), enabled = enableBtn, text = title, icon = if (employeeId.isNotEmpty()) Icons.Default.Edit else Icons.Default.Add, onClick = { viewModel.onEvent(AddEditEmployeeEvent.CreateOrUpdateEmployee) }, ) } ) { paddingValues -> LazyColumn( modifier = Modifier .fillMaxWidth() .padding(paddingValues) .padding(SpaceMedium), verticalArrangement = Arrangement.spacedBy(SpaceSmall), horizontalAlignment = Alignment.CenterHorizontally, ) { item("Person icon") { Box( modifier = Modifier .size(ProfilePictureSizeLarge) .background(LightColor7, CircleShape), contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Default.Person, contentDescription = "Person icon", tint = MaterialTheme.colors.primary, modifier = Modifier .size(IconSizeExtraLarge) .align(Alignment.Center) ) } } item(EMPLOYEE_NAME_FIELD) { StandardOutlinedTextField( modifier = Modifier.testTag(EMPLOYEE_NAME_FIELD), text = viewModel.state.employeeName, label = "Employee Name", errorTag = EMPLOYEE_NAME_ERROR, leadingIcon = Icons.Default.Person4, error = nameError, onValueChange = { viewModel.onEvent(AddEditEmployeeEvent.EmployeeNameChanged(it)) }, ) } item(EMPLOYEE_PHONE_FIELD) { StandardOutlinedTextField( modifier = Modifier.testTag(EMPLOYEE_PHONE_FIELD), text = viewModel.state.employeePhone, label = "Employee Phone", leadingIcon = Icons.Default.PhoneAndroid, keyboardType = KeyboardType.Number, error = phoneError, errorTag = EMPLOYEE_PHONE_ERROR, onValueChange = { viewModel.onEvent(AddEditEmployeeEvent.EmployeePhoneChanged(it)) }, trailingIcon = { PhoneNoCountBox( count = viewModel.state.employeePhone.length ) }, ) } item(EMPLOYEE_MONTHLY_SALARY_FIELD) { StandardOutlinedTextField( modifier = Modifier.testTag(EMPLOYEE_MONTHLY_SALARY_FIELD), text = viewModel.state.employeeSalary, label = "Employee Monthly Salary", leadingIcon = Icons.Default.Money, keyboardType = KeyboardType.Number, error = salaryError, errorTag = EMPLOYEE_MONTHLY_SALARY_ERROR, onValueChange = { viewModel.onEvent(AddEditEmployeeEvent.EmployeeSalaryChanged(it)) }, ) } item(EMPLOYEE_SALARY_TYPE_FIELD) { ExposedDropdownMenuBox( expanded = salaryTypeToggled, onExpandedChange = { salaryTypeToggled = !salaryTypeToggled }, modifier = Modifier.testTag(EMPLOYEE_SALARY_TYPE_FIELD), ) { StandardOutlinedTextField( modifier = Modifier .fillMaxWidth() .onGloballyPositioned { coordinates -> //This value is used to assign to the DropDown the same width textFieldSize = coordinates.size.toSize() }, text = viewModel.state.employeeSalaryType.name, label = "Employee Salary Type", leadingIcon = Icons.AutoMirrored.Filled.MergeType, onValueChange = {}, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = salaryTypeToggled) }, ) DropdownMenu( expanded = salaryTypeToggled, onDismissRequest = { salaryTypeToggled = false }, modifier = Modifier .width(with(LocalDensity.current) { textFieldSize.width.toDp() }), ) { DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeeSalaryTypeChanged( EmployeeSalaryType.Monthly ) ) salaryTypeToggled = false } ) { Text( text = EmployeeSalaryType.Monthly.name, style = MaterialTheme.typography.body1, ) } Divider(modifier = Modifier.fillMaxWidth()) DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeeSalaryTypeChanged( EmployeeSalaryType.Daily ) ) salaryTypeToggled = false } ) { Text( text = EmployeeSalaryType.Daily.name, style = MaterialTheme.typography.body1, ) } Divider(modifier = Modifier.fillMaxWidth()) DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeeSalaryTypeChanged( EmployeeSalaryType.Weekly ) ) salaryTypeToggled = false } ) { Text( text = EmployeeSalaryType.Weekly.name, style = MaterialTheme.typography.body1, ) } } } } item(EMPLOYEE_TYPE_FIELD) { ExposedDropdownMenuBox( expanded = expanded, onExpandedChange = { expanded = !expanded }, modifier = Modifier.testTag(EMPLOYEE_TYPE_FIELD), ) { StandardOutlinedTextField( modifier = Modifier .fillMaxWidth() .onGloballyPositioned { coordinates -> //This value is used to assign to the DropDown the same width textFieldSize = coordinates.size.toSize() }, text = viewModel.state.employeeType.name, label = "Employee Type", leadingIcon = Icons.Default.Accessibility, onValueChange = {}, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, ) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier.width(with(LocalDensity.current) { textFieldSize.width.toDp() }), ) { DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeeTypeChanged(EmployeeType.FullTime) ) expanded = false } ) { Text( text = EmployeeType.FullTime.name, style = MaterialTheme.typography.body1, ) } Divider(modifier = Modifier.fillMaxWidth()) DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeeTypeChanged(EmployeeType.PartTime) ) expanded = false } ) { Text( text = EmployeeType.PartTime.name, style = MaterialTheme.typography.body1, ) } } } } item(EMPLOYEE_POSITION_FIELD) { ExposedDropdownMenuBox( expanded = positionDropdownToggled, onExpandedChange = { positionDropdownToggled = !positionDropdownToggled }, modifier = Modifier.testTag(EMPLOYEE_POSITION_FIELD), ) { StandardOutlinedTextField( modifier = Modifier .fillMaxWidth() .onGloballyPositioned { coordinates -> //This value is used to assign to the DropDown the same width textFieldSize = coordinates.size.toSize() }, text = viewModel.state.employeePosition, label = "Employee Position", readOnly = true, leadingIcon = Icons.Default.Star, error = positionError, errorTag = EMPLOYEE_POSITION_ERROR, onValueChange = { viewModel.onEvent(AddEditEmployeeEvent.EmployeePositionChanged(it)) positionDropdownToggled = true // }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = positionDropdownToggled) }, ) DropdownMenu( expanded = positions.isNotEmpty() && positionDropdownToggled, properties = PopupProperties( focusable = false, dismissOnBackPress = true, dismissOnClickOutside = true, ), onDismissRequest = { positionDropdownToggled = false }, modifier = Modifier.width(with(LocalDensity.current) { textFieldSize.width.toDp() }), ) { positions.forEachIndexed { index, positionName -> DropdownMenuItem( modifier = Modifier.fillMaxWidth(), onClick = { viewModel.onEvent( AddEditEmployeeEvent.EmployeePositionChanged(positionName) ) positionDropdownToggled = false } ) { Text( text = positionName, style = MaterialTheme.typography.body1, ) } if (index != positions.size - 1) { Divider(modifier = Modifier.fillMaxWidth()) } } } } } item(EMPLOYEE_JOINED_DATE_FIELD) { StandardOutlinedTextField( text = viewModel.state.employeeJoinedDate.toSalaryDate, label = "Employee Joined Date", leadingIcon = Icons.Default.CalendarMonth, error = null, onValueChange = {}, trailingIcon = { IconButton( onClick = { dialogState.show() }, modifier = Modifier.testTag(EMPLOYEE_JOINED_DATE_FIELD) ) { Icon( imageVector = Icons.Default.CalendarToday, contentDescription = "Choose Date" ) } } ) } } } MaterialDialog( dialogState = dialogState, buttons = { positiveButton("Ok") negativeButton("Cancel") } ) { datepicker(allowedDateValidator = { date -> date <= LocalDate.now() }) { date -> viewModel.onEvent(AddEditEmployeeEvent.EmployeeJoinedDateChanged(date.toMilliSecond)) } } }
34
Kotlin
0
1
2020b913df5030525c582218f6a91a7a3466ee2c
22,027
POS-Application
MIT License
core/src/jvmAndroidMain/kotlin/com/lehaine/littlekt/util/JvmUtils.kt
littlektframework
442,309,478
false
{"Kotlin": 2285392}
package com.lehaine.littlekt.util import com.lehaine.littlekt.util.internal.clamp import java.util.* /** * @author <NAME> * @date 12/8/2021 */ actual fun Double.toString(precision: Int): String = String.format(Locale.ENGLISH, "%.${precision.clamp(0, 12)}f", this)
14
Kotlin
9
291
89f372fd18e47998d9b1d3add93ba92e4dcaca6e
269
littlekt
Apache License 2.0
app/src/main/java/au/com/mealplanner/mealplanner/feature/main/AddMealTypeView.kt
jess-leung
123,775,089
false
{"Kotlin": 35798}
package au.com.mealplanner.mealplanner.feature.main interface AddMealTypeView { fun updateWeeklyPlanView() }
0
Kotlin
0
0
114eceb65b5efbed4e985b1f7c0d1d675fd16bc2
114
meal-planner
Apache License 2.0
build-conventions/src/main/kotlin/ext/ProjectExtension.kt
mpetuska
417,156,746
false
{"Kotlin": 42938, "Shell": 639}
package ext import org.gradle.api.Project @Suppress("LeakingThis") abstract class ProjectExtension { protected abstract val project: Project }
11
Kotlin
1
45
c8c6c1f08b26317f03738f8bcebc51a8edc4ed6b
147
kon
Apache License 2.0
app/src/main/java/de/drtobiasprinz/summitbook/db/entities/SportType.kt
prinztob
370,702,913
false
null
package de.drtobiasprinz.summitbook.db.entities import de.drtobiasprinz.summitbook.R enum class SportType( val sportNameStringId: Int, val imageIdBlack: Int, val imageIdWhite: Int, val markerIdWithGpx: Int, val markerIdWithoutGpx: Int, val color: Int ) { Bicycle( R.string.bicycle, R.drawable.icons8_cycling_50, R.drawable.icons8_cycling_white_50, R.drawable.ic_filled_location_green_48, R.drawable.ic_outline_location_green_48, R.color.green_200 ), Racer( R.string.racer, R.drawable.icons8_racer_50, R.drawable.icons8_racer_white_50, R.drawable.ic_filled_location_green_48, R.drawable.ic_outline_location_green_48, R.color.green_600 ), IndoorTrainer( R.string.indoor_trainer, R.drawable.icons8_spinning_50, R.drawable.icons8_spinning_white_50, R.drawable.ic_filled_location_green_48, R.drawable.ic_outline_location_green_48, R.color.green_800 ), Mountainbike( R.string.mountainbike, R.drawable.icons8_mtb_50, R.drawable.icons8_mtb_white_50, R.drawable.ic_filled_location_red_48, R.drawable.ic_outline_location_red_48, R.color.red_400 ), BikeAndHike( R.string.bikeAndHike, R.drawable.icons8_mtb_50, R.drawable.icons8_mtb_white_50, R.drawable.ic_filled_location_black_48, R.drawable.ic_outline_location_black_48, R.color.black ), Climb( R.string.climb, R.drawable.icons8_climbing_50, R.drawable.icons8_climbing_white_50, R.drawable.ic_filled_location_darkbrown_48, R.drawable.ic_outline_location_darkbrown_48, R.color.brown_400 ), Hike( R.string.hike, R.drawable.icons8_trekking_50, R.drawable.icons8_trekking_white_50, R.drawable.ic_filled_location_lightbrown_48, R.drawable.ic_outline_location_lightbrown_48, R.color.orange_600 ), Running( R.string.running, R.drawable.icons8_running_50, R.drawable.icons8_running_white_50, R.drawable.ic_filled_location_lightbrown_48, R.drawable.ic_outline_location_lightbrown_48, R.color.orange_100 ), Skitour( R.string.skitour, R.drawable.icon_ski_touring, R.drawable.icon_ski_touring_white, R.drawable.ic_filled_location_blue_48, R.drawable.ic_outline_location_blue_48, R.color.blue_400 ), Other( R.string.other, R.drawable.ic_baseline_accessibility_24_black, R.drawable.ic_baseline_accessibility_24_white, R.drawable.ic_filled_location_black_48, R.drawable.ic_outline_location_black_48, R.color.grey_400 ); override fun toString(): String { return name } } enum class SportGroup(val sportTypes: List<SportType>) { Bike( listOf( SportType.Bicycle, SportType.Racer, SportType.IndoorTrainer, SportType.Mountainbike ) ), Foot(listOf(SportType.Climb, SportType.Hike, SportType.Skitour)) }
0
Kotlin
0
0
b7bbb8f6a6edc5c42fc7e98dacc50032f52957ad
3,203
summitbook
MIT License
komga/src/main/kotlin/org/gotson/komga/infrastructure/jooq/LibraryDao.kt
TSedlar
271,205,793
true
{"Kotlin": 410108, "Vue": 162981, "TypeScript": 43088, "TSQL": 9369, "JavaScript": 2708, "PLSQL": 2130, "Shell": 1470, "HTML": 704, "Dockerfile": 513, "CSS": 309}
package org.gotson.komga.infrastructure.jooq import org.gotson.komga.domain.model.Library import org.gotson.komga.domain.persistence.LibraryRepository import org.gotson.komga.jooq.Sequences.HIBERNATE_SEQUENCE import org.gotson.komga.jooq.Tables import org.gotson.komga.jooq.tables.records.LibraryRecord import org.jooq.DSLContext import org.springframework.stereotype.Component import java.net.URL @Component class LibraryDao( private val dsl: DSLContext ) : LibraryRepository { private val l = Tables.LIBRARY private val ul = Tables.USER_LIBRARY_SHARING override fun findByIdOrNull(libraryId: Long): Library? = dsl.selectFrom(l) .where(l.ID.eq(libraryId)) .fetchOneInto(l) ?.toDomain() override fun findAll(): Collection<Library> = dsl.selectFrom(l) .fetchInto(l) .map { it.toDomain() } override fun findAllById(libraryIds: Collection<Long>): Collection<Library> = dsl.selectFrom(l) .where(l.ID.`in`(libraryIds)) .fetchInto(l) .map { it.toDomain() } override fun existsByName(name: String): Boolean = dsl.fetchExists( dsl.selectFrom(l) .where(l.NAME.equalIgnoreCase(name)) ) override fun delete(libraryId: Long) { dsl.transaction { config -> with(config.dsl()) { deleteFrom(ul).where(ul.LIBRARY_ID.eq(libraryId)).execute() deleteFrom(l).where(l.ID.eq(libraryId)).execute() } } } override fun deleteAll() { dsl.transaction { config -> with(config.dsl()) { deleteFrom(ul).execute() deleteFrom(l).execute() } } } override fun insert(library: Library): Library { val id = dsl.nextval(HIBERNATE_SEQUENCE) dsl.insertInto(l) .set(l.ID, id) .set(l.NAME, library.name) .set(l.ROOT, library.root.toString()) .execute() return findByIdOrNull(id)!! } override fun count(): Long = dsl.fetchCount(l).toLong() private fun LibraryRecord.toDomain() = Library( name = name, root = URL(root), id = id, createdDate = createdDate, lastModifiedDate = lastModifiedDate ) }
0
Kotlin
0
0
78b215ee1e8380305415a441f02e563e39ec60ba
2,136
komga
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/FaceAnguished.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.FaceAnguished: ImageVector get() { if (_faceAnguished != null) { return _faceAnguished!! } _faceAnguished = Builder(name = "FaceAnguished", 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(8.0f, 14.0f) curveToRelative(-1.105f, 0.0f, -2.0f, -0.895f, -2.0f, -2.0f) reflectiveCurveToRelative(0.895f, -2.0f, 2.0f, -2.0f) reflectiveCurveToRelative(2.0f, 0.895f, 2.0f, 2.0f) reflectiveCurveToRelative(-0.895f, 2.0f, -2.0f, 2.0f) close() moveTo(16.0f, 10.0f) curveToRelative(-1.105f, 0.0f, -2.0f, 0.895f, -2.0f, 2.0f) reflectiveCurveToRelative(0.895f, 2.0f, 2.0f, 2.0f) reflectiveCurveToRelative(2.0f, -0.895f, 2.0f, -2.0f) reflectiveCurveToRelative(-0.895f, -2.0f, -2.0f, -2.0f) close() moveTo(12.0f, 14.0f) curveToRelative(-2.209f, 0.0f, -4.0f, 1.791f, -4.0f, 4.0f) horizontalLineToRelative(8.0f) curveToRelative(0.0f, -2.209f, -1.791f, -4.0f, -4.0f, -4.0f) close() moveTo(24.0f, 12.0f) curveToRelative(0.0f, 6.617f, -5.383f, 12.0f, -12.0f, 12.0f) reflectiveCurveTo(0.0f, 18.617f, 0.0f, 12.0f) reflectiveCurveTo(5.383f, 0.0f, 12.0f, 0.0f) reflectiveCurveToRelative(12.0f, 5.383f, 12.0f, 12.0f) close() moveTo(21.0f, 12.0f) curveToRelative(0.0f, -4.963f, -4.038f, -9.0f, -9.0f, -9.0f) reflectiveCurveTo(3.0f, 7.037f, 3.0f, 12.0f) reflectiveCurveToRelative(4.038f, 9.0f, 9.0f, 9.0f) reflectiveCurveToRelative(9.0f, -4.037f, 9.0f, -9.0f) close() moveTo(9.332f, 6.555f) lineToRelative(-1.664f, -1.109f) curveToRelative(-0.773f, 1.159f, -1.852f, 2.058f, -3.039f, 2.531f) lineToRelative(0.741f, 1.857f) curveToRelative(1.582f, -0.631f, 2.952f, -1.765f, 3.962f, -3.279f) close() moveTo(16.332f, 5.446f) lineToRelative(-1.664f, 1.109f) curveToRelative(1.01f, 1.515f, 2.38f, 2.648f, 3.962f, 3.279f) lineToRelative(0.741f, -1.857f) curveToRelative(-1.187f, -0.474f, -2.266f, -1.372f, -3.039f, -2.531f) close() } } .build() return _faceAnguished!! } private var _faceAnguished: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,510
icons
MIT License