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
kotlinx-coroutines-core/common/src/flow/internal/NullSurrogate.kt
hltj
151,721,407
true
null
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow.internal import kotlinx.coroutines.internal.* import kotlin.jvm.* /** * This value is used a a surrogate `null` value when needed. * It should never leak to the outside world. */ @JvmField @SharedImmutable internal val NULL = Symbol("NULL") /* * Symbol used to indicate that the flow is complete. * It should never leak to the outside world. */ @JvmField @SharedImmutable internal val DONE = Symbol("DONE")
1
Kotlin
106
255
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
559
kotlinx.coroutines-cn
Apache License 2.0
app/src/main/java/com/rokoblak/gittrendingcompose/ui/screens/main/MainScreen.kt
oblakr24
641,592,280
false
{"Kotlin": 146539}
package com.rokoblak.gittrendingcompose.ui.screens.main import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import com.rokoblak.gittrendingcompose.ui.screens.repodetails.RepoDetailsRoute import com.rokoblak.gittrendingcompose.ui.screens.reposlisting.ListingReposRoute import com.rokoblak.gittrendingcompose.ui.theme.GitTrendingComposeTheme data class MainScreenUIState( val isDarkTheme: Boolean?, ) @Composable fun MainScreen(viewModel: MainViewModel = hiltViewModel()) { val state = viewModel.uiState.collectAsState(MainScreenUIState(isDarkTheme = null)).value val navController = rememberNavController() GitTrendingComposeTheme(overrideDarkMode = state.isDarkTheme) { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background, ) { MainNavHostContainer(navController) } } } @Composable private fun MainNavHostContainer(navController: NavHostController) { NavHost(navController = navController, startDestination = ListingReposRoute.route) { ListingReposRoute.register(this, navController) RepoDetailsRoute.register(this, navController) } }
0
Kotlin
0
0
46b9059ec372952253f0b310eac51f69f0574967
1,598
GitTrendingCompose
Apache License 2.0
src/main/kotlin/com/github/jyc228/keth/client/eth/CallRequest.kt
jyc228
833,953,853
false
{"Kotlin": 217816, "Solidity": 5515}
package com.github.jyc228.keth.client.eth import com.github.jyc228.keth.type.Address import com.github.jyc228.keth.type.HexBigInt import kotlinx.serialization.Serializable @Serializable data class CallRequest( var from: Address? = null, var to: Address? = null, var gas: HexBigInt? = null, var gasPrice: HexBigInt? = null, var value: HexBigInt? = null, var data: String? = null )
0
Kotlin
0
2
4fd6f900b4e80b5f731090f33c1ddc10c6ede9ca
406
keth-client
Apache License 2.0
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/loop/PaintingLoopIndex.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * 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.meistercharts.canvas import kotlin.jvm.JvmInline /** * Identifies the paint loop index. * * Attention: This variable *will* overflow (from [Int.MAX_VALUE] to `0`. * Please do not use the value to do calculations. * * Assume that the index will overflow after about 414 days (when painting with 60 fps). */ @JvmInline value class PaintingLoopIndex(val value: Int) { /** * Returns the next painting index. * ATTENTION: The value will overflow */ fun next(): PaintingLoopIndex { if (value == Int.MAX_VALUE) { //Overflow to 0 (not Int.MIN_VALUE) return PaintingLoopIndex(0) } val newIndex = value + 1 require(newIndex >= 0) { "Invalid new index $newIndex for old value $value" } return PaintingLoopIndex(newIndex) } override fun toString(): String { return "$value" } companion object { /** * Specifies a loop index that will not happen naturally. * Can be used to specify an unknown index. */ val Unknown: PaintingLoopIndex = PaintingLoopIndex(-1) } }
3
null
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
1,672
meistercharts
Apache License 2.0
app/src/main/java/com/rahul/kotlin/architecture/extension/RecyclerViewExt.kt
rahuljpZignuts
642,706,535
false
{"Kotlin": 225818}
package com.rahul.compose.architecture.extension import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator fun RecyclerView.disableItemAnimator() { itemAnimator?.changeDuration = 0 (itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false }
0
Kotlin
0
0
7e7f21c7489133e094bd918771476c7d8ea48e42
311
AndroidArchitecture-Kotlin
Apache License 2.0
app/src/main/kotlin/io/getstream/android/video/chat/compose/ui/menu/base/DynamicMenu.kt
GetStream
792,097,214
false
null
/* * Copyright (c) 2014-2024 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-video-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.video.android.ui.menu.base import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyItemScope import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf 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.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.getstream.video.android.compose.theme.base.VideoTheme import io.getstream.video.android.compose.ui.components.base.StreamToggleButton import io.getstream.video.android.compose.ui.components.base.styling.StyleSize import io.getstream.video.android.ui.menu.debugSubmenu import io.getstream.video.android.ui.menu.defaultStreamMenu /** * A composable capable of loading a menu based on a list structure of menu items and sub menus. * There are three types of items: * - [ActionMenuItem] - shown normally as an item that can be clicked. * - [SubMenuItem] - that contains another list of [ActionMenuItem] o [SubMenuItem] which will be shown when clicked. * - [DynamicSubMenuItem] - that shows a spinner and calls a loading function before behaving as [SubMenuItem] * * The transition and history between the items is automatic. */ @OptIn(ExperimentalFoundationApi::class) @Composable fun DynamicMenu(header: (@Composable LazyItemScope.() -> Unit)? = null, items: List<MenuItem>) { val history = remember { mutableStateListOf<Pair<String, SubMenuItem>>() } val dynamicItems = remember { mutableStateListOf<MenuItem>() } var loadedItems by remember { mutableStateOf(false) } Box( modifier = Modifier .fillMaxWidth() .background( color = VideoTheme.colors.baseSheetPrimary, shape = VideoTheme.shapes.dialog, ), ) { LazyColumn( modifier = Modifier .fillMaxWidth() .background( shape = VideoTheme.shapes.sheet, color = VideoTheme.colors.baseSheetPrimary, ) .padding(12.dp), ) { if (history.isEmpty()) { header?.let { item(content = header) } menuItems(items) { history.add(Pair(it.title, it)) } } else { val lastContent = history.last() stickyHeader { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .background(VideoTheme.colors.baseSheetPrimary) .fillMaxWidth(), ) { IconButton(onClick = { history.removeLastOrNull() }) { Icon( tint = VideoTheme.colors.basePrimary, imageVector = Icons.AutoMirrored.Default.ArrowBack, contentDescription = "Back", ) } Text( text = lastContent.first, style = VideoTheme.typography.subtitleS, color = VideoTheme.colors.basePrimary, ) } } val subMenu = lastContent.second val dynamicMenu = subMenu as? DynamicSubMenuItem if (dynamicMenu != null) { if (!loadedItems) { dynamicItems.clear() loadingItems(dynamicMenu) { loadedItems = true dynamicItems.addAll(it) } } if (dynamicItems.isNotEmpty()) { menuItems(dynamicItems) { history.add(Pair(it.title, it)) } } else if (loadedItems) { noItems() } } else { if (subMenu.items.isEmpty()) { noItems() } else { menuItems(subMenu.items) { history.add(Pair(it.title, it)) } } } } } } } private fun LazyListScope.loadingItems( dynamicMenu: DynamicSubMenuItem, onLoaded: (List<MenuItem>) -> Unit, ) { item { LaunchedEffect(key1 = dynamicMenu) { onLoaded(dynamicMenu.itemsLoader.invoke()) } LinearProgressIndicator( modifier = Modifier .padding(33.dp) .fillMaxWidth(), color = VideoTheme.colors.basePrimary, ) } } private fun LazyListScope.noItems() { item { Text( modifier = Modifier .fillMaxWidth() .padding(32.dp), textAlign = TextAlign.Center, text = "No items", style = VideoTheme.typography.subtitleS, color = VideoTheme.colors.basePrimary, ) } } private fun LazyListScope.menuItems( items: List<MenuItem>, onNewSubmenu: (SubMenuItem) -> Unit, ) { items(items.size) { index -> val item = items[index] val highlight = item.highlight StreamToggleButton( onText = item.title, offText = item.title, onIcon = item.icon, onStyle = VideoTheme.styles.buttonStyles.toggleButtonStyleOn(StyleSize.XS).copy( iconStyle = VideoTheme.styles.iconStyles.customColorIconStyle( color = if (highlight) VideoTheme.colors.brandPrimary else VideoTheme.colors.basePrimary, ), ), onClick = { val actionItem = item as? ActionMenuItem actionItem?.action?.invoke() val menuItem = item as? SubMenuItem menuItem?.let { onNewSubmenu(it) } }, ) } } @Preview @Composable private fun DynamicMenuPreview() { VideoTheme { DynamicMenu( items = defaultStreamMenu( codecList = emptyList(), onCodecSelected = {}, isScreenShareEnabled = false, isBackgroundBlurEnabled = true, onToggleScreenShare = { }, onShowCallStats = { }, onToggleBackgroundBlurClick = { }, onToggleAudioFilterClick = { }, onRestartSubscriberIceClick = { }, onRestartPublisherIceClick = { }, onKillSfuWsClick = { }, onSwitchSfuClick = { }, availableDevices = emptyList(), onDeviceSelected = {}, onShowFeedback = {}, loadRecordings = { emptyList() }, ), ) } } @Preview @Composable private fun DynamicMenuDebugOptionPreview() { VideoTheme { DynamicMenu( items = defaultStreamMenu( showDebugOptions = true, codecList = emptyList(), onCodecSelected = {}, isScreenShareEnabled = true, isBackgroundBlurEnabled = true, onToggleScreenShare = { }, onShowCallStats = { }, onToggleBackgroundBlurClick = { }, onToggleAudioFilterClick = { }, onRestartSubscriberIceClick = { }, onRestartPublisherIceClick = { }, onKillSfuWsClick = { }, onSwitchSfuClick = { }, availableDevices = emptyList(), onDeviceSelected = {}, onShowFeedback = {}, loadRecordings = { emptyList() }, ), ) } } @Preview @Composable private fun DynamicMenuDebugPreview() { VideoTheme { DynamicMenu( items = debugSubmenu( codecList = emptyList(), onCodecSelected = {}, onKillSfuWsClick = { }, onRestartPublisherIceClick = { }, onRestartSubscriberIceClick = { }, onToggleAudioFilterClick = { }, onSwitchSfuClick = { }, ), ) } }
8
null
8
73
e358f24f4e356df9ddb8dc2d74a1d38fa118f41a
10,066
android-video-chat
Apache License 2.0
app/src/main/kotlin/io/getstream/android/video/chat/compose/ui/menu/base/DynamicMenu.kt
GetStream
792,097,214
false
null
/* * Copyright (c) 2014-2024 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-video-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.video.android.ui.menu.base import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyItemScope import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf 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.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.getstream.video.android.compose.theme.base.VideoTheme import io.getstream.video.android.compose.ui.components.base.StreamToggleButton import io.getstream.video.android.compose.ui.components.base.styling.StyleSize import io.getstream.video.android.ui.menu.debugSubmenu import io.getstream.video.android.ui.menu.defaultStreamMenu /** * A composable capable of loading a menu based on a list structure of menu items and sub menus. * There are three types of items: * - [ActionMenuItem] - shown normally as an item that can be clicked. * - [SubMenuItem] - that contains another list of [ActionMenuItem] o [SubMenuItem] which will be shown when clicked. * - [DynamicSubMenuItem] - that shows a spinner and calls a loading function before behaving as [SubMenuItem] * * The transition and history between the items is automatic. */ @OptIn(ExperimentalFoundationApi::class) @Composable fun DynamicMenu(header: (@Composable LazyItemScope.() -> Unit)? = null, items: List<MenuItem>) { val history = remember { mutableStateListOf<Pair<String, SubMenuItem>>() } val dynamicItems = remember { mutableStateListOf<MenuItem>() } var loadedItems by remember { mutableStateOf(false) } Box( modifier = Modifier .fillMaxWidth() .background( color = VideoTheme.colors.baseSheetPrimary, shape = VideoTheme.shapes.dialog, ), ) { LazyColumn( modifier = Modifier .fillMaxWidth() .background( shape = VideoTheme.shapes.sheet, color = VideoTheme.colors.baseSheetPrimary, ) .padding(12.dp), ) { if (history.isEmpty()) { header?.let { item(content = header) } menuItems(items) { history.add(Pair(it.title, it)) } } else { val lastContent = history.last() stickyHeader { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .background(VideoTheme.colors.baseSheetPrimary) .fillMaxWidth(), ) { IconButton(onClick = { history.removeLastOrNull() }) { Icon( tint = VideoTheme.colors.basePrimary, imageVector = Icons.AutoMirrored.Default.ArrowBack, contentDescription = "Back", ) } Text( text = lastContent.first, style = VideoTheme.typography.subtitleS, color = VideoTheme.colors.basePrimary, ) } } val subMenu = lastContent.second val dynamicMenu = subMenu as? DynamicSubMenuItem if (dynamicMenu != null) { if (!loadedItems) { dynamicItems.clear() loadingItems(dynamicMenu) { loadedItems = true dynamicItems.addAll(it) } } if (dynamicItems.isNotEmpty()) { menuItems(dynamicItems) { history.add(Pair(it.title, it)) } } else if (loadedItems) { noItems() } } else { if (subMenu.items.isEmpty()) { noItems() } else { menuItems(subMenu.items) { history.add(Pair(it.title, it)) } } } } } } } private fun LazyListScope.loadingItems( dynamicMenu: DynamicSubMenuItem, onLoaded: (List<MenuItem>) -> Unit, ) { item { LaunchedEffect(key1 = dynamicMenu) { onLoaded(dynamicMenu.itemsLoader.invoke()) } LinearProgressIndicator( modifier = Modifier .padding(33.dp) .fillMaxWidth(), color = VideoTheme.colors.basePrimary, ) } } private fun LazyListScope.noItems() { item { Text( modifier = Modifier .fillMaxWidth() .padding(32.dp), textAlign = TextAlign.Center, text = "No items", style = VideoTheme.typography.subtitleS, color = VideoTheme.colors.basePrimary, ) } } private fun LazyListScope.menuItems( items: List<MenuItem>, onNewSubmenu: (SubMenuItem) -> Unit, ) { items(items.size) { index -> val item = items[index] val highlight = item.highlight StreamToggleButton( onText = item.title, offText = item.title, onIcon = item.icon, onStyle = VideoTheme.styles.buttonStyles.toggleButtonStyleOn(StyleSize.XS).copy( iconStyle = VideoTheme.styles.iconStyles.customColorIconStyle( color = if (highlight) VideoTheme.colors.brandPrimary else VideoTheme.colors.basePrimary, ), ), onClick = { val actionItem = item as? ActionMenuItem actionItem?.action?.invoke() val menuItem = item as? SubMenuItem menuItem?.let { onNewSubmenu(it) } }, ) } } @Preview @Composable private fun DynamicMenuPreview() { VideoTheme { DynamicMenu( items = defaultStreamMenu( codecList = emptyList(), onCodecSelected = {}, isScreenShareEnabled = false, isBackgroundBlurEnabled = true, onToggleScreenShare = { }, onShowCallStats = { }, onToggleBackgroundBlurClick = { }, onToggleAudioFilterClick = { }, onRestartSubscriberIceClick = { }, onRestartPublisherIceClick = { }, onKillSfuWsClick = { }, onSwitchSfuClick = { }, availableDevices = emptyList(), onDeviceSelected = {}, onShowFeedback = {}, loadRecordings = { emptyList() }, ), ) } } @Preview @Composable private fun DynamicMenuDebugOptionPreview() { VideoTheme { DynamicMenu( items = defaultStreamMenu( showDebugOptions = true, codecList = emptyList(), onCodecSelected = {}, isScreenShareEnabled = true, isBackgroundBlurEnabled = true, onToggleScreenShare = { }, onShowCallStats = { }, onToggleBackgroundBlurClick = { }, onToggleAudioFilterClick = { }, onRestartSubscriberIceClick = { }, onRestartPublisherIceClick = { }, onKillSfuWsClick = { }, onSwitchSfuClick = { }, availableDevices = emptyList(), onDeviceSelected = {}, onShowFeedback = {}, loadRecordings = { emptyList() }, ), ) } } @Preview @Composable private fun DynamicMenuDebugPreview() { VideoTheme { DynamicMenu( items = debugSubmenu( codecList = emptyList(), onCodecSelected = {}, onKillSfuWsClick = { }, onRestartPublisherIceClick = { }, onRestartSubscriberIceClick = { }, onToggleAudioFilterClick = { }, onSwitchSfuClick = { }, ), ) } }
8
null
8
73
e358f24f4e356df9ddb8dc2d74a1d38fa118f41a
10,066
android-video-chat
Apache License 2.0
app/src/main/java/com/example/latestnewsapp/domain/useCase/DeleteSavedNewsUseCase.kt
tusharjha44
506,074,565
false
{"Kotlin": 39392}
package com.example.latestnewsapp.domain.useCase import com.example.latestnewsapp.data.model.Article import com.example.latestnewsapp.domain.repository.NewsRepository class DeleteSavedNewsUseCase(private val newsRepository: NewsRepository) { suspend fun execute(article: Article){ return newsRepository.deleteNews(article) } }
0
Kotlin
0
1
37c0e70ebdb2054f8d84ccd446f990aaa7ee454f
346
NewsAPIApp
MIT License
src/main/kotlin/no/nav/familie/ba/sak/kjerne/vedtak/begrunnelser/SanityEØSBegrunnelse.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.kjerne.vedtak.begrunnelser import no.nav.familie.ba.sak.kjerne.brev.domene.ISanityBegrunnelse import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.AnnenForeldersAktivitet import no.nav.familie.ba.sak.kjerne.eøs.kompetanse.domene.KompetanseResultat import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Vilkår enum class BarnetsBostedsland { NORGE, IKKE_NORGE; } fun landkodeTilBarnetsBostedsland(landkode: String): BarnetsBostedsland = when (landkode) { "NO" -> BarnetsBostedsland.NORGE else -> BarnetsBostedsland.IKKE_NORGE } data class RestSanityEØSBegrunnelse( val apiNavn: String?, val navnISystem: String?, val annenForeldersAktivitet: List<String>?, val barnetsBostedsland: List<String>?, val kompetanseResultat: List<String>?, val hjemler: List<String>?, val hjemlerFolketrygdloven: List<String>?, val hjemlerEOSForordningen883: List<String>?, val hjemlerEOSForordningen987: List<String>?, val hjemlerSeperasjonsavtalenStorbritannina: List<String>?, val eosVilkaar: List<String>? = null ) { fun tilSanityEØSBegrunnelse(): SanityEØSBegrunnelse? { if (apiNavn == null || navnISystem == null) return null return SanityEØSBegrunnelse( apiNavn = apiNavn, navnISystem = navnISystem, annenForeldersAktivitet = annenForeldersAktivitet?.mapNotNull { konverterTilEnumverdi<AnnenForeldersAktivitet>(it) } ?: emptyList(), barnetsBostedsland = barnetsBostedsland?.mapNotNull { konverterTilEnumverdi<BarnetsBostedsland>(it) } ?: emptyList(), kompetanseResultat = kompetanseResultat?.mapNotNull { konverterTilEnumverdi<KompetanseResultat>(it) } ?: emptyList(), hjemler = hjemler ?: emptyList(), hjemlerFolketrygdloven = hjemlerFolketrygdloven ?: emptyList(), hjemlerEØSForordningen883 = hjemlerEOSForordningen883 ?: emptyList(), hjemlerEØSForordningen987 = hjemlerEOSForordningen987 ?: emptyList(), hjemlerSeperasjonsavtalenStorbritannina = hjemlerSeperasjonsavtalenStorbritannina ?: emptyList(), vilkår = eosVilkaar?.mapNotNull { konverterTilEnumverdi<Vilkår>(it) } ?: emptyList() ) } private inline fun <reified T> konverterTilEnumverdi(it: String): T? where T : Enum<T> = enumValues<T>().find { enum -> enum.name == it } } data class SanityEØSBegrunnelse( override val apiNavn: String, override val navnISystem: String, val annenForeldersAktivitet: List<AnnenForeldersAktivitet>, val barnetsBostedsland: List<BarnetsBostedsland>, val kompetanseResultat: List<KompetanseResultat>, val hjemler: List<String>, val hjemlerFolketrygdloven: List<String>, val hjemlerEØSForordningen883: List<String>, val hjemlerEØSForordningen987: List<String>, val hjemlerSeperasjonsavtalenStorbritannina: List<String>, val vilkår: List<Vilkår> ) : ISanityBegrunnelse fun List<SanityEØSBegrunnelse>.finnBegrunnelse(eøsBegrunnelse: EØSStandardbegrunnelse): SanityEØSBegrunnelse? = this.find { it.apiNavn == eøsBegrunnelse.sanityApiNavn }
17
Kotlin
1
9
2f4dd839f0cf38a983515ab4b119735d70ecfc00
3,226
familie-ba-sak
MIT License
app/src/main/java/com/romarickc/reminder/MyApplication.kt
RomaricKc1
794,945,527
false
{"Kotlin": 131733}
package com.romarickc.reminder import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication : Application()
0
Kotlin
1
2
2658c3c27a6349f647eeee86d960651cbf44ab58
157
WaterReminder
MIT License
app/src/main/java/co/nimblehq/compose/crypto/ui/screens/home/HomeViewModel.kt
nimblehq
503,287,253
false
null
package co.nimblehq.compose.crypto.ui.screens.home import co.nimblehq.compose.crypto.domain.usecase.GetMyCoinsUseCase import co.nimblehq.compose.crypto.domain.usecase.GetTrendingCoinsUseCase import co.nimblehq.compose.crypto.lib.IsLoading import co.nimblehq.compose.crypto.ui.base.* import co.nimblehq.compose.crypto.ui.navigation.AppDestination import co.nimblehq.compose.crypto.ui.uimodel.CoinItemUiModel import co.nimblehq.compose.crypto.ui.uimodel.toUiModel import co.nimblehq.compose.crypto.util.DispatchersProvider import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import javax.inject.Inject const val FIAT_CURRENCY = "usd" private const val MY_COINS_ORDER = "market_cap_desc" private const val MY_COINS_PRICE_CHANGE_IN_HOUR = "24h" private const val MY_COINS_ITEM_PER_PAGE = 10 private const val MY_COINS_INITIAL_PAGE = 1 interface Input : BaseInput { fun loadData(isRefreshing: Boolean = false) fun getTrendingCoins(isRefreshing: Boolean = false, loadMore: Boolean = false) fun onMyCoinsItemClick(coin: CoinItemUiModel) fun onTrendingCoinsItemClick(coin: CoinItemUiModel) } interface Output : BaseOutput { val showMyCoinsLoading: StateFlow<IsLoading> val showTrendingCoinsLoading: StateFlow<LoadingState> val myCoins: StateFlow<List<CoinItemUiModel>> val trendingCoins: StateFlow<List<CoinItemUiModel>> val myCoinsError: SharedFlow<Throwable?> val trendingCoinsError: SharedFlow<Throwable?> } @HiltViewModel class HomeViewModel @Inject constructor( dispatchers: DispatchersProvider, private val getMyCoinsUseCase: GetMyCoinsUseCase, private val getTrendingCoinsUseCase: GetTrendingCoinsUseCase ) : BaseViewModel(dispatchers), Input, Output { override val input = this override val output = this private val _showMyCoinsLoading = MutableStateFlow(false) override val showMyCoinsLoading: StateFlow<IsLoading> get() = _showMyCoinsLoading private val _showTrendingCoinsLoading = MutableStateFlow<LoadingState>(LoadingState.Idle) override val showTrendingCoinsLoading: StateFlow<LoadingState> get() = _showTrendingCoinsLoading private val _myCoins = MutableStateFlow<List<CoinItemUiModel>>(emptyList()) override val myCoins: StateFlow<List<CoinItemUiModel>> get() = _myCoins private val _trendingCoins = MutableStateFlow<List<CoinItemUiModel>>(emptyList()) override val trendingCoins: StateFlow<List<CoinItemUiModel>> get() = _trendingCoins private val _myCoinsError = MutableStateFlow<Throwable?>(null) override val myCoinsError: StateFlow<Throwable?> get() = _myCoinsError private val _trendingCoinsError = MutableStateFlow<Throwable?>(null) override val trendingCoinsError: StateFlow<Throwable?> get() = _trendingCoinsError private var trendingCoinsPage = MY_COINS_INITIAL_PAGE init { loadData() } override fun loadData(isRefreshing: Boolean) { if (isRefreshing) { trendingCoinsPage = MY_COINS_INITIAL_PAGE } getMyCoins(isRefreshing = isRefreshing) getTrendingCoins(isRefreshing = isRefreshing) } private fun getMyCoins(isRefreshing: Boolean) = execute { if (isRefreshing) { showLoading() } else { _showMyCoinsLoading.value = true } getMyCoinsUseCase.execute( GetMyCoinsUseCase.Input( currency = FIAT_CURRENCY, order = MY_COINS_ORDER, priceChangeInHour = MY_COINS_PRICE_CHANGE_IN_HOUR, itemPerPage = MY_COINS_ITEM_PER_PAGE, page = MY_COINS_INITIAL_PAGE ) ) .catch { e -> _myCoinsError.emit(e) } .collect { coins -> _myCoins.emit(coins.map { it.toUiModel() }) } if (isRefreshing) hideLoading() else _showMyCoinsLoading.value = false } override fun getTrendingCoins(isRefreshing: Boolean, loadMore: Boolean) { if (_showTrendingCoinsLoading.value != LoadingState.Idle) return execute { if (isRefreshing) showLoading() else _showTrendingCoinsLoading.value = if (loadMore) LoadingState.LoadingMore else LoadingState.Loading getTrendingCoinsUseCase.execute( GetTrendingCoinsUseCase.Input( currency = FIAT_CURRENCY, order = MY_COINS_ORDER, priceChangeInHour = MY_COINS_PRICE_CHANGE_IN_HOUR, itemPerPage = MY_COINS_ITEM_PER_PAGE, page = trendingCoinsPage ) ) .catch { e -> _trendingCoinsError.emit(e) } .collect { coins -> val newCoinList = coins.map { it.toUiModel() } if (isRefreshing) { _trendingCoins.emit(newCoinList) } else { _trendingCoins.emit(_trendingCoins.value + newCoinList) } trendingCoinsPage++ } if (isRefreshing) hideLoading() else _showTrendingCoinsLoading.value = LoadingState.Idle } } override fun onMyCoinsItemClick(coin: CoinItemUiModel) { execute { _navigator.emit(AppDestination.CoinDetail.buildDestination(coin.id)) } } override fun onTrendingCoinsItemClick(coin: CoinItemUiModel) { execute { _navigator.emit(AppDestination.CoinDetail.buildDestination(coin.id)) } } }
6
null
4
9
4f78e720513ecbcf84e372209b184f879c59dcaa
5,678
jetpack-compose-crypto
MIT License
app/src/main/java/com/example/inventory/ui/item/PetDetailsScreen.kt
guilhelp
861,441,942
false
{"Kotlin": 60115}
package com.example.inventory.ui.item import androidx.annotation.StringRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.rememberImagePainter import com.example.inventory.InventoryTopAppBar import com.example.inventory.R import com.example.inventory.data.Pet import com.example.inventory.ui.AppViewModelProvider import com.example.inventory.ui.navigation.NavigationDestination import com.example.inventory.ui.theme.InventoryTheme import kotlinx.coroutines.launch object PetDetailsDestination : NavigationDestination { override val route = "pet_details" override val titleRes = R.string.pet_detail_title const val petIdArg = "petId" val routeWithArgs = "$route/{$petIdArg}" } @OptIn(ExperimentalMaterial3Api::class) @Composable fun PetDetailsScreen( navigateToEditPet: (Int) -> Unit, navigateBack: () -> Unit, modifier: Modifier = Modifier, viewModel: PetDetailsViewModel = viewModel(factory = AppViewModelProvider.Factory) ) { val uiState = viewModel.uiState.collectAsState() val coroutineScope = rememberCoroutineScope() Scaffold( topBar = { InventoryTopAppBar( title = stringResource(PetDetailsDestination.titleRes), canNavigateBack = true, navigateUp = navigateBack ) }, floatingActionButton = { FloatingActionButton( onClick = { navigateToEditPet(uiState.value.petDetails.id) }, shape = MaterialTheme.shapes.medium, modifier = Modifier .padding( end = WindowInsets.safeDrawing.asPaddingValues() .calculateEndPadding(LocalLayoutDirection.current) ) ) { Icon( imageVector = Icons.Default.Edit, contentDescription = stringResource(R.string.edit_item_title), ) } }, modifier = modifier, ) { innerPadding -> PetDetailsBody( petDetailsUiState = uiState.value, onDelete = { coroutineScope.launch { viewModel.deletePet() navigateBack() } }, modifier = Modifier .padding( start = innerPadding.calculateStartPadding(LocalLayoutDirection.current), top = innerPadding.calculateTopPadding(), end = innerPadding.calculateEndPadding(LocalLayoutDirection.current), ) .verticalScroll(rememberScrollState()) ) } } @Composable private fun PetDetailsBody( petDetailsUiState: PetDetailsUiState, onDelete: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier.padding(dimensionResource(id = R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_medium)) ) { var deleteConfirmationRequired by rememberSaveable { mutableStateOf(false) } PetDetails( pet = petDetailsUiState.petDetails.toPet(), modifier = Modifier.fillMaxWidth() ) OutlinedButton( onClick = { deleteConfirmationRequired = true }, shape = MaterialTheme.shapes.small, modifier = Modifier.fillMaxWidth() ) { Text(stringResource(R.string.delete)) } if (deleteConfirmationRequired) { DeleteConfirmationDialog( onDeleteConfirm = { deleteConfirmationRequired = false onDelete() }, onDeleteCancel = { deleteConfirmationRequired = false }, modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_medium)) ) } } } @Composable fun PetDetails( pet: Pet, modifier: Modifier = Modifier ) { Card( modifier = modifier, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) { Column( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(id = R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_medium)) ) { PetDetailsRow( labelResID = R.string.pet, petDetail = pet.nome, modifier = Modifier.padding( horizontal = dimensionResource(id = R.dimen.padding_medium) ) ) PetDetailsRow( labelResID = R.string.idade, petDetail = pet.idade.toString(), modifier = Modifier.padding( horizontal = dimensionResource(id = R.dimen.padding_medium) ) ) Image( painter = rememberImagePainter(pet.foto), contentDescription = pet.nome, modifier = Modifier .fillMaxWidth() .height(200.dp) .padding(dimensionResource(id = R.dimen.padding_medium)) ) } } } @Composable private fun PetDetailsRow( @StringRes labelResID: Int, petDetail: String, modifier: Modifier = Modifier ) { Row(modifier = modifier) { Text(text = stringResource(labelResID)) Spacer(modifier = Modifier.weight(1f)) Text(text = petDetail, fontWeight = FontWeight.Bold) } } @Composable private fun DeleteConfirmationDialog( onDeleteConfirm: () -> Unit, onDeleteCancel: () -> Unit, modifier: Modifier = Modifier ) { AlertDialog(onDismissRequest = { /* Do nothing */ }, title = { Text(stringResource(R.string.attention)) }, text = { Text(stringResource(R.string.delete_question)) }, modifier = modifier, dismissButton = { TextButton(onClick = onDeleteCancel) { Text(text = stringResource(R.string.no)) } }, confirmButton = { TextButton(onClick = onDeleteConfirm) { Text(text = stringResource(R.string.yes)) } }) } @Preview(showBackground = true) @Composable fun PetDetailsScreenPreview() { InventoryTheme { PetDetailsBody(PetDetailsUiState( petDetails = PetDetails(1, "Billy", 5, "teste") ), onDelete = {}) } }
0
Kotlin
0
0
fd6d931e855fd16d71374029dc930dd363b727cd
8,712
aumigos-project
Apache License 2.0
src/test/kotlin/S05c10p10AlignmentLocalTest.kt
jimandreas
377,843,697
false
null
@file:Suppress("UNUSED_VARIABLE", "MemberVisibilityCanBePrivate") import algorithms.AlignmentLocal import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test /** * Code Challenge: Solve the Local Alignment Problem. Input: Two protein strings written in the single-letter amino acid alphabet. Output: The maximum score of a local alignment of the strings, followed by a local alignment of these strings achieving the maximum score. Use the PAM250 scoring matrix for matches and mismatches as well as the indel penalty σ = 5. Note: this could be combined with the Local Alignment code. Most of the code change occurs in the outputLCS function. But in the interests of clarity and reduction of complexity, the changes to find the maximum score will occur only here. MODIFIED: to accept: A match score m, a mismatch penalty μ, a gap penalty σ These are set up when the class is instantiated. A modal flag indicates whether to use the PAM250 match/mismatch matrix. The changes involve using the scoring matrix to calculate the winning value for each cell. * See also: * stepik: @link: https://stepik.org/lesson/240305/step/10?unit=212651 * rosalind: @link: http://rosalind.info/problems/ba5e/ * book (5.10): http://rosalind.info/problems/ba5f/ */ internal class S05c10p10AlignmentLocalTest { /** * Test the scoring function - this checks to make sure the PAM250 * match matrix is set up for those tests that use it. */ @Test @DisplayName("local alignment - matrix input test") fun localAlignmentMatrixInputTest() { val la = AlignmentLocal(0, 0, 0, usePAM250 = true) val test1 = la.score('Y', 'Y') assertEquals(10, test1) val test2 = la.score('A', 'A') assertEquals(2, test2) } /* * first sample in the Test Dataset * This test makes sure that your code correctly parses the first line of input and uses the correct penalties. */ @Test @DisplayName("local alignment test 01") fun localAlignmentTest01() { val sample = """ Input: 3 3 1 AGC ATC Output: 4 A-GC AT-C """.trimIndent() runTest(sample) } /* * second sample in the Test Dataset * This test makes sure that the mismatch penalties are being correctly applied. */ @Test @DisplayName("local alignment test 02") fun localAlignmentTest02() { val sample = """ Input: 1 1 1 AT AG Output: 1 A A """.trimIndent() runTest(sample) } /* * TEST DATASET 3: * This test makes sure that your code can correctly * find the highest scoring alignment, wherever it is in the dynamic programming matrix. */ @Test @DisplayName("local alignment test 03") fun localAlignmentTest03() { val sample = """ Input: 1 1 1 TAACG ACGTG Output: 3 ACG ACG """.trimIndent() runTest(sample) } /** * This test makes sure that your code can handle inputs in * which the strings vary drastically in length. */ @Test @DisplayName("local alignment test 04") fun localAlignmentTest04() { val sample = """ Input: 3 2 1 CAGAGATGGCCG ACG Output: 6 CG CG """.trimIndent() runTest(sample) } /** * This dataset checks that your code can handle inputs * in which the two strings to be aligned are different lengths. */ @Test @DisplayName("local alignment test 05") fun localAlignmentTest05() { val sample = """ Input: 2 3 1 CTT AGCATAAAGCATT Output: 5 C-TT CATT """.trimIndent() runTest(sample) } /** Problem from Description TODO: build a test that compares the Global, Local, and Fitting algorithms as per the text “Fitting” w to v requires finding a substring v′ of v that maximizes the global alignment score between v′ and w among all substrings of v. For example, the best global, local, and fitting alignments of v = CGTAGGCTTAAGGTTA and w = ATAGATA are shown in the figure below (with mismatch and indel penalties equal to 1). @link: https://stepik.org/lesson/240306/step/4?unit=212652 "Note in the figure that the optimal local alignment (with score 3) is not a valid fitting alignment. On the other hand, the score of the optimal global alignment (6 - 9 - 1 = -4) is smaller than that of the best fitting alignment (5 - 2 - 2 = +1)." */ @Test @DisplayName("local alignment text example") fun localAlignmentTextExampleTest() { val sample = """ Input: 1 1 1 CGTAGGCTTAAGGTTA ATAGATA Output: 3 TAG TAG """.trimIndent() runTest(sample) } fun runTest(sample: String, usePAM250: Boolean = false) { val reader = sample.reader() val lines = reader.readLines() val parms = lines[1].split(" ").map { it.toInt() } val match = parms[0] val mismatch = parms[1] val gap = parms[2] val la = AlignmentLocal(match, mismatch, gap, usePAM250) val sRow = lines[2] val tCol = lines[3] val scoreExpected = lines[5].toInt() val sRowAlignedExpected = lines[6] val tColAlignedExpected = lines[7] val result = la.localAlignment(sRow, tCol) val scoreResult = result.first val sRowResult = result.second val tColResult = result.third assertEquals(scoreExpected, scoreResult) assertEquals(sRowAlignedExpected, sRowResult) assertEquals(tColAlignedExpected, tColResult) } /* * the sample problem */ @Test @DisplayName("local alignment test 99") fun localAlignmentTest99() { val sample = """ Sample Input: 0 0 5 MEANLY PENALTY Sample Output: 15 EANL-Y ENALTY """.trimIndent() runTest(sample, usePAM250 = true) } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
6,569
stepikBioinformaticsCourse
Apache License 2.0
app/src/main/java/com/imaginato/homeworkmvvm/data/remote/login/request/LoginRequestModel.kt
dev-tecocraft
578,121,863
false
null
package com.imaginato.homeworkmvvm.data.remote.login.request import com.google.gson.annotations.SerializedName data class LoginRequestModel( @SerializedName("username") val userName: String? = null, val password: String? = null, )
0
Kotlin
0
0
87b4df41bcbac49cce6b55d521573cf69cc581e9
246
android-test
Apache License 2.0
EcoSwapAndroid/src/main/java/com/darrenthiores/ecoswap/android/presentation/components/header/SettingHeader.kt
darrenthiores
688,372,873
false
{"Kotlin": 770054, "Swift": 362583}
package com.darrenthiores.ecoswap.android.presentation.components.header import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowBack import androidx.compose.material.icons.rounded.MoreHoriz import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.darrenthiores.ecoswap.android.presentation.components.buttons.CircleButton import com.darrenthiores.ecoswap.android.theme.EcoSwapTheme import com.darrenthiores.ecoswap.android.theme.HeadlineB @Composable fun SettingHeader( modifier: Modifier = Modifier, text: String, onBackClick: () -> Unit, onSettingClick: () -> Unit ) { Row( modifier = modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { CircleButton( icon = Icons.Rounded.ArrowBack ) { onBackClick() } Spacer(modifier = Modifier.width(16.dp)) Text( modifier = Modifier .weight(1f), text = text, style = HeadlineB, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.width(16.dp)) CircleButton( icon = Icons.Rounded.MoreHoriz ) { onSettingClick() } } } @Preview @Composable private fun SettingHeaderPreview() { EcoSwapTheme { SettingHeader( text = "My Profile", onBackClick = { } ) { } } }
0
Kotlin
0
0
792b3293b4e378b7482f948ce4de622cb88f3cf1
1,932
EcoSwap
MIT License
presentation/src/main/java/com/no1/taiwan/stationmusicfm/internal/di/AppModule.kt
SmashKs
168,842,876
false
null
/* * Copyright (C) 2019 The Smash Ks Open Project * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.no1.taiwan.stationmusicfm.internal.di import android.content.Context import com.google.firebase.analytics.FirebaseAnalytics import com.hwangjr.rxbus.Bus import com.hwangjr.rxbus.RxBus import com.no1.taiwan.stationmusicfm.player.ExoPlayerWrapper import com.no1.taiwan.stationmusicfm.player.MusicPlayer import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance /** * To provide the necessary App objects(singleton) for the whole app. */ object AppModule { /** * Provider the objects by using application context. * * @param context */ fun appProvider(context: Context) = Kodein.Module("Application Module") { bind<MusicPlayer>() with instance(ExoPlayerWrapper(context)) bind<Bus>() with instance(RxBus.get()) bind<FirebaseAnalytics>() with instance(FirebaseAnalytics.getInstance(context)) } }
0
Kotlin
1
5
696fadc54bc30fe72f9115bdec2dacdac8cd4394
2,034
StationMusicFM
MIT License
kt/entry-generation/godot-entry-generator/src/main/kotlin/godot/entrygenerator/ext/FqNameExtensions.kt
utopia-rise
289,462,532
false
null
package godot.entrygenerator.ext import godot.entrygenerator.EntryGenerator import godot.entrygenerator.model.JvmType fun String.fqNameIsJvmType(vararg jvmTypes: JvmType): Boolean = jvmTypes.any { jvmType -> EntryGenerator .jvmTypeFqNamesProvider(jvmType) .any { jvmTypeFqName -> jvmTypeFqName == this } } val JvmType.fqName: Set<String> get() = EntryGenerator.jvmTypeFqNamesProvider(this)
63
null
44
634
ac2a1bd5ea931725e2ed19eb5093dea171962e3f
417
godot-kotlin-jvm
MIT License
feature/src/main/kotlin/de/scout/fireplace/feature/settings/CurrencyFormatter.kt
Scout24
96,885,938
false
null
package de.scout.fireplace.feature.settings import java.text.NumberFormat import java.util.Locale import javax.inject.Inject internal class CurrencyFormatter @Inject constructor() : StringFormatter { private val format = NumberFormat.getCurrencyInstance(Locale.GERMANY) override fun format(value: Int): String = format.format(value) }
0
Kotlin
0
0
9c4532cf447d6df5a55c42628ce9dd85e7068e76
343
is24-fireplace-android
Apache License 2.0
arrow-libs/core/arrow-core/src/jvmTest/kotlin/examples/example-iterable-16.kt
arrow-kt
86,057,409
false
{"Kotlin": 1993399, "Java": 434}
// This file was automatically generated from Iterable.kt by Knit tool. Do not edit. package arrow.core.examples.exampleIterable16 import arrow.core.* import io.kotest.matchers.shouldBe fun test() { listOf("A".left(), 2.right(), "C".left(), 4.right()) .separateEither() shouldBe Pair(listOf("A", "C"), listOf(2, 4)) }
42
Kotlin
451
6,170
c47d9bcfbb402f827b312dbcfec1d5cf68ba2fc3
326
arrow
Apache License 2.0
AnylineSDK-Examples/AnylineSDK-Examples-Source/app/src/main/java/io/anyline/examples/HubspotRequestBody.kt
njlaboet
447,931,425
false
{"XML": 200, "Markdown": 2, "Git Attributes": 1, "HTML": 147, "Ignore List": 1, "Text": 1, "Java Properties": 2, "Gradle": 3, "INI": 1, "JSON": 47, "Java": 96, "Kotlin": 13, "JavaScript": 1, "CSS": 1, "JAR Manifest": 1}
package io.anyline.examples data class HubspotRequestBody( val fields: ArrayList<Field>, val legalConsentOptions: LegalConsentOptions ) { data class Field( val name: String, val value: String ) data class LegalConsentOptions( val consent: Consent ) { data class Consent( val consentToProcess: Boolean, val text: String, val communications: ArrayList<Communication> ) { data class Communication( val value: Boolean, val subscriptionTypeId: Int, val text: String ) } } }
1
null
1
1
26734abf76d4186294ba7a26e0ba116200a4865e
701
anyline-ocr-examples-android
Apache License 2.0
app/src/main/java/com/nan/xarch/network/INetworkService.kt
huannan
402,384,136
false
null
package com.nan.xarch.network import com.nan.xarch.bean.VideoBean import com.nan.xarch.network.base.BaseResponse import retrofit2.http.GET import retrofit2.http.Query interface INetworkService { @GET("videodetail") suspend fun requestVideoDetail(@Query("id") id: String): BaseResponse<VideoBean> }
2
null
107
524
cf64c7907fb47dab652a13ac341cc35aee0bf751
308
XArch
Apache License 2.0
health/health-services-client/src/main/java/androidx/health/services/client/data/PassiveMonitoringUpdate.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * 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 androidx.health.services.client.data import android.content.Intent import android.os.Parcel import android.os.Parcelable /** * Represents an update from Passive tracking. * * Provides [DataPoint] s associated with the Passive tracking, in addition to data related to the * user's [UserActivityState]. */ public data class PassiveMonitoringUpdate( /** List of [DataPoint] s from Passive tracking. */ val dataPoints: List<DataPoint>, /** The [UserActivityInfo] of the user from Passive tracking. */ val userActivityInfoUpdates: List<UserActivityInfo>, ) : Parcelable { /** * Puts the state as an extra into a given [Intent]. The state can then be obtained from the * intent via [PassiveMonitoringUpdate.fromIntent]. */ public fun putToIntent(intent: Intent) { intent.putExtra(EXTRA_KEY, this) } override fun describeContents(): Int = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(dataPoints.size) dest.writeTypedArray(dataPoints.toTypedArray(), flags) dest.writeInt(userActivityInfoUpdates.size) dest.writeTypedArray(userActivityInfoUpdates.toTypedArray(), flags) } public companion object { private const val EXTRA_KEY = "hs.passive_monitoring_update" @JvmField public val CREATOR: Parcelable.Creator<PassiveMonitoringUpdate> = object : Parcelable.Creator<PassiveMonitoringUpdate> { override fun createFromParcel(source: Parcel): PassiveMonitoringUpdate? { val dataPointsArray: Array<DataPoint?> = arrayOfNulls(source.readInt()) source.readTypedArray(dataPointsArray, DataPoint.CREATOR) val userActivityInfoArray: Array<UserActivityInfo?> = arrayOfNulls(source.readInt()) source.readTypedArray(userActivityInfoArray, UserActivityInfo.CREATOR) return PassiveMonitoringUpdate( dataPointsArray.filterNotNull().toList(), userActivityInfoArray.filterNotNull().toList(), ) } override fun newArray(size: Int): Array<PassiveMonitoringUpdate?> { return arrayOfNulls(size) } } /** * Creates a [PassiveMonitoringUpdate] from an [Intent]. Returns null if no * [PassiveMonitoringUpdate] is stored in the given intent. */ @JvmStatic public fun fromIntent(intent: Intent): PassiveMonitoringUpdate? = intent.getParcelableExtra(EXTRA_KEY) } }
0
Java
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,287
androidx
Apache License 2.0
node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt
stanly-johnson
133,830,866
true
{"Gradle": 49, "INI": 27, "Markdown": 31, "Shell": 12, "Text": 12, "Ignore List": 4, "Batchfile": 4, "XML": 48, "Java": 84, "Kotlin": 1161, "Java Properties": 2, "Gherkin": 3, "Groovy": 2, "RPM Spec": 1, "CSS": 10, "SVG": 1, "PowerShell": 1, "JSON": 3, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "Makefile": 1, "reStructuredText": 115, "Python": 1, "TeX": 5, "BibTeX": 1}
package net.corda.node.internal import net.corda.core.concurrent.CordaFuture import net.corda.core.contracts.ContractState import net.corda.core.crypto.SecureHash import net.corda.core.doOnError import net.corda.core.flows.FlowLogic import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name import net.corda.core.internal.concurrent.doOnError import net.corda.core.internal.concurrent.mapError import net.corda.core.mapErrors import net.corda.core.messaging.CordaRPCOps import net.corda.core.messaging.DataFeed import net.corda.core.messaging.FlowHandle import net.corda.core.messaging.FlowProgressHandle import net.corda.core.node.services.vault.* import net.corda.core.utilities.loggerFor import net.corda.nodeapi.exceptions.InternalNodeException import net.corda.nodeapi.exceptions.adapters.InternalObfuscatingFlowHandle import net.corda.nodeapi.exceptions.adapters.InternalObfuscatingFlowProgressHandle import java.io.InputStream import java.security.PublicKey class RpcExceptionHandlingProxy(private val delegate: SecureCordaRPCOps) : CordaRPCOps { private companion object { private val logger = loggerFor<RpcExceptionHandlingProxy>() } override val protocolVersion: Int get() = delegate.protocolVersion override fun <T> startFlowDynamic(logicType: Class<out FlowLogic<T>>, vararg args: Any?): FlowHandle<T> = wrap { val handle = delegate.startFlowDynamic(logicType, *args) val result = InternalObfuscatingFlowHandle(handle) result.returnValue.doOnError { error -> logger.error(error.message, error) } result } override fun <T> startTrackedFlowDynamic(logicType: Class<out FlowLogic<T>>, vararg args: Any?): FlowProgressHandle<T> = wrap { val handle = delegate.startTrackedFlowDynamic(logicType, *args) val result = InternalObfuscatingFlowProgressHandle(handle) result.returnValue.doOnError { error -> logger.error(error.message, error) } result } override fun waitUntilNetworkReady() = wrapFuture(delegate::waitUntilNetworkReady) override fun stateMachinesFeed() = wrapFeed(delegate::stateMachinesFeed) override fun <T : ContractState> vaultTrackBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>) = wrapFeed { delegate.vaultTrackBy(criteria, paging, sorting, contractStateType) } override fun <T : ContractState> vaultTrack(contractStateType: Class<out T>) = wrapFeed { delegate.vaultTrack(contractStateType) } override fun <T : ContractState> vaultTrackByCriteria(contractStateType: Class<out T>, criteria: QueryCriteria) = wrapFeed { delegate.vaultTrackByCriteria(contractStateType, criteria) } override fun <T : ContractState> vaultTrackByWithPagingSpec(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification) = wrapFeed { delegate.vaultTrackByWithPagingSpec(contractStateType, criteria, paging) } override fun <T : ContractState> vaultTrackByWithSorting(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort) = wrapFeed { delegate.vaultTrackByWithSorting(contractStateType, criteria, sorting) } override fun stateMachineRecordedTransactionMappingFeed() = wrapFeed(delegate::stateMachineRecordedTransactionMappingFeed) override fun networkMapFeed() = wrapFeed(delegate::networkMapFeed) override fun networkParametersFeed() = wrapFeed(delegate::networkParametersFeed) override fun internalVerifiedTransactionsFeed() = wrapFeed(delegate::internalVerifiedTransactionsFeed) override fun stateMachinesSnapshot() = wrap(delegate::stateMachinesSnapshot) override fun <T : ContractState> vaultQueryBy(criteria: QueryCriteria, paging: PageSpecification, sorting: Sort, contractStateType: Class<out T>) = wrap { delegate.vaultQueryBy(criteria, paging, sorting, contractStateType) } override fun <T : ContractState> vaultQuery(contractStateType: Class<out T>) = wrap { delegate.vaultQuery(contractStateType) } override fun <T : ContractState> vaultQueryByCriteria(criteria: QueryCriteria, contractStateType: Class<out T>) = wrap { delegate.vaultQueryByCriteria(criteria, contractStateType) } override fun <T : ContractState> vaultQueryByWithPagingSpec(contractStateType: Class<out T>, criteria: QueryCriteria, paging: PageSpecification) = wrap { delegate.vaultQueryByWithPagingSpec(contractStateType, criteria, paging) } override fun <T : ContractState> vaultQueryByWithSorting(contractStateType: Class<out T>, criteria: QueryCriteria, sorting: Sort) = wrap { delegate.vaultQueryByWithSorting(contractStateType, criteria, sorting) } override fun internalVerifiedTransactionsSnapshot() = wrap(delegate::internalVerifiedTransactionsSnapshot) override fun stateMachineRecordedTransactionMappingSnapshot() = wrap(delegate::stateMachineRecordedTransactionMappingSnapshot) override fun networkMapSnapshot() = wrap(delegate::networkMapSnapshot) override fun acceptNewNetworkParameters(parametersHash: SecureHash) = wrap { delegate.acceptNewNetworkParameters(parametersHash) } override fun nodeInfo() = wrap(delegate::nodeInfo) override fun notaryIdentities() = wrap(delegate::notaryIdentities) override fun addVaultTransactionNote(txnId: SecureHash, txnNote: String) = wrap { delegate.addVaultTransactionNote(txnId, txnNote) } override fun getVaultTransactionNotes(txnId: SecureHash) = wrap { delegate.getVaultTransactionNotes(txnId) } override fun attachmentExists(id: SecureHash) = wrap { delegate.attachmentExists(id) } override fun openAttachment(id: SecureHash) = wrap { delegate.openAttachment(id) } override fun uploadAttachment(jar: InputStream) = wrap { delegate.uploadAttachment(jar) } override fun uploadAttachmentWithMetadata(jar: InputStream, uploader: String, filename: String) = wrap { delegate.uploadAttachmentWithMetadata(jar, uploader, filename) } override fun queryAttachments(query: AttachmentQueryCriteria, sorting: AttachmentSort?) = wrap { delegate.queryAttachments(query, sorting) } override fun currentNodeTime() = wrap(delegate::currentNodeTime) override fun wellKnownPartyFromAnonymous(party: AbstractParty) = wrap { delegate.wellKnownPartyFromAnonymous(party) } override fun partyFromKey(key: PublicKey) = wrap { delegate.partyFromKey(key) } override fun wellKnownPartyFromX500Name(x500Name: CordaX500Name) = wrap { delegate.wellKnownPartyFromX500Name(x500Name) } override fun notaryPartyFromX500Name(x500Name: CordaX500Name) = wrap { delegate.notaryPartyFromX500Name(x500Name) } override fun partiesFromName(query: String, exactMatch: Boolean) = wrap { delegate.partiesFromName(query, exactMatch) } override fun registeredFlows() = wrap(delegate::registeredFlows) override fun nodeInfoFromParty(party: AbstractParty) = wrap { delegate.nodeInfoFromParty(party) } override fun clearNetworkMapCache() = wrap(delegate::clearNetworkMapCache) override fun setFlowsDrainingModeEnabled(enabled: Boolean) = wrap { delegate.setFlowsDrainingModeEnabled(enabled) } override fun isFlowsDrainingModeEnabled() = wrap(delegate::isFlowsDrainingModeEnabled) override fun shutdown() = wrap(delegate::shutdown) private fun <RESULT> wrap(call: () -> RESULT): RESULT { return try { call.invoke() } catch (error: Throwable) { logger.error(error.message, error) throw InternalNodeException.obfuscateIfInternal(error) } } private fun <SNAPSHOT, ELEMENT> wrapFeed(call: () -> DataFeed<SNAPSHOT, ELEMENT>) = wrap { call.invoke().doOnError { error -> logger.error(error.message, error) }.mapErrors(InternalNodeException.Companion::obfuscateIfInternal) } private fun <RESULT> wrapFuture(call: () -> CordaFuture<RESULT>): CordaFuture<RESULT> = wrap { call.invoke().mapError(InternalNodeException.Companion::obfuscateIfInternal).doOnError { error -> logger.error(error.message, error) } } }
0
Kotlin
0
0
f6bc59115f4ec8c053a7cd5b94a8f2ef612d9160
8,022
corda
Apache License 2.0
app/src/main/java/com/epigram/android/data/arch/utils/LoadNextPage.kt
tomstark99
192,521,547
false
{"Gradle": 3, "XML": 217, "Java Properties": 4, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "INI": 2, "JSON": 2, "Proguard": 1, "Kotlin": 71, "Java": 5}
package com.epigram.android.data.arch.utils import android.widget.ImageView import com.epigram.android.data.model.Post interface LoadNextPage { fun bottomReached() fun onPostClicked(clicked: Post, titleImage: ImageView?) }
6
null
1
1
5223721d071377ebcbfb07460d0803cf21cd74c9
232
epigram
Apache License 2.0
app/src/main/java/com/yifu/ladianbao/ui/login/LoginContract.kt
maqc666
221,878,066
false
{"Java": 974782, "Kotlin": 143045}
package com.yifu.ladianbao.ui.login import com.yifu.ladianbao.base.BasePresent import com.yifu.ladianbao.base.BaseView class LoginContract { interface View : BaseView { fun onLoginSuccess(bean: UserBean) fun onLoginFail(msg: String) fun onIndexSuccess(bean: UserBean) fun onIndexFail(msg: String) } abstract class Presenter : BasePresent<View>() { abstract fun login(username: String, password: String) abstract fun index(token: String,username: String, password: String) } }
1
null
1
1
387990132bd2d07778d2f6797b01289eb35ebd65
543
ladianbao
Apache License 2.0
themeEngine/src/main/java/com/quickersilver/themeengine/ThemeMode.kt
prathameshmm02
484,720,663
false
null
package com.neko.themeengine object ThemeMode { const val AUTO = 0 const val LIGHT = 1 const val DARK = 2 }
1
null
4
53
383151622708ff589a9024cebdfe59a7784ad586
120
ThemeEngine
Apache License 2.0
src/main/java/uk/gov/justice/digital/hmpps/whereabouts/model/VideoLinkAppointment.kt
uk-gov-mirror
356,783,561
false
null
package uk.gov.justice.digital.hmpps.whereabouts.model import javax.persistence.Entity import javax.persistence.EnumType import javax.persistence.Enumerated import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.Table enum class HearingType { MAIN, PRE, POST } @Entity @Table(name = "VIDEO_LINK_APPOINTMENT") data class VideoLinkAppointment( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, val bookingId: Long, val appointmentId: Long, val court: String, @Enumerated(EnumType.STRING) val hearingType: HearingType, val createdByUsername: String? = null, val madeByTheCourt: Boolean? = true )
1
null
1
1
fcb65de589127fb83239a288c579b6fe8db4fde6
727
ministryofjustice.whereabouts-api
Apache License 2.0
tripart/src/main/java/com/jn/kiku/ttp/chat/MobManage.kt
JerrNeon
196,114,074
false
null
package com.jn.kiku.ttp.chat import android.app.Activity import android.content.Context import com.hyphenate.chat.ChatClient import com.hyphenate.chat.ChatClient.ConnectionListener import com.hyphenate.chat.ChatManager.MessageListener import com.hyphenate.chat.Message import com.hyphenate.helpdesk.callback.Callback import com.hyphenate.helpdesk.callback.ValueCallBack import com.hyphenate.helpdesk.easeui.util.IntentBuilder import com.jn.kiku.ttp.BuildConfig import com.jn.kiku.ttp.TtpConstants /** * Author:Stevie.Chen Time:2020/09/08 10:48 * Class Comment:环信管理 */ object MobManage { fun init(context: Context?, logEnable: Boolean = BuildConfig.DEBUG) { ChatClient.getInstance().init( context, ChatClient.Options() .setAppkey(TtpConstants.MOB_APPKEY) //必填项,appkey获取地址:kefu.easemob.com,“管理员模式 > 渠道管理 > 手机APP”页面的关联的“Ap .setTenantId(TtpConstants.MOB_TENANTID) //必填项,tenantId获取地址:kefu.easemob.com,“管理员模式 > 设置 > 企业信息”页面的“租户ID” .setConsoleLog(logEnable) ) //是否开启日志 } /** * 注册 * * @param username 用户名 * @param password 密码 */ fun register(username: String?, password: String?) { ChatClient.getInstance().register(username, password, object : Callback { override fun onSuccess() {} /*ErrorCode: Error.NETWORK_ERROR 网络不可用 Error.USER_ALREADY_EXIST 用户已存在 Error.USER_AUTHENTICATION_FAILED 无开放注册权限(后台管理界面设置[开放|授权]) Error.USER_ILLEGAL_ARGUMENT 用户名非法 */ override fun onError(i: Int, s: String) {} override fun onProgress(i: Int, s: String) {} }) } /** * 登录 * * @param username 用户名 * @param password 密码 */ fun login(username: String?, password: String?) { ChatClient.getInstance().login(username, password, object : Callback { override fun onSuccess() {} /*ErrorCode: Error.NETWORK_ERROR 网络不可用 Error.USER_ALREADY_EXIST 用户已存在 Error.USER_AUTHENTICATION_FAILED 无开放注册权限(后台管理界面设置[开放|授权]) Error.USER_ILLEGAL_ARGUMENT 用户名非法 */ override fun onError(i: Int, s: String) {} override fun onProgress(i: Int, s: String) {} }) } /** * 登录 * * @param username 用户名 * @param token token */ fun loginWithToken(username: String?, token: String?) { ChatClient.getInstance().loginWithToken(username, token, object : Callback { override fun onSuccess() {} /*ErrorCode: Error.NETWORK_ERROR 网络不可用 Error.USER_ALREADY_EXIST 用户已存在 Error.USER_AUTHENTICATION_FAILED 无开放注册权限(后台管理界面设置[开放|授权]) Error.USER_ILLEGAL_ARGUMENT 用户名非法 */ override fun onError(i: Int, s: String) {} override fun onProgress(i: Int, s: String) {} }) } /** * 退出登录 */ fun logout() { // unbindToken:是否解绑推送的devicetoken ChatClient.getInstance().logout(true, object : Callback { override fun onSuccess() {} /*ErrorCode: Error.NETWORK_ERROR 网络不可用 Error.USER_ALREADY_EXIST 用户已存在 Error.USER_AUTHENTICATION_FAILED 无开放注册权限(后台管理界面设置[开放|授权]) Error.USER_ILLEGAL_ARGUMENT 用户名非法 */ override fun onError(i: Int, s: String) {} override fun onProgress(i: Int, s: String) {} }) } /** * 是否已经登录 * * @return true:登录 */ val isLogin: Boolean get() = ChatClient.getInstance().isLoggedInBefore /** * 打开客服界面 * * @param activity Activity * @param toChatUsername 客服 */ fun openServiceUI(activity: Activity, toChatUsername: String?) { val intent = IntentBuilder(activity) .setServiceIMNumber(toChatUsername) //客服关联的IM服务号 获取地址:kefu.easemob.com,“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号” .build() activity.startActivity(intent) } /** * 创建一个新的留言 * * @param postContent 留言内容 * @param projectId 留言ProjectId 进入“管理员模式 → 留言”,可以看到这个Project ID * @param imUser 接入环信移动客服系统使用的关联的IM服务号 */ fun createLeaveMsg(postContent: String?, projectId: String?, imUser: String?) { ChatClient.getInstance().leaveMsgManager() .createLeaveMsg(postContent, projectId, imUser, object : ValueCallBack<String?> { override fun onSuccess(o: String?) {} override fun onError(i: Int, s: String) {} }) } /** * 添加网络监听,可以显示当前是否连接服务器 */ fun addConnectionListener() { ChatClient.getInstance().addConnectionListener(object : ConnectionListener { override fun onConnected() { //成功连接到服务器 } /* errorcode的值 Error.USER_REMOVED 账号移除 Error.USER_LOGIN_ANOTHER_DEVICE 账号在其他地方登录 Error.USER_AUTHENTICATION_FAILED 账号密码错误 Error.USER_NOT_FOUND 账号找不到 */ override fun onDisconnected(errorcode: Int) {} }) } /** * 添加消息监听 */ fun addMessageListener() { ChatClient.getInstance().chatManager().addMessageListener(object : MessageListener { override fun onMessage(list: List<Message>) { //收到普通消息 } override fun onCmdMessage(list: List<Message>) { //收到命令消息,命令消息不存数据库,一般用来作为系统通知,例如留言评论更新, //会话被客服接入,被转接,被关闭提醒 } override fun onMessageStatusUpdate() { //消息的状态修改,一般可以用来刷新列表,显示最新的状态 } override fun onMessageSent() { //发送消息后,会调用,可以在此刷新列表,显示最新的消息 } }) } }
0
Kotlin
1
1
bc6675aee4514111981626b48a888efdcbe5ddc2
5,987
Kiku-kotlin
Apache License 2.0
java/java-tests/testSrc/com/intellij/codeInsight/daemon/inlays/IntentionTest.kt
yanglikun
75,526,976
true
{"Text": 2606, "XML": 4282, "Ant Build System": 20, "Shell": 35, "Markdown": 8, "Ignore List": 23, "Git Attributes": 4, "Batchfile": 24, "Java": 52489, "Java Properties": 86, "HTML": 2473, "Kotlin": 618, "Groovy": 2339, "JavaScript": 1257, "JFlex": 23, "XSLT": 109, "CSS": 70, "desktop": 2, "Python": 8024, "INI": 186, "SVG": 194, "C#": 32, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 182, "CoffeeScript": 3, "JSON with Comments": 1, "Perl": 4, "J": 18, "Protocol Buffer": 2, "JAR Manifest": 8, "fish": 1, "Gradle": 32, "E-mail": 18, "Roff": 38, "Roff Manpage": 1, "Gherkin": 4, "Diff": 16, "YAML": 89, "Maven POM": 1, "Checksums": 58, "Java Server Pages": 24, "C": 37, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "Scala": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "Microsoft Visual Studio Solution": 9, "C++": 20, "CMake": 1, "Objective-C": 9, "OpenStep Property List": 2, "VBScript": 1, "NSIS": 8, "EditorConfig": 1, "Thrift": 2, "Cython": 7, "TeX": 7, "reStructuredText": 41, "Gettext Catalog": 125, "Jupyter Notebook": 5, "Regular Expression": 5}
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.inlays import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.openapi.editor.Inlay import org.assertj.core.api.Assertions.assertThat class BlackListMethodIntentionTest: InlayParameterHintsTest() { fun `test add to blacklist by alt enter`() { configureFile("a.java", """ class Test { void test() { check(<caret>100); } void check(int isShow) {} } """) val before = onLineStartingWith("check").inlays[0].getHintText() assertThat(before).isNotEmpty() val intention = myFixture.getAvailableIntention("Do not show hints for current method") myFixture.launchAction(intention!!) myFixture.doHighlighting() val after = onLineStartingWith("check").inlays[0].getHintText() assertThat(after).isNull() } private fun Inlay.getHintText() = ParameterHintsPresentationManager.getInstance().getHintText(this) }
0
Java
0
0
831581de7f10a135b181bc43a18b6cbe8c251c66
1,543
intellij-community
Apache License 2.0
app/src/main/java/com/example/kotlincodingtest/baekjoon/기타/피보나치_함수.kt
ichanguk
788,416,368
false
{"Kotlin": 233781}
package com.example.kotlincodingtest.baekjoon.기타 import java.io.BufferedReader import java.io.BufferedWriter fun main() = with(BufferedReader(System.`in`.bufferedReader())) { val T = readLine().toInt() val dp = MutableList(41) { Pair(0, 0) } dp[0] = Pair(1, 0) dp[1] = Pair(0, 1) for (i in 2..40) { dp[i] = Pair(dp[i - 1].first + dp[i - 2].first, dp[i - 1].second + dp[i - 2].second) } val bw = BufferedWriter(System.out.bufferedWriter()) var n:Int for (i in 1..T) { n = readLine().toInt() bw.write("${dp[n].first} ${dp[n].second}\n") } bw.flush() bw.close() }
0
Kotlin
0
0
1d863d3a9a0ced3a1c1e3c1aec934067b03e77bb
638
KotlinCodingTest
MIT License
compose/src/main/java/androidx/ui/layout/LayoutPaddingSample.kt
BlueLucky
280,043,017
true
{"Kotlin": 551590, "Shell": 5712, "HTML": 2737}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.ui.layout.samples import androidx.annotation.Sampled import androidx.compose.Composable import androidx.ui.core.Modifier import androidx.ui.foundation.Box import androidx.ui.foundation.drawBackground import androidx.ui.graphics.Color import androidx.ui.layout.InnerPadding import androidx.ui.layout.Stack import androidx.ui.layout.absolutePadding import androidx.ui.layout.padding import androidx.ui.layout.preferredSize import androidx.ui.unit.dp @Sampled @Composable fun PaddingModifier() { Stack(Modifier.drawBackground(Color.Gray)) { Box( Modifier.padding(start = 20.dp, top = 30.dp, end = 20.dp, bottom = 30.dp) .preferredSize(50.dp), backgroundColor = Color.Blue ) } } @Sampled @Composable fun SymmetricPaddingModifier() { Stack(Modifier.drawBackground(Color.Gray)) { Box( Modifier.padding(horizontal = 20.dp, vertical = 30.dp).preferredSize(50.dp), backgroundColor = Color.Blue ) } } @Sampled @Composable fun PaddingAllModifier() { Stack(Modifier.drawBackground(Color.Gray)) { Box(Modifier.padding(all = 20.dp).preferredSize(50.dp), backgroundColor = Color.Blue) } } @Sampled @Composable fun PaddingInnerPaddingModifier() { val innerPadding = InnerPadding(top = 10.dp, start = 15.dp) Stack(Modifier.drawBackground(Color.Gray)) { Box(Modifier.padding(innerPadding).preferredSize(50.dp), backgroundColor = Color.Blue) } } @Sampled @Composable fun AbsolutePaddingModifier() { Stack(Modifier.drawBackground(Color.Gray)) { Box( Modifier.absolutePadding(left = 20.dp, top = 30.dp, right = 20.dp, bottom = 30.dp) .preferredSize(50.dp), backgroundColor = Color.Blue ) } }
0
null
0
0
899594173c878590dccc4cda25c64c5c53aeb27f
2,422
Jetpack-Compose-Playground
MIT License
app/src/main/java/com/ojhdtapp/parabox/ui/guide/GuidePageViewModel.kt
Parabox-App
482,740,446
false
null
package com.ojhdtapp.parabox.ui.guide import android.content.Context import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject @HiltViewModel class GuidePageViewModel @Inject constructor( @ApplicationContext val context: Context): ViewModel() { }
0
null
5
98
044d9ed13bce54d28c8e95f344239f7ee8e6c451
366
Parabox
MIT License
lighthouse/src/main/java/com/ivanempire/lighthouse/models/packets/NotificationSubtype.kt
ivanempire
448,494,873
false
{"Kotlin": 139591}
package com.ivanempire.lighthouse.models.packets import java.util.Locale /** * Each SSDP packet has an NTS field which identifies its type. One exception is an M-SEARCH * response packet, which uses an ST field */ internal enum class NotificationSubtype(val rawString: String) { ALIVE("SSDP:ALIVE"), UPDATE("SSDP:UPDATE"), BYEBYE("SSDP:BYEBYE"); companion object { fun getByRawValue(rawValue: String?): NotificationSubtype? { return if (rawValue == null) { null } else { values().firstOrNull { it.rawString == rawValue.uppercase(Locale.getDefault()) } } } } }
0
Kotlin
3
19
b9ed2f7360514cb66d703af167f34e2f4f4b3596
671
lighthouse
Apache License 2.0
lib/src/main/kotlin/com/lemonappdev/konsist/core/util/EndOfLine.kt
LemonAppDev
621,181,534
false
{"Kotlin": 5054558, "Python": 46133}
package com.lemonappdev.konsist.core.util internal enum class EndOfLine( val value: String, ) { /** * Unix-style end-of-line marker (LF) */ UNIX("\n"), /** * Windows-style end-of-line marker (CRLF) */ WINDOWS("\r\n"), }
6
Kotlin
27
1,141
696b67799655e2154447ab45f748e983d8bcc1b5
262
konsist
Apache License 2.0
app/src/main/java/com/bsuir/bsuirschedule/domain/repository/SharedPrefsRepository.kt
Saydullin
526,953,048
false
null
package com.bsuir.bsuirschedule.domain.repository import android.content.Context interface SharedPrefsRepository { val context: Context fun isFirstTime(): Boolean fun setFirstTime(isFirst: Boolean) fun getActiveScheduleId(): Int fun isAutoUpdate(): Boolean fun getPrevVersion(): Int fun setPrevVersion(prevVersion: Int) fun setAutoUpdate(isAutoUpdate: Boolean) fun setActiveScheduleId(scheduleId: Int) fun getLanguage(): String? fun setLanguage(lang: String) fun getThemeType(): Int fun setTheme(themeType: Int) fun getScheduleUpdateCounter(): Int fun setScheduleUpdateCounter(counter: Int) fun getScheduleAutoUpdateDate(): String fun setScheduleAutoUpdateDate(autoUpdateDate: String) fun isNotificationsEnabled(): Boolean fun setNotificationsEnabled(isNotificationsEnabled: Boolean) fun getDefaultScheduleTitle(): String? fun setDefaultScheduleTitle(scheduleTitle: String) }
0
Kotlin
0
4
d818940f2ab942256048f942ec5b3498b939d78c
986
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
src/main/kotlin/us/timinc/mc/cobblemon/ivbooster/config/IvBoosterConfig.kt
timinc-cobble
676,400,916
false
null
package us.timinc.mc.cobblemon.ivbooster.config import draylar.omegaconfig.api.Comment import draylar.omegaconfig.api.Config import us.timinc.mc.cobblemon.ivbooster.IvBooster class IvBoosterConfig : Config { @Comment("The number of points each of these counter types grant") val koStreakPoints = 0 val koCountPoints = 0 val captureStreakPoints = 1 val captureCountPoints = 0 @Comment("The distance at which a spawning Pokemon considers a player") val effectiveRange = 64 @Comment("Thresholds for the KO counts : shiny chance bonus") val thresholds: Map<Int, Int> = mutableMapOf(Pair(5, 1), Pair(10, 2), Pair(20, 3), Pair(30, 4)) override fun getName(): String { return IvBooster.MOD_ID } }
0
Kotlin
0
0
57a78ba84d042a7fcb17b8b8070695da3204766a
746
cobblemon-ivbooster
MIT License
app/src/test/java/hu/mostoha/mobile/android/huki/ui/home/gpx/history/GpxHistoryViewModelTest.kt
RolandMostoha
386,949,428
false
{"Kotlin": 812945, "Java": 21937, "Shell": 308}
package hu.mostoha.mobile.android.huki.ui.home.gpx.history import android.net.Uri import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import hu.mostoha.mobile.android.huki.R import hu.mostoha.mobile.android.huki.logger.ExceptionLogger import hu.mostoha.mobile.android.huki.model.domain.GpxHistory import hu.mostoha.mobile.android.huki.model.domain.GpxHistoryItem import hu.mostoha.mobile.android.huki.model.domain.GpxType import hu.mostoha.mobile.android.huki.model.mapper.GpxHistoryUiModelMapper import hu.mostoha.mobile.android.huki.model.ui.GpxRenameResult import hu.mostoha.mobile.android.huki.model.ui.Message import hu.mostoha.mobile.android.huki.repository.LayersRepository import hu.mostoha.mobile.android.huki.util.MainCoroutineRule import hu.mostoha.mobile.android.huki.util.runTestDefault import io.mockk.coEvery import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import java.time.LocalDateTime @ExperimentalCoroutinesApi class GpxHistoryViewModelTest { private lateinit var viewModel: GpxHistoryViewModel private val exceptionLogger = mockk<ExceptionLogger>() private val layersRepository = mockk<LayersRepository>() @get:Rule val mainCoroutineRule = MainCoroutineRule() @Before fun setUp() { every { DEFAULT_GPX_FILE_URI.lastPathSegment } returns "dera_szurdok.gpx" coEvery { layersRepository.getGpxHistory() } returns GpxHistory( routePlannerGpxList = listOf( GpxHistoryItem( name = "dera_szurdok.gpx", fileUri = DEFAULT_GPX_FILE_URI, lastModified = LocalDateTime.of(2023, 6, 2, 16, 0), ) ), externalGpxList = emptyList() ) viewModel = GpxHistoryViewModel( exceptionLogger, layersRepository, GpxHistoryUiModelMapper(), mainCoroutineRule.testDispatcher, ) } @Test fun `When init, then gpx history file names return GPX file names without file extension`() { runTestDefault { viewModel.gpxHistoryFileNames.test { assertThat(awaitItem()).isEqualTo(emptyList<String>()) assertThat(awaitItem()).isEqualTo(listOf("dera_szurdok")) } } } @Test fun `Given a route planner GPX, when init, then route planner gpx history adapter items are emitted`() { runTestDefault { viewModel.gpxHistoryAdapterItems.test { assertThat(awaitItem()).isNull() assertThat(awaitItem()).isEqualTo(listOf(DEFAULT_ROUTE_PLANNER_GPX_HISTORY_ITEM)) } } } @Test fun `Given an external GPX, when init, then route planner gpx history adapter items are emitted`() { coEvery { layersRepository.getGpxHistory() } returns GpxHistory( routePlannerGpxList = emptyList(), externalGpxList = listOf( GpxHistoryItem( name = "dera_szurdok.gpx", fileUri = DEFAULT_GPX_FILE_URI, lastModified = LocalDateTime.of(2023, 6, 2, 16, 0), ) ), ) runTestDefault { viewModel.gpxHistoryAdapterItems.test { viewModel.tabSelected(GpxHistoryTab.EXTERNAL) assertThat(awaitItem()).isNull() assertThat(awaitItem()).isEqualTo( listOf( GpxHistoryAdapterModel.InfoView( message = R.string.gpx_history_item_route_planner_empty, iconRes = R.drawable.ic_gpx_history_empty ) ) ) assertThat(awaitItem()).isEqualTo(listOf(DEFAULT_EXTERNAL_GPX_HISTORY_ITEM)) } } } @Test fun `When select external tab, then empty external items are emitted`() { runTestDefault { viewModel.gpxHistoryAdapterItems.test { viewModel.tabSelected(GpxHistoryTab.EXTERNAL) assertThat(awaitItem()).isNull() assertThat(awaitItem()).isEqualTo(listOf(DEFAULT_ROUTE_PLANNER_GPX_HISTORY_ITEM)) assertThat(awaitItem()).isEqualTo( listOf( GpxHistoryAdapterModel.InfoView( message = R.string.gpx_history_item_external_empty, iconRes = R.drawable.ic_gpx_history_empty ) ) ) } } } @Test fun `Given error, when delete GPX, then error message is emitted`() { runTestDefault { coEvery { layersRepository.deleteGpx(any()) } throws Exception("Error") viewModel.errorMessage.test { viewModel.deleteGpx(DEFAULT_GPX_FILE_URI) assertThat(awaitItem()).isEqualTo(Message.Res(R.string.gpx_history_rename_operation_error)) } } } @Test fun `Given error, when rename GPX, then error message is emitted`() { runTestDefault { coEvery { layersRepository.renameGpx(any(), any()) } throws Exception("Error") viewModel.errorMessage.test { viewModel.renameGpx(GpxRenameResult(DEFAULT_GPX_FILE_URI, "new_name")) assertThat(awaitItem()).isEqualTo(Message.Res(R.string.gpx_history_rename_operation_error)) } } } companion object { private val DEFAULT_GPX_FILE_URI = mockk<Uri>() private val DEFAULT_ROUTE_PLANNER_GPX_HISTORY_ITEM = GpxHistoryAdapterModel.Item( name = "dera_szurdok.gpx", gpxType = GpxType.ROUTE_PLANNER, fileUri = DEFAULT_GPX_FILE_URI, dateText = Message.Res( R.string.gpx_history_item_route_planner_date_template, listOf("2023.06.02 16:00") ), ) private val DEFAULT_EXTERNAL_GPX_HISTORY_ITEM = GpxHistoryAdapterModel.Item( name = "dera_szurdok.gpx", gpxType = GpxType.EXTERNAL, fileUri = DEFAULT_GPX_FILE_URI, dateText = Message.Res( R.string.gpx_history_item_external_date_template, listOf("2023.06.02 16:00") ), ) } }
0
Kotlin
1
6
503376ed94263cdcf3e03b9ac5e42a7c163fdd73
6,508
HuKi-Android
The Unlicense
src/main/kotlin/com/github/versusfm/kotlinsql/adapter/types/ByteArrayAdapter.kt
versus-fm
720,887,840
false
{"Kotlin": 68668}
package com.github.versusfm.kotlinsql.adapter.types import com.github.jasync.sql.db.RowData import com.github.versusfm.kotlinsql.adapter.TypeAdapter class ByteArrayAdapter : TypeAdapter<Array<Byte>> { override fun type(): Class<Array<Byte>> { return Array<Byte>::class.java } override fun convert(columnName: String, rowData: RowData): Array<Byte>? { return rowData.getAs(columnName) } }
0
Kotlin
0
0
dfc10c6fbc4cabe572b064daa205cbd489aa1e5d
422
kotlin-query
MIT License
app/src/main/java/at/fhj/ims/privacylibdemo/viewmodel/RadioGroupDemoViewModel.kt
n81ur3
296,239,790
false
null
package at.fhj.ims.privacylibdemo.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class RadioGroupDemoViewModel : ViewModel() { private val _currentSelection = MutableLiveData<String>() val currentSelection: LiveData<String> get() = _currentSelection fun setSelection(selectedIndex: Int) { when (selectedIndex) { 0 -> _currentSelection.value = "Red" 1 -> _currentSelection.value = "Green" else -> _currentSelection.value = "Yellow" } } }
0
Kotlin
0
0
47dc7eeee95e3d632cca7ca247c2ca3d0e670500
592
PrivacyLib-Android
Apache License 2.0
src/main/kotlin/me/yunleah/plugin/coldexcavate/ColdExcavate.kt
Yunleah
670,438,586
false
null
package me.yunleah.plugin.coldexcavate import taboolib.common.platform.Plugin import taboolib.module.configuration.Config import taboolib.module.configuration.ConfigFile import taboolib.platform.BukkitPlugin object ColdExcavate : Plugin() { const val KEY = "§3Cold§bExcavate" val plugin by lazy { BukkitPlugin.getInstance() } @Config("setting.yml", true) lateinit var setting: ConfigFile }
0
Kotlin
0
1
03169f43596cde9fe5b5bce8e747b249e1d68575
409
ColdExcavate
Creative Commons Zero v1.0 Universal
StoryApp/app/src/main/java/com/wororn/storyapp/interfaces/map/MapViewModel.kt
wororn
669,360,664
false
null
package com.wororn.storyapp.interfaces.map import androidx.lifecycle.ViewModel import com.wororn.storyapp.componen.repository.StoriesRepository class MapViewModel (private val storiesRepository: StoriesRepository) : ViewModel() { fun getAllMapData(token: String,location:Int) = storiesRepository.getMapData(token,location) }
0
Kotlin
0
0
239714067c40b7bbe8aac2bc2ab2d1e6278cc001
331
android-intermediate-II
MIT License
app/src/main/java/com/lodz/android/agiledevkt/modules/contact/ContactTestActivity.kt
LZ9
137,967,291
false
{"Kotlin": 2174504}
package com.lodz.android.agiledevkt.modules.contact import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.DividerItemDecoration import com.lodz.android.agiledevkt.R import com.lodz.android.agiledevkt.databinding.ActivityContactTestBinding import com.lodz.android.agiledevkt.modules.main.MainActivity import com.lodz.android.corekt.anko.goAppDetailSetting import com.lodz.android.corekt.anko.isPermissionGranted import com.lodz.android.corekt.anko.toastShort import com.lodz.android.corekt.contacts.bean.ContactsInfoBean import com.lodz.android.pandora.mvvm.base.activity.BaseVmActivity import com.lodz.android.pandora.utils.viewbinding.bindingLayout import com.lodz.android.pandora.utils.viewmodel.bindViewModel import com.lodz.android.pandora.widget.rv.anko.linear import com.lodz.android.pandora.widget.rv.anko.setup import permissions.dispatcher.PermissionRequest import permissions.dispatcher.ktx.constructPermissionsRequest /** * 通讯录测试类 * @author zhouL * @date 2022/3/30 */ @SuppressLint("NotifyDataSetChanged") class ContactTestActivity : BaseVmActivity() { companion object { fun start(context: Context) { val intent = Intent(context, ContactTestActivity::class.java) context.startActivity(intent) } } private val mViewModel by bindViewModel { ContactViewModel() } override fun getViewModel(): ContactViewModel = mViewModel private val mBinding: ActivityContactTestBinding by bindingLayout(ActivityContactTestBinding::inflate) override fun getViewBindingLayout(): View = mBinding.root private val hasReadContactsPermissions by lazy { constructPermissionsRequest( Manifest.permission.READ_CONTACTS,// 通讯录 onShowRationale = ::onShowRationaleBeforeRequest, onPermissionDenied = ::onDenied, onNeverAskAgain = ::onNeverAskAgain, requiresPermission = ::onRequestPermission ) } private val hasWriteContactsPermissions by lazy { constructPermissionsRequest( Manifest.permission.WRITE_CONTACTS,// 通讯录 onShowRationale = ::onShowRationaleBeforeRequest, onPermissionDenied = ::onDenied, onNeverAskAgain = ::onNeverAskAgain, requiresPermission = ::onRequestPermission ) } /** 适配器 */ private lateinit var mAdapter: ContactAdapter override fun findViews(savedInstanceState: Bundle?) { getTitleBarLayout().setTitleName(intent.getStringExtra(MainActivity.EXTRA_TITLE_NAME) ?: "") initRecyclerView() } private fun initRecyclerView() { mAdapter = mBinding.contactRv.let { it.linear() it.addItemDecoration(DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL)) it.setup(ContactAdapter(getContext())) } } override fun onClickBackBtn() { super.onClickBackBtn() finish() } override fun onClickReload() { super.onClickReload() showStatusLoading() mViewModel.getAllContactData(getContext()) } override fun setListeners() { super.setListeners() mBinding.deleteAllContactBtn.setOnClickListener { showDeleteAllDialog() } mBinding.addContactBtn.setOnClickListener { mViewModel.addContactData(getContext()) } mAdapter.setOnDeleteClickListener { viewHolder, item -> showDeleteDialog(item) } mAdapter.setOnUpdateNoteClickListener { viewHolder, item -> item.noteBean.note = "测试" mViewModel.updateContactData(getContext(), item.noteBean) } } /** 显示删除所有通讯录弹框 */ private fun showDeleteAllDialog() { AlertDialog.Builder(getContext()) .setMessage(R.string.contact_delete_all_confirm) .setPositiveButton(R.string.contact_delete_ok) { dif, witch -> dif.dismiss() mViewModel.deleteAllContact(getContext()) } .setNegativeButton(R.string.contact_delete_cancel) { dif, witch -> dif.dismiss() } .create() .show() } /** 显示删除弹框 */ private fun showDeleteDialog(bean: ContactsInfoBean) { AlertDialog.Builder(getContext()) .setMessage(R.string.contact_delete_confirm) .setPositiveButton(R.string.contact_delete_ok) { dif, witch -> dif.dismiss() mViewModel.deleteContact(getContext(), bean) } .setNegativeButton(R.string.contact_delete_cancel) { dif, witch -> dif.dismiss() } .create() .show() } override fun setViewModelObserves() { super.setViewModelObserves() mViewModel.mContactList.observe(getLifecycleOwner()){ mAdapter.setData(it) mAdapter.notifyDataSetChanged() } } private fun init() { showStatusCompleted() mViewModel.getAllContactData(getContext()) } override fun initData() { super.initData() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0以上的手机对权限进行动态申请 onRequestPermission()//申请权限 } else { init() } } /** 权限申请成功 */ private fun onRequestPermission() { if (!isPermissionGranted(Manifest.permission.READ_CONTACTS)) { hasReadContactsPermissions.launch() return } if (!isPermissionGranted(Manifest.permission.WRITE_CONTACTS)) { hasWriteContactsPermissions.launch() return } init() } /** 用户拒绝后再次申请前告知用户为什么需要该权限 */ private fun onShowRationaleBeforeRequest(request: PermissionRequest) { request.proceed()//请求权限 } /** 被拒绝 */ private fun onDenied() { onRequestPermission()//申请权限 } /** 被拒绝并且勾选了不再提醒 */ private fun onNeverAskAgain() { toastShort(R.string.splash_check_permission_tips) goAppDetailSetting() showStatusError() } }
0
Kotlin
3
11
926b9f968a984c42ade94371714ef4caf3ffbccf
6,310
AgileDevKt
Apache License 2.0
src/main/kotlin/com/gaelmarhic/quadrant/models/generation/FileToBeGenerated.kt
gaelmarhic
234,946,737
false
{"Kotlin": 184003}
package com.gaelmarhic.quadrant.models.generation data class FileToBeGenerated( val name: String, val constantList: List<ConstantToBeGenerated> )
0
Kotlin
13
211
de8a13cc3b9bc5ff445afdc8a7c7f6cc1a317cc6
155
Quadrant
Apache License 2.0
paymentsheet/src/main/java/com/stripe/android/paymentsheet/model/GooglePayButtonType.kt
stripe
6,926,049
false
{"Kotlin": 10352685, "Java": 71963, "Ruby": 24683, "Shell": 20001, "Python": 13941, "HTML": 7519}
package com.stripe.android.paymentsheet.model import com.google.android.gms.wallet.button.ButtonConstants internal enum class GooglePayButtonType(val value: Int) { Buy(ButtonConstants.ButtonType.BUY), Book(ButtonConstants.ButtonType.BOOK), Checkout(ButtonConstants.ButtonType.CHECKOUT), Donate(ButtonConstants.ButtonType.DONATE), Order(ButtonConstants.ButtonType.ORDER), Pay(ButtonConstants.ButtonType.PAY), Subscribe(ButtonConstants.ButtonType.SUBSCRIBE), Plain(ButtonConstants.ButtonType.PLAIN) }
116
Kotlin
630
1,179
d49aba6f78e7c3d37b957e2d5307ab5d41070172
533
stripe-android
MIT License
project/kimmer/src/test/kotlin/org/babyfish/kimmer/model/BookStore.kt
babyfish-ct
447,936,858
false
{"Kotlin": 967243}
package org.babyfish.kimmer.model import java.math.BigDecimal interface BookStore: Node { val name: String val books: List<Book> val avgPrice: BigDecimal }
0
Kotlin
3
37
8345d9112292b7f13aaccae681bc91cb51fa9315
170
kimmer
MIT License
engrave/src/main/java/com/angcyo/engrave/EngraveFlowLayoutHelper.kt
angcyo
229,037,684
false
null
package com.angcyo.engrave import com.angcyo.bluetooth.fsc.enqueue import com.angcyo.bluetooth.fsc.laserpacker.HawkEngraveKeys import com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerHelper import com.angcyo.bluetooth.fsc.laserpacker.command.EngraveCmd import com.angcyo.bluetooth.fsc.laserpacker.command.ExitCmd import com.angcyo.bluetooth.fsc.laserpacker.writeBleLog import com.angcyo.canvas.items.data.DataItemRenderer import com.angcyo.canvas.items.renderer.IItemRenderer import com.angcyo.core.component.file.writeToLog import com.angcyo.core.showIn import com.angcyo.core.tgStrokeLoadingCaller import com.angcyo.core.vmApp import com.angcyo.dialog.inputDialog import com.angcyo.dialog.messageDialog import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.dsladapter.find import com.angcyo.engrave.data.TransferState import com.angcyo.engrave.dslitem.EngraveDividerItem import com.angcyo.engrave.dslitem.EngraveSegmentScrollItem import com.angcyo.engrave.dslitem.engrave.* import com.angcyo.engrave.dslitem.preview.PreviewExDeviceTipItem import com.angcyo.engrave.dslitem.preview.PreviewTipItem import com.angcyo.engrave.dslitem.transfer.DataStopTransferItem import com.angcyo.engrave.dslitem.transfer.DataTransmittingItem import com.angcyo.engrave.dslitem.transfer.TransferDataNameItem import com.angcyo.engrave.dslitem.transfer.TransferDataPxItem import com.angcyo.engrave.model.EngraveModel import com.angcyo.engrave.model.TransferModel import com.angcyo.engrave.transition.EngraveTransitionManager import com.angcyo.item.DslBlackButtonItem import com.angcyo.item.form.checkItemThrowable import com.angcyo.item.style.itemCurrentIndex import com.angcyo.item.style.itemLabelText import com.angcyo.laserpacker.LPDataConstant import com.angcyo.laserpacker.device.* import com.angcyo.library.L import com.angcyo.library.component.pad.isInPadMode import com.angcyo.library.ex.* import com.angcyo.library.toast import com.angcyo.library.toastQQ import com.angcyo.objectbox.laser.pecker.entity.EngraveConfigEntity import com.angcyo.objectbox.laser.pecker.entity.MaterialEntity import com.angcyo.objectbox.laser.pecker.lpSaveEntity import com.angcyo.viewmodel.observe import com.angcyo.widget.span.span import kotlin.math.max /** * 雕刻布局相关操作 * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022/05/30 */ open class EngraveFlowLayoutHelper : BasePreviewLayoutHelper() { //数据传输模式 val transferModel = vmApp<TransferModel>() override fun renderFlowItems() { if (isAttach()) { when (engraveFlow) { ENGRAVE_FLOW_ITEM_CONFIG -> renderEngraveItemParamsConfig() ENGRAVE_FLOW_TRANSFER_BEFORE_CONFIG -> renderTransferConfig() ENGRAVE_FLOW_AUTO_TRANSFER -> renderAutoTransfer() ENGRAVE_FLOW_TRANSMITTING -> renderTransmitting() ENGRAVE_FLOW_BEFORE_CONFIG -> renderEngraveConfig() ENGRAVE_FLOW_ENGRAVING -> renderEngraving() ENGRAVE_FLOW_FINISH -> renderEngraveFinish() else -> super.renderFlowItems() } } } override fun bindDeviceState() { super.bindDeviceState() // transferModel.transferStateOnceData.observe(this, allowBackward = false) { it?.apply { //数据传输进度通知 if (it.error == null && it.state == TransferState.TRANSFER_STATE_FINISH) { //默认选中第1个雕刻图层 selectLayerMode = EngraveFlowDataHelper.getEngraveLayerList(taskId).firstOrNull()?.layerMode ?: 0 } if (engraveFlow == ENGRAVE_FLOW_TRANSMITTING) { //在[renderTransmitting] 中 engraveFlow = ENGRAVE_FLOW_BEFORE_CONFIG renderFlowItems() } } } // engraveModel.engraveStateData.observe(this, allowBackward = false) { it?.apply { "雕刻状态改变,当前流程id[$flowTaskId]:$this".writeBleLog() if (taskId == flowTaskId) { val engraveCmdError = engraveModel._lastEngraveCmdError if (it.state == EngraveModel.ENGRAVE_STATE_ERROR && engraveCmdError != null) { toastQQ(engraveCmdError.message) engraveFlow = ENGRAVE_FLOW_BEFORE_CONFIG renderFlowItems() } else if (engraveFlow == ENGRAVE_FLOW_ENGRAVING) { when (it.state) { EngraveModel.ENGRAVE_STATE_FINISH -> { //雕刻完成 engraveFlow = ENGRAVE_FLOW_FINISH renderFlowItems() } EngraveModel.ENGRAVE_STATE_INDEX_FINISH -> { //当前索引雕刻完成, 传输下一个文件 startTransferNext() } else -> { renderFlowItems() } } } } } } } // /**当前选中的图层模式 * [EngraveLayerConfigItem]*/ var selectLayerMode: Int = 0 override fun onEngraveFlowChanged(from: Int, to: Int) { super.onEngraveFlowChanged(from, to) if (to == ENGRAVE_FLOW_TRANSFER_BEFORE_CONFIG) { //在开始传输数据的时候, 创建任务 /*if (flowTaskId != null) { //再次传输不一样的数据时, 重新创建任务id flowTaskId = EngraveFlowDataHelper.generateTaskId(flowTaskId) }*/ } else if (to == ENGRAVE_FLOW_BEFORE_CONFIG) { //no op } } /**回调*/ var onStartEngraveAction: (taskId: String?) -> Unit = {} /**开始雕刻前回调*/ open fun onStartEngrave(taskId: String?) { onStartEngraveAction(taskId) } /**回调*/ var onStartEngraveTransferDataAction: (taskId: String?) -> Unit = {} /**开始传输数据的回调*/ open fun onStartEngraveTransferData(taskId: String?) { onStartEngraveTransferDataAction(taskId) } //region ---数据配置--- /**渲染传输数据配置界面*/ fun renderTransferConfig() { updateIViewTitle(_string(R.string.file_setting)) engraveBackFlow = ENGRAVE_FLOW_PREVIEW showCloseView(true, _string(R.string.ui_back)) val transferConfigEntity = EngraveFlowDataHelper.generateTransferConfig( flowTaskId,//此时的flowTaskId可以为空 engraveCanvasFragment?.canvasDelegate ) //全部是GCode数据, 不能选择分辨率, 并且强制使用1k val isAllGCode = EngraveTransitionManager.isAllSameLayerMode( engraveCanvasFragment?.canvasDelegate, LPDataConstant.DATA_MODE_GCODE ) renderDslAdapter { TransferDataNameItem()() { itemTransferConfigEntity = transferConfigEntity observeItemChange { clearFlowId() engraveCanvasFragment?.canvasDelegate?.changedRenderItemData() } } if (!isAllGCode) { //并非全部是GCode数据 TransferDataPxItem()() { itemPxList = if ((laserPeckerModel.isL3() || laserPeckerModel.isC1()) && laserPeckerModel.deviceSettingData.value?.zFlag == 1 ) { //L3 C1 z轴打开的情况下, 取消4k 2023-1-4 / 2023-3-10 LaserPeckerHelper.findProductSupportPxList() .filter { it.px != LaserPeckerHelper.PX_4K } } else { LaserPeckerHelper.findProductSupportPxList() } itemTransferConfigEntity = transferConfigEntity observeItemChange { clearFlowId() engraveCanvasFragment?.canvasDelegate?.changedRenderItemData() } } EngraveDividerItem()() } DslBlackButtonItem()() { itemButtonText = _string(R.string.send_file) itemClick = { if (!checkItemThrowable() && !checkOverflowBounds() && checkTransferData()) { //下一步, 数据传输界面 //退出打印模式, 进入空闲模式 engraveCanvasFragment?.fragment?.engraveLoadingAsyncTimeout({ syncSingle { countDownLatch -> ExitCmd().enqueue { bean, error -> countDownLatch.countDown() if (error == null) { engraveBackFlow = ENGRAVE_FLOW_TRANSFER_BEFORE_CONFIG engraveFlow = ENGRAVE_FLOW_TRANSMITTING val canvasDelegate = engraveCanvasFragment?.canvasDelegate if (canvasDelegate == null) { //不是画布上的数据, 可能是恢复的数据 } else { HawkEngraveKeys.lastDpi = transferConfigEntity.dpi val flowId = generateFlowId()//每次发送数据之前, 都生成一个新的任务 transferConfigEntity.taskId = flowId transferConfigEntity.lpSaveEntity() onStartEngraveTransferData(flowId) transferModel.startCreateTransferData( flowId, canvasDelegate ) } //last renderFlowItems() } else { toastQQ(error.message) } } } }) } } } } } //endregion ---数据配置--- //region ---数据传输中--- /**开始传输下一个*/ fun startTransferNext() { engraveFlow = ENGRAVE_FLOW_TRANSMITTING transferModel.startTransferNextData(flowTaskId) //last renderFlowItems() } /**开始雕刻下一个*/ fun startEngraveNext() { engraveFlow = ENGRAVE_FLOW_ENGRAVING engraveModel.startEngraveNext(flowTaskId) renderFlowItems() } /**开始自动传输数据*/ fun renderAutoTransfer() { val flowId = flowTaskId onStartEngraveTransferData(flowId) transferModel.startTransferData(flowId) //last engraveFlow = ENGRAVE_FLOW_TRANSMITTING renderFlowItems() } /**渲染传输中的界面 * 通过传输状态改变实时刷新界面 * [com.angcyo.engrave.model.TransferModel.transferStateOnceData] * [com.angcyo.engrave.EngraveFlowLayoutHelper.bindDeviceState] * */ fun renderTransmitting() { updateIViewTitle(_string(R.string.transmitting)) showCloseView(false) val taskStateData = transferModel.transferStateOnceData.value if (taskStateData?.error == null && taskStateData?.state == TransferState.TRANSFER_STATE_FINISH) { //文件传输完成 if (engraveModel._engraveTaskEntity?.state == EngraveModel.ENGRAVE_STATE_INDEX_FINISH) { startEngraveNext() } else { engraveFlow = ENGRAVE_FLOW_BEFORE_CONFIG renderFlowItems() } } else { renderDslAdapter { DataTransmittingItem()() { itemProgress = taskStateData?.progress ?: 0 } if (isDebug()) { val monitorEntity = EngraveFlowDataHelper.getTransferMonitor(flowTaskId) if (monitorEntity != null) { PreviewTipItem()() { itemTip = span { if (monitorEntity.dataMakeStartTime > 0) { if (monitorEntity.dataMakeFinishTime > 0) { append("生成耗时:${monitorEntity.dataMakeDuration()} ") } else { append("数据生成中... ") } } if (monitorEntity.dataTransferSize > 0) { append(" 大小:${monitorEntity.dataSize()} ") } if (monitorEntity.dataTransferStartTime > 0) { appendln() append("传输耗时:") if (monitorEntity.dataTransferFinishTime > 0) { append("${monitorEntity.dataTransferDuration()} ") } else { append("${monitorEntity.dataTransferDuration(nowTime())} ") } if (monitorEntity.dataTransferSpeed > 0) { append(" 速率:${monitorEntity.speedString()} :${monitorEntity.maxSpeedString()}") } else { append(" 传输中... ") } } } } } } DataStopTransferItem()() { itemException = taskStateData?.error itemClick = { transferModel.stopTransfer() //强制退出 engraveCanvasFragment?.fragment?.tgStrokeLoadingCaller { isCancel, loadEnd -> ExitCmd().enqueue { bean, error -> loadEnd(bean, error) if (error != null) { toastQQ(error.message) } else { engraveFlow = ENGRAVE_FLOW_TRANSFER_BEFORE_CONFIG renderFlowItems() } } } } } } } } //endregion ---数据传输中--- //region ---雕刻参数配置--- /**开始单个元素雕刻参数配置*/ fun startEngraveItemConfig( engraveFragment: IEngraveCanvasFragment, itemRenderer: IItemRenderer<*>? ) { if (isAttach() && engraveFlow > ENGRAVE_FLOW_ITEM_CONFIG) { //已经在显示其他流程 return } if (deviceStateModel.deviceStateData.value?.isModeIdle() != true) { //设备非空闲 return } if (itemRenderer == null) { //选中空item hide() return } if (itemRenderer is DataItemRenderer) { _engraveItemRenderer = itemRenderer engraveFlow = ENGRAVE_FLOW_ITEM_CONFIG showIn(engraveFragment.fragment, engraveFragment.flowLayoutContainer) } } /**单元素雕刻参数配置界面, 只能配置参数, 无法next*/ fun renderEngraveItemParamsConfig() { updateIViewTitle(_string(R.string.print_setting)) showCloseView(false) cancelable = true var engraveConfigEntity: EngraveConfigEntity? = null val projectItemBean = _engraveItemRenderer?.rendererItem?.dataBean projectItemBean?.apply { printPower = printPower ?: HawkEngraveKeys.lastPower printDepth = printDepth ?: HawkEngraveKeys.lastDepth printPrecision = printPrecision ?: HawkEngraveKeys.lastPrecision printType = printType ?: DeviceHelper.getProductLaserType().toInt() printCount = printCount ?: 1 materialKey = materialKey ?: MaterialHelper.createCustomMaterial().key //雕刻配置 engraveConfigEntity = EngraveFlowDataHelper.generateEngraveConfig("$index", projectItemBean) } renderDslAdapter { //材质选择 EngraveMaterialWheelItem()() { itemTag = MaterialEntity::name.name itemLabelText = _string(R.string.custom_material) itemWheelList = MaterialHelper.unionMaterialList itemSelectedIndex = MaterialHelper.indexOfMaterial( MaterialHelper.unionMaterialList, projectItemBean?.materialKey, projectItemBean?.printType, ) itemEngraveItemBean = projectItemBean itemEngraveConfigEntity = engraveConfigEntity itemDeleteAction = { key -> showDeleteMaterialDialog(flowTaskId, key) { renderFlowItems() } } //刷新界面 observeItemChange { renderFlowItems() } observeEngraveParamsChange() } // 激光光源选择 val typeList = LaserPeckerHelper.findProductSupportLaserTypeList() if (laserPeckerModel.productInfoData.value?.isCI() != true && typeList.isNotEmpty()) { EngraveSegmentScrollItem()() { itemText = _string(R.string.laser_type) itemSegmentList = typeList itemCurrentIndex = typeList.indexOfFirst { it.type == DeviceHelper.getProductLaserType() } observeItemChange { val type = typeList[itemCurrentIndex].type projectItemBean?.printType = type.toInt() HawkEngraveKeys.lastType = type.toInt() engraveConfigEntity?.type = type engraveConfigEntity.lpSaveEntity() renderFlowItems() } observeEngraveParamsChange() } } if (laserPeckerModel.isC1()) { //C1 加速级别选择 EngraveOptionWheelItem()() { itemTag = EngraveConfigEntity::precision.name itemLabelText = _string(R.string.engrave_precision) itemWheelList = EngraveHelper.percentList(5) itemSelectedIndex = EngraveHelper.findOptionIndex( itemWheelList, projectItemBean?.printPrecision ) itemEngraveConfigEntity = engraveConfigEntity itemEngraveItemBean = projectItemBean observeEngraveParamsChange() } } //雕刻参数 if (deviceStateModel.isPenMode()) { //雕刻速度, 非雕刻深度 EngraveOptionWheelItem()() { itemTag = MaterialEntity.SPEED itemLabelText = _string(R.string.engrave_speed) itemWheelList = EngraveHelper.percentList() itemEngraveItemBean = projectItemBean itemEngraveConfigEntity = engraveConfigEntity itemSelectedIndex = EngraveHelper.findOptionIndex( itemWheelList, EngraveCmd.depthToSpeed( projectItemBean?.printDepth ?: HawkEngraveKeys.lastDepth ) ) observeEngraveParamsChange() } } else { //功率/深度/次数 EngravePropertyItem()() { itemEngraveItemBean = projectItemBean itemEngraveConfigEntity = engraveConfigEntity observeEngraveParamsChange() } } } } /**渲染雕刻配置界面*/ fun renderEngraveConfig() { updateIViewTitle(_string(R.string.print_setting)) engraveBackFlow = ENGRAVE_FLOW_PREVIEW showCloseView(true, _string(R.string.ui_back)) val taskId = flowTaskId val layerList = EngraveFlowDataHelper.getEngraveLayerList(taskId) val findLayer = layerList.find { it.layerMode == selectLayerMode } if (findLayer == null) { //选中的图层不存在, 则使用第一个 selectLayerMode = layerList.firstOrNull()?.layerMode ?: selectLayerMode } //默认选中材质 var materialEntity = EngraveFlowDataHelper.findTaskMaterial(taskId) "材质:${taskId} $materialEntity".writeToLog(logLevel = L.WARN) //雕刻配置信息 val engraveConfigEntity = if (materialEntity == null) { //未初始化材质信息, 默认使用第一个 val lastMaterial = EngraveFlowDataHelper.findLastMaterial() materialEntity = if (lastMaterial != null && MaterialHelper.materialList.find { it.key == lastMaterial.key } != null) { //上一次设备推荐的材质, 在列表中 lastMaterial } else { //使用列表中第一个 MaterialHelper.materialList.firstOrNull() ?: MaterialHelper.createCustomMaterial() } EngraveFlowDataHelper.generateEngraveConfigByMaterial( taskId, materialEntity.key, materialEntity ).find { it.layerMode == selectLayerMode } ?: EngraveFlowDataHelper.generateEngraveConfig(taskId, selectLayerMode) } else { EngraveFlowDataHelper.generateEngraveConfig(taskId, selectLayerMode) } renderDslAdapter { PreviewTipItem()() { itemTip = _string(R.string.engrave_tip) } if (!laserPeckerModel.isC1()) { //非C1显示, 设备水平角度 renderDeviceInfoIfNeed() } if (deviceStateModel.needShowExDeviceTipItem()) { PreviewExDeviceTipItem()() } //雕刻相关的参数 if (HawkEngraveKeys.enableItemEngraveParams) { //参数配置提示 PreviewTipItem()() { itemTip = _string(R.string.engrave_item_params_tip) itemTipTextColor = _color(R.color.error) } } else { //材质选择 EngraveMaterialWheelItem()() { itemTag = MaterialEntity::name.name itemLabelText = _string(R.string.custom_material) itemWheelList = MaterialHelper.unionMaterialList itemSelectedIndex = MaterialHelper.indexOfMaterial( MaterialHelper.unionMaterialList, materialEntity ) itemEngraveConfigEntity = engraveConfigEntity itemSaveAction = { showSaveMaterialDialog(taskId, materialEntity) { //刷新界面, 使用自定义的材质信息 renderFlowItems() } } itemDeleteAction = { key -> showDeleteMaterialDialog(taskId, key) { renderFlowItems() } } //刷新界面 observeItemChange { renderFlowItems() } } //雕刻图层切换 if (layerList.isNotEmpty()) { EngraveLayerConfigItem()() { itemSegmentList = layerList itemCurrentIndex = max( 0, layerList.indexOf(layerList.find { it.layerMode == selectLayerMode }) ) observeItemChange { selectLayerMode = layerList[itemCurrentIndex].layerMode renderFlowItems() } } } // 激光光源选择 val typeList = LaserPeckerHelper.findProductSupportLaserTypeList() if (laserPeckerModel.productInfoData.value?.isCI() != true && typeList.isNotEmpty()) { EngraveSegmentScrollItem()() { itemText = _string(R.string.laser_type) itemSegmentList = typeList itemCurrentIndex = typeList.indexOfFirst { it.type == engraveConfigEntity.type } observeItemChange { val type = typeList[itemCurrentIndex].type HawkEngraveKeys.lastType = type.toInt() engraveConfigEntity.type = type engraveConfigEntity.lpSaveEntity() renderFlowItems() } observeMaterialChange() } } if (laserPeckerModel.isC1()) { //C1 加速级别选择 EngraveOptionWheelItem()() { itemTag = EngraveConfigEntity::precision.name itemLabelText = _string(R.string.engrave_precision) itemWheelList = EngraveHelper.percentList(5) itemSelectedIndex = EngraveHelper.findOptionIndex( itemWheelList, engraveConfigEntity.precision ) itemEngraveConfigEntity = engraveConfigEntity observeMaterialChange() } } //雕刻参数 if (deviceStateModel.isPenMode()) { //握笔模块, 雕刻速度, 非雕刻深度 engraveConfigEntity.power = 100 //功率必须100% engraveConfigEntity.lpSaveEntity() EngraveOptionWheelItem()() { itemTag = MaterialEntity.SPEED itemLabelText = _string(R.string.engrave_speed) itemWheelList = EngraveHelper.percentList() itemEngraveConfigEntity = engraveConfigEntity itemSelectedIndex = EngraveHelper.findOptionIndex( itemWheelList, EngraveCmd.depthToSpeed(engraveConfigEntity.depth) ) observeMaterialChange() } } else { //功率/深度/次数 EngravePropertyItem()() { itemEngraveConfigEntity = engraveConfigEntity observeMaterialChange() } } /*EngraveOptionWheelItem()() { itemTag = MaterialEntity::power.name itemLabelText = _string(R.string.custom_power) itemWheelList = percentList() itemEngraveConfigEntity = engraveConfigEntity itemSelectedIndex = EngraveHelper.findOptionIndex(itemWheelList, engraveConfigEntity.power) } EngraveOptionWheelItem()() { itemTag = MaterialEntity::depth.name itemLabelText = _string(R.string.custom_speed) itemWheelList = percentList() itemEngraveConfigEntity = engraveConfigEntity itemSelectedIndex = EngraveHelper.findOptionIndex(itemWheelList, engraveConfigEntity.depth) } //次数 EngraveOptionWheelItem()() { itemLabelText = _string(R.string.print_times) itemWheelList = percentList(255) itemTag = EngraveConfigEntity::time.name itemEngraveConfigEntity = engraveConfigEntity itemSelectedIndex = EngraveHelper.findOptionIndex(itemWheelList, engraveConfigEntity.time) }*/ } EngraveConfirmItem()() { itemClick = { //开始雕刻 checkEngraveNotify { checkExDevice { showFocalDistance(it.context) { showSafetyTips(it.context) { engraveCanvasFragment?.fragment?.engraveLoadingAsyncTimeout({ syncSingle { countDownLatch -> ExitCmd().enqueue { bean, error -> countDownLatch.countDown() if (error == null) { //开始雕刻 if (HawkEngraveKeys.enableItemEngraveParams) { EngraveFlowDataHelper.generateEngraveConfig( engraveCanvasFragment?.canvasDelegate ) } onStartEngrave(taskId) val taskEntity = engraveModel.startEngrave(taskId) if (taskEntity.dataIndexList.isNullOrEmpty()) { toastQQ(_string(R.string.no_data_engrave)) } else { engraveFlow = ENGRAVE_FLOW_ENGRAVING renderFlowItems() } } else { toastQQ(error.message) } } } }) } } } } } } } } /**监听改变之后, 显示材质保存按钮*/ fun DslAdapterItem.observeMaterialChange() { observeItemChange { itemDslAdapter?.find<EngraveMaterialWheelItem>()?.let { it.itemShowSaveButton = true it.updateAdapterItem() } } } /**回调*/ var onEngraveParamsChangeAction: () -> Unit = {} /**监听改变之后, 单文件雕刻参数*/ fun DslAdapterItem.observeEngraveParamsChange() { observeItemChange { onEngraveParamsChangeAction() } } /**显示保存自定义材质的对话框*/ fun showSaveMaterialDialog(taskId: String?, materialEntity: MaterialEntity, action: Action) { engraveCanvasFragment?.fragment?.fContext()?.inputDialog { dialogTitle = _string(R.string.save_material_title) hintInputString = _string(R.string.material_title_limit) maxInputLength = 20 canInputEmpty = false defaultInputString = materialEntity.toText() ?: _string(R.string.custom) onInputResult = { dialog, inputText -> EngraveFlowDataHelper.saveEngraveConfigToMaterial(taskId, "$inputText") action.invoke() false } } } /**显示删除自定义材质的对话框*/ fun showDeleteMaterialDialog(taskId: String?, materialKey: String, action: Action) { engraveCanvasFragment?.fragment?.fContext()?.messageDialog { dialogTitle = _string(R.string.engrave_warn) dialogMessage = _string(R.string.delete_material_tip) needPositiveButton { dialog, dialogViewHolder -> dialog.dismiss() EngraveFlowDataHelper.deleteMaterial(taskId, materialKey) action() } } } //endregion ---雕刻参数配置--- //region ---雕刻中--- /**渲染雕刻中的界面 * 通过设备状态改变实时刷新界面 * [com.angcyo.engrave.model.EngraveModel.engraveStateData] * * [com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerModel.deviceStateData] * * [com.angcyo.engrave.BaseFlowLayoutHelper.bindDeviceState] * */ fun renderEngraving() { updateIViewTitle(_string(R.string.engraving)) if (HawkEngraveKeys.enableBackEngrave) { engraveBackFlow = 0 showCloseView(true, _string(R.string.back_creation)) } else { engraveBackFlow = ENGRAVE_FLOW_BEFORE_CONFIG showCloseView(false) } renderDslAdapter { PreviewTipItem()() { itemTip = _string(R.string.engrave_move_state_tips) } if (!laserPeckerModel.isC1()) { //非C1显示, 设备水平角度 renderDeviceInfoIfNeed() } //强制显示模块信息 PreviewExDeviceTipItem()() { itemEngraveConfigEntity = EngraveFlowDataHelper.getCurrentEngraveConfig(flowTaskId) } EngraveProgressItem()() { itemTaskId = flowTaskId } EngravingInfoItem()() { itemTaskId = flowTaskId } if (HawkEngraveKeys.enableSingleItemTransfer) { //激活单文件雕刻的情况下, 允许跳过当前雕刻的索引 DslBlackButtonItem()() { itemButtonText = _string(R.string.engrave_skip_current) itemClick = { //强制退出 engraveCanvasFragment?.fragment?.tgStrokeLoadingCaller { isCancel, loadEnd -> ExitCmd().enqueue { bean, error -> loadEnd(bean, error) if (error != null) { toastQQ(error.message) } else { engraveModel.finishCurrentIndexEngrave() } } } } } } //---雕刻控制-暂停-结束 EngravingControlItem()() { itemTaskId = flowTaskId itemPauseAction = { isPause -> if (isPause) { engraveModel.continueEngrave() } else { engraveModel.pauseEngrave() } } itemStopAction = { //停止雕刻, 直接完成 engraveModel.stopEngrave("来自点击按钮") } } } } //endregion ---雕刻中--- //region ---雕刻完成--- /**渲染雕刻完成的界面*/ open fun renderEngraveFinish() { updateIViewTitle(_string(R.string.engrave_finish)) engraveBackFlow = 0 if (isInPadMode()) { showCloseView(true, _string(R.string.ui_quit)) } else { showCloseView(true, _string(R.string.back_creation)) } val taskId = flowTaskId renderDslAdapter { EngraveFinishTopItem()() { itemTaskId = taskId } // if (!HawkEngraveKeys.enableItemEngraveParams) { EngraveFlowDataHelper.getEngraveLayerList(taskId).forEach { engraveLayerInfo -> EngraveLabelItem()() { itemText = engraveLayerInfo.label } EngraveFinishInfoItem()() { itemTaskId = taskId itemLayerMode = engraveLayerInfo.layerMode } } } // EngraveFinishControlItem()() { itemShareAction = { toast("功能开发中...") } itemAgainAction = { //再次雕刻, 回退到参数配置页面 EngraveFlowDataHelper.againEngrave(taskId) //清除缓存状态数据 engraveFlow = ENGRAVE_FLOW_BEFORE_CONFIG renderFlowItems() } } } } //endregion ---雕刻完成--- }
0
Kotlin
4
3
13dc66c06abd72995fb8393655bb69544c259248
37,011
UICoreEx
MIT License
typescript/ts-nodes/src/org/jetbrains/dukat/ast/model/nodes/ModuleNode.kt
vipyami
270,574,458
true
{"Kotlin": 2584052, "WebIDL": 317874, "TypeScript": 125096, "JavaScript": 15185, "ANTLR": 11333}
package org.jetbrains.dukat.ast.model.nodes import org.jetbrains.dukat.ast.model.TopLevelNode import org.jetbrains.dukat.astCommon.NameEntity data class ModuleNode( val moduleName: NameEntity?, val export: ExportAssignmentNode?, val packageName: NameEntity, var qualifiedPackageName: NameEntity, val declarations: List<TopLevelNode> = emptyList(), val imports: Map<String, ImportNode>, val moduleNameIsStringLiteral: Boolean, var jsModule: NameEntity?, var jsQualifier: NameEntity?, override var uid: String, override val external: Boolean ) : TopLevelNode
0
null
0
0
61d863946227f59d9b2c7c4e4c463c2558c4e605
652
dukat
Apache License 2.0
client/slack-spring-api-client/src/main/kotlin/com/kreait/slack/api/spring/SpringSlackClient.kt
raphaeldelio
342,576,196
true
{"Kotlin": 923419, "Shell": 654}
package com.kreait.slack.api.spring import com.kreait.slack.api.SlackClient import com.kreait.slack.api.group.auth.AuthGroup import com.kreait.slack.api.group.chat.ChatMethodGroup import com.kreait.slack.api.group.conversations.ConversationsMethodGroup import com.kreait.slack.api.group.dialog.DialogMethodGroup import com.kreait.slack.api.group.oauth.OauthMethodGroup import com.kreait.slack.api.group.pins.PinsMethodGroup import com.kreait.slack.api.group.reminders.RemindersMethodGroup import com.kreait.slack.api.group.respond.RespondMethodGroup import com.kreait.slack.api.group.team.TeamMethodGroup import com.kreait.slack.api.group.usergroups.UsergroupsMethodGroup import com.kreait.slack.api.group.users.UsersMethodGroup import com.kreait.slack.api.spring.group.auth.SpringAuthMethodGroup import com.kreait.slack.api.spring.group.chat.SpringChatMethodGroup import com.kreait.slack.api.spring.group.conversations.SpringConversationsMethodGroup import com.kreait.slack.api.spring.group.dialog.SpringDialogMethodGroup import com.kreait.slack.api.spring.group.oauth.SpringOauthMethodGroup import com.kreait.slack.api.spring.group.pins.SpringPinsMethodGroup import com.kreait.slack.api.spring.group.reminders.SpringRemindersMethodGroup import com.kreait.slack.api.spring.group.respond.SpringRespondMethodGroup import com.kreait.slack.api.spring.group.team.SpringTeamMethodGroup import com.kreait.slack.api.spring.group.usergroups.SpringUsergroupMethodGroup import com.kreait.slack.api.spring.group.users.SpringUserMethodGroup /** * Api Client to interact with the slack api */ class SpringSlackClient : SlackClient { /** * Convenience function to apply slack api oauth method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun respond(): RespondMethodGroup { return SpringRespondMethodGroup() } /** * Convenience function to apply slack api auth method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun auth(): AuthGroup { return SpringAuthMethodGroup() } /** * Convenience function to apply slack api chat method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun chat(): ChatMethodGroup { return SpringChatMethodGroup() } /** * Convenience function to apply slack api dialog method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun dialog(): DialogMethodGroup { return SpringDialogMethodGroup() } /** * Convenience function to apply slack api conversation method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun conversation(): ConversationsMethodGroup { return SpringConversationsMethodGroup() } /** * Convenience function to apply slack api users method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun users(): UsersMethodGroup { return SpringUserMethodGroup() } /** * Convenience function to apply slack api oauth method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun oauth(): OauthMethodGroup { return SpringOauthMethodGroup() } /** * Convenience function to apply slack api Team method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun team(): TeamMethodGroup { return SpringTeamMethodGroup() } /** * Convenience function to apply slack api Usergroups method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun usergroups(): UsergroupsMethodGroup { return SpringUsergroupMethodGroup() } /** * Convenience function to apply slack api Usergroups method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun reminders(): RemindersMethodGroup { return SpringRemindersMethodGroup() } /** * Convenience function to apply slack api Pins method grouping * * [Slack Api Documentation](https://api.slack.com/methods) */ override fun pins(): PinsMethodGroup { return SpringPinsMethodGroup() } /** * [SpringSlackClient] configuration class that contains slack configuration options */ data class Config constructor(val slackToken: String) }
0
null
0
0
7313d2205e2b284d7d50c6d04e7acd29b284f433
4,576
slack-spring-boot-starter
MIT License
core/src/main/java/io/github/thisdk/core/cookie/AppCookieStore.kt
thisdk
584,729,338
false
{"Kotlin": 21141}
package io.github.thisdk.core.cookie import io.github.thisdk.core.ds.AppDataStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import okhttp3.Cookie import okhttp3.HttpUrl class AppCookieStore(private val appDataStore: AppDataStore) { fun save(url: HttpUrl, cookies: List<Cookie>) { runBlocking(Dispatchers.IO) { val keySet = cookies.asFlow() .filter { it.expiresAt > System.currentTimeMillis() } .map { AppCookie( name = it.name, value = it.value, expiresAt = it.expiresAt, domain = it.domain, path = it.path, secure = it.secure, httpOnly = it.httpOnly, persistent = it.persistent, hostOnly = it.hostOnly ) }.onEach { appDataStore.putString("${it.name}@${url.host}", Json.encodeToString(it)) }.map { it.name }.toSet() appDataStore.putStringSet(url.host, keySet) } } fun load(url: HttpUrl): List<Cookie> { return appDataStore.getStringSet4Sync(url.host) .asSequence() .mapNotNull { appDataStore.getString4Sync("${it}@${url.host}") } .map { Json.decodeFromString(AppCookie.serializer(), it) } .filter { it.expiresAt > System.currentTimeMillis() } .map { val builder = Cookie.Builder() builder.name(it.name) builder.value(it.value) builder.expiresAt(it.expiresAt) builder.domain(it.domain) builder.path(it.path) if (it.secure) { builder.secure() } if (it.hostOnly) { builder.hostOnlyDomain(it.domain) } else { builder.domain(it.domain) } if (it.httpOnly) { builder.httpOnly() } builder.build() }.toMutableList() } }
0
Kotlin
0
0
f9226751072c7687f915ef842c153d022bae767f
2,382
waterink
Apache License 2.0
mobile/app/src/main/java/at/sunilson/tahomaraffstorecontroller/mobile/features/schedules/presentation/add/DaySelectionRow.kt
sunilson
524,687,319
false
{"Kotlin": 247961}
package at.sunilson.tahomaraffstorecontroller.mobile.features.schedules.presentation.add import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Checkbox 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.tooling.preview.Preview import androidx.compose.ui.unit.dp import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.toImmutableSet import java.time.DayOfWeek @Composable fun DaySelectionRow( selectedDays: ImmutableSet<DayOfWeek> = emptySet<DayOfWeek>().toImmutableSet(), onDayOfWeekClicked: (DayOfWeek) -> Unit = {} ) { Row(modifier = Modifier.fillMaxWidth()) { DayOfWeek.values().forEach { DayCheckbox(dayOfWeek = it, selectedDays = selectedDays, onDayOfWeekClicked = onDayOfWeekClicked) } } } @Composable private fun RowScope.DayCheckbox( dayOfWeek: DayOfWeek, selectedDays: ImmutableSet<DayOfWeek>, onDayOfWeekClicked: (DayOfWeek) -> Unit ) { Column( modifier = Modifier .weight(1f) .padding(bottom = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Checkbox( checked = selectedDays.contains(dayOfWeek), onCheckedChange = { onDayOfWeekClicked(dayOfWeek) }, ) Text(text = dayOfWeek.name.take(2)) } } @Preview(showBackground = true, showSystemUi = true) @Composable private fun DaySelectionRowPreview() { DaySelectionRow( selectedDays = setOf(DayOfWeek.WEDNESDAY, DayOfWeek.SATURDAY).toImmutableSet() ) }
0
Kotlin
0
0
1808f76814f433900204552584e38f4bfe832070
2,136
somfy-tahoma-raffstore-app
MIT License
TwoPaneLayout/library/src/main/java/com/microsoft/device/dualscreen/twopanelayout/common/TwoPaneLayoutMeasure.kt
microsoft
426,672,378
false
{"Kotlin": 198513}
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.device.dualscreen.twopanelayout import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Size import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.ParentDataModifier import androidx.compose.ui.layout.Placeable import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import com.microsoft.device.dualscreen.windowstate.WindowMode import kotlin.math.roundToInt @Composable internal fun twoPaneMeasurePolicy( windowMode: WindowMode, isSeparating: Boolean, paneSizes: Array<Size>, mockConstraints: Constraints = Constraints(0, 0, 0, 0) ): MeasurePolicy { return MeasurePolicy { measurables, constraints -> val childrenConstraints = if (mockConstraints == Constraints(0, 0, 0, 0)) constraints else mockConstraints val twoPaneParentData = Array(measurables.size) { measurables[it].data } val placeables: List<Placeable> var totalWeight = 0f var maxWeight = 0f val childrenCount = measurables.count() require(childrenCount == 2) { "TwoPaneLayout requires 2 child elements in the two pane mode" } for (i in measurables.indices) { val parentData = twoPaneParentData[i] val weight = parentData.weight if (weight > 0f) { totalWeight += weight maxWeight = weight.coerceAtLeast(maxWeight) } } // there is no weight or two weights are equal val hasEqualWeight: Boolean = maxWeight == 0f || maxWeight * 2 == totalWeight // shows two panes equally when the foldingFeature is separating or the weights are equal val shouldLayoutEqually = isSeparating || hasEqualWeight placeables = if (shouldLayoutEqually) { measureTwoPaneEqually( constraints = childrenConstraints, paneSizes = paneSizes, measurables = measurables ) } else { // the foldingFeature is not separating and the weights are not equal measureTwoPaneProportionally( constraints = childrenConstraints, measurables = measurables, totalWeight = totalWeight, windowMode = windowMode, twoPaneParentData = twoPaneParentData ) } if (shouldLayoutEqually) { layout(childrenConstraints.maxWidth, childrenConstraints.maxHeight) { placeables.forEachIndexed { index, placeable -> placeTwoPaneEqually( windowMode = windowMode, placeable = placeable, index = index, lastPaneSize = paneSizes[1], constraints = childrenConstraints ) } } } else { layout(childrenConstraints.maxWidth, childrenConstraints.maxHeight) { placeables.forEachIndexed { index, placeable -> placeTwoPaneProportionally( windowMode = windowMode, placeable = placeable, index = index, twoPaneParentData = twoPaneParentData, constraints = childrenConstraints, totalWeight = totalWeight ) } } } } } /** * to measure the two panes for dual-screen/foldable/large-screen without weight, * or with two equal weight */ private fun measureTwoPaneEqually( constraints: Constraints, paneSizes: Array<Size>, measurables: List<Measurable> ): List<Placeable> { val placeables = emptyList<Placeable>().toMutableList() for (i in measurables.indices) { val paneWidth = paneSizes[i].width.roundToInt() val paneHeight = paneSizes[i].height.roundToInt() val childConstraints = Constraints( minWidth = constraints.minWidth.coerceAtMost(paneWidth), minHeight = constraints.minHeight.coerceAtMost(paneHeight), maxWidth = constraints.maxWidth.coerceAtMost(paneWidth), maxHeight = constraints.maxHeight.coerceAtMost(paneHeight) ) placeables.add(measurables[i].measure(childConstraints)) } return placeables } /** * to measure the pane for dual-screen with two non-equal weight */ private fun measureTwoPaneProportionally( constraints: Constraints, measurables: List<Measurable>, totalWeight: Float, windowMode: WindowMode, twoPaneParentData: Array<TwoPaneParentData?> ): List<Placeable> { val minWidth = constraints.minWidth val minHeight = constraints.minHeight val maxWidth = constraints.maxWidth val maxHeight = constraints.maxHeight val placeables = emptyList<Placeable>().toMutableList() for (i in measurables.indices) { val parentData = twoPaneParentData[i] val weight = parentData.weight var childConstraints: Constraints val ratio = weight / totalWeight childConstraints = when (windowMode) { WindowMode.DUAL_PORTRAIT -> { Constraints( minWidth = (minWidth * ratio).roundToInt(), minHeight = minHeight, maxWidth = (maxWidth * ratio).roundToInt(), maxHeight = maxHeight ) } WindowMode.DUAL_LANDSCAPE -> { Constraints( minWidth = minWidth, minHeight = (minHeight * ratio).roundToInt(), maxWidth = maxWidth, maxHeight = (maxHeight * ratio).roundToInt() ) } else -> throw IllegalStateException("[measureTwoPaneProportionally] Error: single pane window mode ($windowMode) found inside TwoPaneContainer") } val placeable = measurables[i].measure(childConstraints) placeables.add(placeable) } return placeables } private fun Placeable.PlacementScope.placeTwoPaneEqually( windowMode: WindowMode, placeable: Placeable, index: Int, lastPaneSize: Size, constraints: Constraints ) { when (windowMode) { WindowMode.DUAL_PORTRAIT -> { var xPosition = 0 // for the first pane if (index != 0) { // for the second pane val lastPaneWidth = lastPaneSize.width.roundToInt() val firstPaneWidth = constraints.maxWidth - lastPaneWidth xPosition += firstPaneWidth } placeable.place(x = xPosition, y = 0) } WindowMode.DUAL_LANDSCAPE -> { var yPosition = 0 if (index != 0) { val lastPaneHeight = lastPaneSize.height.roundToInt() val firstPaneHeight = constraints.maxHeight - lastPaneHeight yPosition += firstPaneHeight } placeable.place(x = 0, y = yPosition) } else -> throw IllegalStateException("[placeTwoPaneEqually] Error: single pane window mode ($windowMode) found inside TwoPaneContainer") } } private fun Placeable.PlacementScope.placeTwoPaneProportionally( windowMode: WindowMode, placeable: Placeable, index: Int, twoPaneParentData: Array<TwoPaneParentData?>, constraints: Constraints, totalWeight: Float ) { when (windowMode) { WindowMode.DUAL_PORTRAIT -> { var xPosition = 0 // for the first pane if (index != 0) { // for the second pane val parentData = twoPaneParentData[index] val weight = parentData.weight val ratio = 1f - (weight / totalWeight) val firstPaneWidth = (constraints.maxWidth * ratio).roundToInt() xPosition += firstPaneWidth } placeable.place(x = xPosition, y = 0) } WindowMode.DUAL_LANDSCAPE -> { var yPosition = 0 if (index != 0) { val parentData = twoPaneParentData[index] val weight = parentData.weight val ratio = 1f - (weight / totalWeight) val firstPaneHeight = (constraints.maxHeight * ratio).roundToInt() yPosition += firstPaneHeight } placeable.place(x = 0, y = yPosition) } else -> throw IllegalStateException("[placeTwoPaneProportionally] Error: single pane window mode ($windowMode) found inside TwoPaneContainer") } } private val IntrinsicMeasurable.data: TwoPaneParentData? get() = parentData as? TwoPaneParentData private val TwoPaneParentData?.weight: Float get() = this?.weight ?: 1f // set weight as 1 by default to avoid the unintentional single pane /** * Parent data associated with children. */ internal data class TwoPaneParentData( var weight: Float = 1f ) internal class LayoutWeightImpl( val weight: Float, inspectorInfo: InspectorInfo.() -> Unit ) : ParentDataModifier, InspectorValueInfo(inspectorInfo) { override fun Density.modifyParentData(parentData: Any?) = ((parentData as? TwoPaneParentData) ?: TwoPaneParentData()).also { it.weight = weight } override fun equals(other: Any?): Boolean { if (this === other) return true val otherModifier = other as? LayoutWeightImpl ?: return false return weight != otherModifier.weight } override fun hashCode(): Int { var result = weight.hashCode() result *= 31 return result } override fun toString(): String = "LayoutWeightImpl(weight=$weight)" }
1
Kotlin
3
74
17769ca638e5cab086e0532f407585bdeb0fd26e
10,124
surface-duo-compose-sdk
MIT License
kompendium-swagger-ui/src/main/kotlin/io/bkbn/kompendium/swagger/SwaggerUI.kt
bkbnio
356,919,425
false
null
package org.leafygreens.kompendium.swagger import io.ktor.application.call import io.ktor.response.respondRedirect import io.ktor.routing.Routing import io.ktor.routing.get fun Routing.swaggerUI(openApiJsonUrl: String = "/openapi.json") { get("/swagger-ui") { call.respondRedirect("/webjars/swagger-ui/index.html?url=$openApiJsonUrl", true) } }
8
null
7
33
ae2a1b578a66d7c805a2fcd37878c482faa11f55
355
kompendium
MIT License
kit/src/main/java/healthstack/kit/task/activity/step/TappingSpeedMeasureStep.kt
S-HealthStack
520,365,275
false
{"Kotlin": 900773}
package healthstack.kit.task.activity.step import androidx.compose.runtime.Composable import healthstack.kit.task.activity.model.TappingSpeedMeasureModel import healthstack.kit.task.activity.view.TappingSpeedMeasureView import healthstack.kit.task.base.CallbackCollection import healthstack.kit.task.base.Step import healthstack.kit.task.base.View class TappingSpeedMeasureStep( id: String, name: String, model: TappingSpeedMeasureModel, view: View<TappingSpeedMeasureModel> = TappingSpeedMeasureView(), ) : Step<TappingSpeedMeasureModel, Map<String, Int>>(id, name, model, view, { mapOf() }) { @Composable override fun Render(callbackCollection: CallbackCollection): Unit = view.Render(model, callbackCollection, null) }
5
Kotlin
19
25
a8fc44c65b482e53e4ef3fb8f539ec731ef59230
756
app-sdk
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/Diversity1Rounded.kt
karakum-team
387,062,541
false
{"Kotlin": 3079611, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/Diversity1Rounded") package mui.icons.material @JsName("default") external val Diversity1Rounded: SvgIconComponent
0
Kotlin
5
35
60404a8933357df15ecfd8caf6e83258962ca909
198
mui-kotlin
Apache License 2.0
embedded_video_lib/src/main/java/com/gapps/library/api/VideoLoadHelper.kt
TalbotGooday
225,641,422
false
null
package com.gapps.library.api import android.content.Context import android.util.Log import com.gapps.library.api.models.api.base.VideoInfoModel import com.gapps.library.api.models.video.VideoPreviewModel import com.gapps.library.api.models.video.base.BaseVideoResponse import com.gapps.library.cache.getCachedVideoModel import com.gapps.library.cache.insertModel import com.gapps.library.utils.errors.ERROR_2 import com.gapps.library.utils.errors.ERROR_3 import com.google.gson.GsonBuilder import com.google.gson.JsonElement import com.google.gson.JsonParser.parseString import kotlinx.coroutines.* import okhttp3.OkHttpClient import okhttp3.Request import java.lang.reflect.Type import kotlin.coroutines.CoroutineContext internal class VideoLoadHelper( private val context: Context?, private val client: OkHttpClient, private val isCacheEnabled: Boolean, private val isLogEnabled: Boolean, ) : CoroutineScope { override val coroutineContext: CoroutineContext get() = SupervisorJob() + Dispatchers.Main private val gson = GsonBuilder() .setLenient() .setPrettyPrinting() .create() fun getVideoInfo( originalUrl: String?, videoInfoModel: VideoInfoModel<*>, onSuccess: (VideoPreviewModel) -> Unit, onError: (String, String) -> Unit, ) { val finalUrl = videoInfoModel.getInfoUrl(originalUrl) val videoId = videoInfoModel.parseVideoId(originalUrl) if (finalUrl == null || videoId == null) { onError.invoke(originalUrl ?: "null url", ERROR_3) return } val playLink = videoInfoModel.getPlayLink(videoId) launch { if (isCacheEnabled) { if (context != null) { try { val model = getCachedVideoModel(context, playLink) if (model != null) { onSuccess.invoke(model) return@launch } } catch (e: Exception) { e.printStackTrace() } } } try { val jsonBody = makeCallGetBody(client, finalUrl) if (isLogEnabled) { Log.i( VideoService.TAG, "a response from $originalUrl:\n${gson.toJson(jsonBody)}" ) } if (jsonBody == null) { onSuccess.invoke( VideoPreviewModel.error( originalUrl, "$ERROR_2 \n---> Response is null" ) ) return@launch } val result = fromJson(jsonBody, videoInfoModel.type) .toPreview( url = originalUrl, linkToPlay = playLink, hostingName = videoInfoModel.hostingName, videoId = videoId ) onSuccess.invoke(result) try { if (context != null && isCacheEnabled) { insertModel(context, result) } } catch (e: Exception) { onError.invoke( originalUrl ?: "null url", "$ERROR_2\n---> ${e.localizedMessage}" ) } } catch (e: Exception) { onError.invoke( originalUrl ?: "null url", "$ERROR_2 !!! \n---> ${e.localizedMessage}" ) } } } @Suppress("BlockingMethodInNonBlockingContext") private suspend fun makeCallGetBody(client: OkHttpClient, url: String) = withContext(Dispatchers.IO) { val response = client.newCall(Request.Builder().url(url).build()).execute() val stringBody = response.body?.string() ?: return@withContext null val jsonObject = parseString(stringBody) return@withContext if (jsonObject.isJsonArray) { jsonObject.asJsonArray[0] } else { jsonObject } } private fun fromJson(json: JsonElement?, type: Type?): BaseVideoResponse { return gson.fromJson(json, type) } }
2
null
3
27
bb80676b24739cd861fdae526a666045b18cee44
4,492
Android-Oembed-Video
Apache License 2.0
app/src/main/java/com/example/consumapp/AddVehicleScreen.kt
maikelrkruger
828,428,591
false
{"Kotlin": 18685}
package com.example.consumapp import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import com.example.consumapp.databinding.ActivityAddVehicleScreenBinding import com.example.consumapp.helper.FirebaseHelper import com.example.consumapp.model.VehicleModel import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.firestore import com.google.firebase.firestore.ktx.firestore class AddVehicleScreen : AppCompatActivity() { private lateinit var binding: ActivityAddVehicleScreenBinding var vehicle = VehicleModel() private var newVehicle: Boolean = true private var funToDo: Int = -1 private var vehicleId: Int = -1 private val refDbVehicles = com.google.firebase.ktx.Firebase.firestore.collection("users").document(FirebaseAuth.getInstance().currentUser!!.uid).collection("vehicles") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAddVehicleScreenBinding.inflate(layoutInflater) enableEdgeToEdge() setContentView(binding.root) binding.backButton.setOnClickListener(){ goStartScreen() } funToDo = intent.getIntExtra("funToDo", 1) vehicleId = intent.getIntExtra("vehicleId", -1) if (funToDo == 1) { newVehicle = true binding.vehicleAddText.setText("Adicionar veículo") initListeners() } else if (funToDo == 0){ newVehicle = false binding.vehicleAddText.setText("Atualizar veículo") editVehicle() } else { binding.vehicleAddText.setText("Erro") } } private fun goStartScreen(){ val startScreen = Intent(this, StartScreen::class.java) startActivity(startScreen) finish() } private fun progressSignup(inProgress : Boolean){ if (inProgress){ binding.progressAddVehicle.visibility = View.VISIBLE binding.addVehicleButton.visibility = View.GONE }else{ binding.progressAddVehicle.visibility = View.GONE binding.addVehicleButton.visibility = View.VISIBLE } } private fun initListeners(){ binding.addVehicleButton.setOnClickListener{ validateData() } } private fun validateData(){ val vehModel = binding.vehicleModelInput.text.toString().trim() val vehBrand = binding.vehicleBrandInput.text.toString().trim() val vehAge = binding.vehicleAgeInput.text.toString().trim() val vehConsum = binding.vehicleConsumInput.text.toString().trim() if (vehModel.isNotEmpty() || vehBrand.isNotEmpty() || vehAge.isNotEmpty() || vehConsum.isNotEmpty()){ progressSignup(true) if (newVehicle == true) { vehicle = VehicleModel() refDbVehicles.get().addOnSuccessListener { querySnapshot -> for (document in querySnapshot) { if (document != null) { val id = document.data?.get("id")!!.toString() vehicle.id = id.toInt() + 1 println("ID novo" + vehicle.id.toString()) } } } } println("ID depois do for " + vehicle.id.toString()) vehicle.model = vehModel vehicle.brand = vehBrand vehicle.age = vehAge vehicle.consum = vehConsum saveVehicle() }else{ Toast.makeText(applicationContext,"Preencha todos os campos corretamente.", Toast.LENGTH_SHORT).show() progressSignup(false) } } private fun saveVehicle(){ Firebase.firestore .collection("users").document(FirebaseHelper.getIdUser() ?: "") .collection("vehicles").document(vehicle.key) .set(vehicle) .addOnCompleteListener{ vehicle -> if(vehicle.isSuccessful){ if (newVehicle){ Toast.makeText(applicationContext, "Veículo adicionado com sucesso.",Toast.LENGTH_SHORT).show() goStartScreen() }else{ Toast.makeText(applicationContext, "Veículo atualizado com sucesso.",Toast.LENGTH_SHORT).show() goStartScreen() } }else{ Toast.makeText(applicationContext, "Veículo não foi adicionado.",Toast.LENGTH_SHORT).show() progressSignup(false) } }.addOnFailureListener { Toast.makeText(applicationContext, "Veículo não foi adicionado.",Toast.LENGTH_SHORT).show() progressSignup(false) } } private fun editVehicle(){ refDbVehicles.get().addOnSuccessListener { querySnapshot -> for (document in querySnapshot) { if (document != null) { val id = document.data?.get("id")!!.toString() val model = document.data?.get("model")?.toString() val brand = document.data?.get("brand")?.toString() val age = document.data?.get("age")?.toString() binding.vehicleModelInput.setText(model) binding.vehicleAgeInput.setText(age) binding.vehicleBrandInput.setText(brand) vehicleId = id.toInt() initListeners() // val age = document.getString("age") } } } } }
0
Kotlin
0
0
d9d0d63674ae0194e1a5a2a0cb1aa5abf3ac6e28
5,762
consumio_apk
MIT License
app/src/main/java/com/example/play/anim/InstallButtonAnim.kt
pushpalroy
301,166,308
false
null
package com.example.play.anim import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FastOutLinearInEasing import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode.Reverse import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateIntAsState import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.snap import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.play.anim.ButtonState.IDLE import com.example.play.anim.ButtonState.PRESSED enum class ButtonState { IDLE, PRESSED } @Composable fun getInstallButtonOpacityState( isPressed: Boolean ): State<Float> { val currentState = if (isPressed) PRESSED else IDLE val transition = updateTransition(targetState = currentState, label = "installButtonOpacityState") return transition.animateFloat( transitionSpec = { when { IDLE isTransitioningTo PRESSED -> tween(durationMillis = 1500) PRESSED isTransitioningTo IDLE -> { tween(durationMillis = 2000) } else -> snap() } }, label = "installButtonOpacityState" ) { installButtonOpacityState -> when (installButtonOpacityState) { IDLE -> 0f PRESSED -> 0.5f } } } @Composable fun getButtonIconSizeState(): State<Float> { val transition = rememberInfiniteTransition() return transition.animateFloat( initialValue = 0f, targetValue = 24f, animationSpec = infiniteRepeatable( tween(500), Reverse ) ) } @Composable fun getOpenButtonWidthState(isPressed: Boolean): State<Dp> { return animateDpAsState( targetValue = if (isPressed) 150.dp else 0.dp, animationSpec = tween( durationMillis = 800, delayMillis = if (isPressed) 0 else 1500 ) ) } @Composable fun getInstallButtonWidthState(isPressed: Boolean): State<Dp> { return animateDpAsState( targetValue = if (isPressed) 150.dp else 340.dp, animationSpec = tween( durationMillis = 1500, delayMillis = if (isPressed) 800 else 0 ) ) } @Composable fun getButtonColorState(isPressed: Boolean): State<Color> { return animateColorAsState( targetValue = if (isPressed) Color(0xff01875f) else Color.White, animationSpec = tween( durationMillis = 500 ) ) } @Composable fun getInstallBtnBorderColorState(isPressed: Boolean): State<Color> { return animateColorAsState( targetValue = if (isPressed) Color.White else Color(0xff01875f) ) } @Composable fun getInstallBtnBorderWidthState(isPressed: Boolean): State<Dp> { return animateDpAsState( targetValue = if (isPressed) 0.dp else 1.dp, ) } @Composable fun getInstallBtnBgColorState(isPressed: Boolean): State<Color> { return animateColorAsState( targetValue = if (isPressed) Color.White else Color(0xff01875f), animationSpec = tween( durationMillis = 3000 ) ) } @Composable fun getInstallBtnCornerState(isPressed: Boolean): State<Int> { return animateIntAsState( targetValue = if (isPressed) 50 else 10, animationSpec = tween( durationMillis = 3000, easing = FastOutLinearInEasing, ) ) } @Composable fun getOpenButtonGapWidthState(isPressed: Boolean): State<Dp> { return animateDpAsState( targetValue = if (isPressed) 8.dp else 0.dp, animationSpec = tween( durationMillis = 800, delayMillis = if (isPressed) 800 else 1500, easing = LinearEasing ) ) }
0
Kotlin
16
78
5d9487920c60a3a582f99bdcfa3a8a71dd174d46
3,883
jetstore
Apache License 2.0
app/src/main/java/io/geeteshk/dot/App.kt
geeteshk
152,525,611
false
null
/* * Copyright 2018 Geetesh Kalakoti * * 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 io.geeteshk.dot import android.app.Application import com.squareup.leakcanary.LeakCanary import io.github.inflationx.calligraphy3.CalligraphyConfig import io.github.inflationx.calligraphy3.CalligraphyInterceptor import io.github.inflationx.viewpump.ViewPump /** * A custom application class used to inject LeakCanary for debug * builds and our rounded font throughout the app using Calligraphy */ class App : Application() { /** * Called when the Application is created * * This is where we do our installation of LeakCanary * and Calligraphy fonts */ override fun onCreate() { super.onCreate() // LeakCanary for detecting memory leaks if (LeakCanary.isInAnalyzerProcess(this)) return LeakCanary.install(this) // Calligraphy to set a custom font ViewPump.init(ViewPump.builder() .addInterceptor(CalligraphyInterceptor( CalligraphyConfig.Builder() .setDefaultFontPath("fonts/VarelaRound-Regular.otf") .setFontAttrId(R.attr.fontPath) .build() )).build()) } }
0
Kotlin
0
0
cf2b9bab70b1ce03826fd60576763f7e2eefdacc
1,810
Dot
Apache License 2.0
core_library_common/src/jvmTest/kotlin/net/apptronic/core/viewmodel/navigation/TestListAdapter.kt
apptronicnet
264,405,837
false
null
package net.apptronic.core.viewmodel.navigation import net.apptronic.core.viewmodel.navigation.adapters.ViewModelListAdapter class TestListAdapter : ViewModelListAdapter<Unit> { var items: List<ViewModelItem> = emptyList() override fun onDataChanged(items: List<ViewModelItem>, state: Unit, changeInfo: Any?) { this.items = items } fun setFullBound(viewModel: ViewModelItem, state: Boolean) { if (state) { viewModel.setBound(true) viewModel.setVisible(true) viewModel.setFocused(true) } else { viewModel.setFocused(false) viewModel.setVisible(false) viewModel.setBound(false) } } }
2
Kotlin
0
6
5320427ddc9dd2393f01e75564dab126fdeaac72
711
core
MIT License
src/main/kotlin/net/misskey4j/listeners/NoteListener.kt
tomocrafter
152,958,997
false
null
package net.misskey4j.listeners import net.misskey4j.Note interface NoteListener { fun onConnected() fun onNote(note: Note) fun onDisconnect() }
0
Kotlin
0
0
869b576b18efe69782d59371223ffa46db4d066d
160
Misskey4J
Apache License 2.0
app/src/main/java/com/ejiaah/chattingapp/ChatFragment.kt
ejiaah
188,538,738
false
null
package com.ejiaah.chattingapp import android.content.Context import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager.widget.ViewPager import com.google.android.material.tabs.TabLayout // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [ChatFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [ChatFragment.newInstance] factory method to * create an instance of this fragment. * */ class ChatFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null private var listener: OnFragmentInteractionListener? = null private lateinit var chatPager: ViewPager private lateinit var chatPagerAdapter: ChatPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.d(TAG, "LifeCycle: onCreateView") // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_chat, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { Log.d(TAG, "LifeCycle: onViewCreated") super.onViewCreated(view, savedInstanceState) listener?.setupToolbar(getString(R.string.title_chatting), mutableListOf(MainActivity.ToolbarContent.TITLE, MainActivity.ToolbarContent.CHARACTER)) chatPagerAdapter = ChatPagerAdapter(childFragmentManager) chatPager = view.findViewById(R.id.chat_pager) chatPager.adapter = chatPagerAdapter val tabLayout = view.findViewById<TabLayout>(R.id.chat_tab) tabLayout.setupWithViewPager(chatPager) } class ChatPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { override fun getItem(position: Int): Fragment { val fragment: Fragment // fragment.arguments = Bundle().apply { // // Our object is just an integer :-P // putInt(ARG_OBJECT, i + 1) // } when (position) { 0 -> fragment = RoomFragment() else -> fragment = MessageFragment() } return fragment } override fun getPageTitle(position: Int): CharSequence { when (position) { 0 -> return "dd" else -> return "dddd" // 0 -> return R.string.friend // else -> return R.string.message } } override fun getCount(): Int = 2 } // TODO: Rename method, update argument and hook method into UI event fun onButtonPressed(uri: Uri) { //listener?.onFragmentInteraction(uri) } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnFragmentInteractionListener) { listener = context } else { throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() listener = null } companion object { private const val TAG = "ChatFragment" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ChatFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ChatFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
0
Kotlin
0
0
0dc65bdfeabc911ae9a6e929ba383d418c298181
4,604
android-chatting-app
Apache License 2.0
app/src/main/java/com/example/proyecto_veterinaria/VacunaUno.kt
2020-A-Moviles-GR1
296,729,688
false
{"JavaScript": 359185, "HTML": 211279, "Kotlin": 123196, "Less": 783, "CSS": 528}
package com.example.proyecto_veterinaria import android.os.Parcel import android.os.Parcelable class VacunaUno( var createdAt: Long, var updatedAt: Long, var id: Int, var fechaVacuna: String?, var tipoVacuna: String?, var numDosisVacuna: String?, var cita: Int ) :Parcelable{ constructor(parcel: Parcel) : this( parcel.readLong(), parcel.readLong(), parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readInt() ) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(createdAt) parcel.writeLong(updatedAt) parcel.writeInt(id) parcel.writeString(fechaVacuna) parcel.writeString(tipoVacuna) parcel.writeString(numDosisVacuna) parcel.writeInt(cita) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<VacunaUno> { override fun createFromParcel(parcel: Parcel): VacunaUno { return VacunaUno(parcel) } override fun newArray(size: Int): Array<VacunaUno?> { return arrayOfNulls(size) } } }
0
JavaScript
0
0
95bbe98589a472d6cc87e419f7ba5c11a8200a71
1,235
proyecto-Reinoso-Revelo
MIT License
app/src/main/java/com/example/proyecto_veterinaria/VacunaUno.kt
2020-A-Moviles-GR1
296,729,688
false
{"JavaScript": 359185, "HTML": 211279, "Kotlin": 123196, "Less": 783, "CSS": 528}
package com.example.proyecto_veterinaria import android.os.Parcel import android.os.Parcelable class VacunaUno( var createdAt: Long, var updatedAt: Long, var id: Int, var fechaVacuna: String?, var tipoVacuna: String?, var numDosisVacuna: String?, var cita: Int ) :Parcelable{ constructor(parcel: Parcel) : this( parcel.readLong(), parcel.readLong(), parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readInt() ) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(createdAt) parcel.writeLong(updatedAt) parcel.writeInt(id) parcel.writeString(fechaVacuna) parcel.writeString(tipoVacuna) parcel.writeString(numDosisVacuna) parcel.writeInt(cita) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<VacunaUno> { override fun createFromParcel(parcel: Parcel): VacunaUno { return VacunaUno(parcel) } override fun newArray(size: Int): Array<VacunaUno?> { return arrayOfNulls(size) } } }
0
JavaScript
0
0
95bbe98589a472d6cc87e419f7ba5c11a8200a71
1,235
proyecto-Reinoso-Revelo
MIT License
app/src/main/java/sn/moisemomo/aadpracticeproject/FormSubmissionActivity.kt
moisemomo
293,787,785
false
null
package sn.moisemomo.aadpracticeproject import android.os.Bundle import android.util.Log import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.annotation.DrawableRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import kotlinx.android.synthetic.main.activity_form_submission.* import sn.moisemomo.aadpracticeproject.viewmodels.FormSubmissionViewModel import java.util.logging.Logger class FormSubmissionActivity : AppCompatActivity() { private lateinit var mViewModel: FormSubmissionViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_form_submission) setSupportActionBar(form_toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = null mViewModel = ViewModelProvider(this).get(FormSubmissionViewModel::class.java) handleClicks() } private fun handleClicks() { submit_form_button.setOnClickListener { if (isAllInputsFilled()) { showConfirmationDialog() } } } private fun isAllInputsFilled(): Boolean { if (first_name.isEditextBlankOrEmpty()) { first_name.error = getString(R.string.field_cant_be_empty) return false } if (last_name.isEditextBlankOrEmpty()) { last_name.error = getString(R.string.field_cant_be_empty) return false } if (email.isEditextBlankOrEmpty()) { email.error = getString(R.string.field_cant_be_empty) return false } if (link.isEditextBlankOrEmpty()) { link.error = getString(R.string.field_cant_be_empty) return false } return true } private fun showConfirmationDialog() { val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(this) val dialogView: View = layoutInflater.inflate(R.layout.dialog_form_confirmation, null) dialogBuilder.setView(dialogView) val alertDialog: AlertDialog = dialogBuilder.create() alertDialog.setCancelable(false) alertDialog.show() dialogView.findViewById<Button>(R.id.yes).setOnClickListener { mViewModel.submitFormInfo( email.text.toString(), first_name.text.toString(), last_name.text.toString(), link.text.toString()).observe(this, Observer { it?.let { code -> alertDialog.dismiss() if (code == 200){ showResultDialog(getString(R.string.submission_successful), R.drawable.ic_check_circle) } else { showResultDialog(getString(R.string.submission_not_successful), R.drawable.ic_alert) } } }) } dialogView.findViewById<ImageView>(R.id.close_dialog).setOnClickListener { alertDialog.dismiss() } } private fun showResultDialog(message: String, @DrawableRes drawable: Int ) { val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(this) val dialogView: View = layoutInflater.inflate(R.layout.result_dialog, null) dialogView.findViewById<ImageView>(R.id.alert_icon).setImageDrawable(ResourcesCompat.getDrawable(resources, drawable , null)) dialogView.findViewById<TextView>(R.id.alert_message).text = message dialogBuilder.setView(dialogView) val alertDialog: AlertDialog = dialogBuilder.create() alertDialog.show() } private fun EditText.isEditextBlankOrEmpty(): Boolean { return this.text.isEmpty() && this.text.isBlank() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() } return true } }
0
Kotlin
0
0
64c2162e7fff49b0d07167eab4d28a75b8488bbc
4,330
aadpracticeproject
Apache License 2.0
app/src/main/java/com/jammin/myapplication/core/component/Table.kt
Junction2022
526,564,786
false
{"Kotlin": 140145}
package com.jammin.myapplication.core.component import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider 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.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.jammin.myapplication.core.theme.Body3 import com.jammin.myapplication.core.theme.JunctionColor data class TableModel( val title: String, val description: String ) @Composable fun TableList( modifier: Modifier = Modifier, tableModel: List<TableModel> ) { LazyColumn( modifier = modifier.border( width = 1.dp, color = JunctionColor.Gray100, shape = RoundedCornerShape(8.dp) ) ) { itemsIndexed(tableModel) { index, item -> Table(table = item) } } } @Composable fun Table( shape: Shape = RectangleShape, table: TableModel ) { Column { Row( modifier = Modifier .fillMaxWidth() .height(44.dp) .background(shape = shape, color = Color.Transparent), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .fillMaxWidth(0.3f) .fillMaxHeight() .background(JunctionColor.BackgroundColor), contentAlignment = Alignment.CenterStart ) { Body3( text = table.title, color = JunctionColor.Gray300, modifier = Modifier.padding(start = 12.dp) ) } Body3( text = table.description, color = JunctionColor.Black, modifier = Modifier.padding(start = 12.dp) ) } Divider(thickness = 1.dp, color = JunctionColor.Gray100, modifier = Modifier.fillMaxWidth()) } } @Preview @Composable fun PreviewTable() { Box(modifier = Modifier.padding(20.dp)) { TableList( tableModel = listOf( TableModel("123", "123"), TableModel("123", "123"), TableModel("123", "123") ) ) } }
4
Kotlin
0
1
5cefcbb90842b2a3ef87d6533be6093a18f375d1
3,019
PaperIn_Android
Apache License 2.0
auth/src/main/kotlin/com/weesnerdevelopment/auth/AuthDatabase.kt
adamWeesner
239,233,558
false
null
package com.weesnerdevelopment.auth import auth.UsersTable import com.weesnerdevelopment.auth.user.UserHistoryTable import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import history.HistoryTable import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils.create import org.jetbrains.exposed.sql.transactions.transaction /** * The database factory for weesnerDevelopment.com. */ object AuthDatabase { /** * Initializes the [DatabaseFactory] and creates the database tables if needed. */ fun init(testing: Boolean) { if (testing) Database.connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver") else Database.connect(hikari()) transaction { create( UsersTable, UserHistoryTable, HistoryTable ) } } private fun hikari() = HikariDataSource( HikariConfig().apply { driverClassName = "org.h2.Driver" jdbcUrl = "jdbc:h2:./server/auth-database;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false" maximumPoolSize = 3 isAutoCommit = false transactionIsolation = "TRANSACTION_REPEATABLE_READ" validate() } ) }
1
Kotlin
1
1
c7962e6ccec3b8b327886a3b35e2e17d16449c34
1,315
weesnerDevelopment
MIT License
kotlin-generator/src/commonMain/kotlin/com.chrynan.graphkl/kotlin/KotlinConstructor.kt
chRyNaN
230,310,677
false
null
package com.chrynan.graphkl.kotlin import com.chrynan.graphkl.kotlin.modifier.VisibilityModifier data class KotlinConstructor( val isPrimary: Boolean = false, val visibility: VisibilityModifier = VisibilityModifier.PUBLIC, val parameters: List<KotlinParameter> = emptyList(), val constructorCall: ((KotlinConstructor) -> String)? = null, val extraImports: List<KotlinImportStatement> = emptyList(), val body: ((KotlinConstructor) -> String)? = null ) { val importStatements: List<KotlinImportStatement> = parameters.flatMap { it.importStatements } + extraImports override fun toString() = buildString { if (!isPrimary) { append("constructor") } append("(") parameters.forEachIndexed { index, parameter -> append(parameter) if (index != parameters.lastIndex) { append(", ") } } append(")") if (constructorCall != null) { append(": ${constructorCall.invoke(this@KotlinConstructor)}") } if (body != null) { append(" {\n") append(body.invoke(this@KotlinConstructor)) append("\n}") } } }
0
Kotlin
0
2
2526cedddc0a5b5777dea0ec7fc67bc2cd16fe05
1,247
graphkl
Apache License 2.0
app/src/main/java/com/rgbstudios/alte/ui/fragments/MessagesFragment.kt
cooncudee
732,994,014
false
null
package com.rgbstudios.alte.ui.fragments import android.os.Bundle import android.text.InputFilter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.PopupMenu import androidx.activity.OnBackPressedCallback import androidx.activity.addCallback import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.SearchView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.google.firebase.auth.FirebaseUser import com.rgbstudios.alte.AlteApplication import com.rgbstudios.alte.R import com.rgbstudios.alte.data.model.Chat import com.rgbstudios.alte.data.model.Peep import com.rgbstudios.alte.data.model.UserDetails import com.rgbstudios.alte.data.remote.FirebaseAccess import com.rgbstudios.alte.data.repository.AlteRepository import com.rgbstudios.alte.databinding.FragmentMessagesBinding import com.rgbstudios.alte.ui.adapters.ConvoAdapter import com.rgbstudios.alte.ui.adapters.PeepAdapter import com.rgbstudios.alte.utils.DateTimeManager import com.rgbstudios.alte.utils.DialogManager import com.rgbstudios.alte.utils.ImageHandler import com.rgbstudios.alte.utils.ToastManager import com.rgbstudios.alte.viewmodel.AlteViewModel import com.rgbstudios.alte.viewmodel.AlteViewModelFactory class MessagesFragment : Fragment() { private val firebase = FirebaseAccess() private val alteViewModel: AlteViewModel by activityViewModels { AlteViewModelFactory( requireActivity().application as AlteApplication, AlteRepository(firebase) ) } private val toastManager = ToastManager() private val dialogManager = DialogManager() private val imageHandler = ImageHandler() private val dateTimeManager = DateTimeManager() private lateinit var binding: FragmentMessagesBinding private lateinit var convoAdapter: ConvoAdapter private var currentUser: FirebaseUser? = null private var isCropImageLayoutVisible = false private lateinit var callback: OnBackPressedCallback private var isSearchResultsShowing = false private var isSearchViewVisible = false private var selectedConvoList: List<UserDetails> = emptyList() private var allConvoList: List<Triple<Chat, String, Pair<Int, Int>>> = emptyList() private var isInSelectionMode = false private var isFilledList = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMessagesBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { currentUser = firebase.auth.currentUser if (currentUser != null) { alteViewModel.startDatabaseListeners(requireActivity().applicationContext) } // Set up the planet adapter val peepAdapter = PeepAdapter(requireContext(), object : PeepAdapter.PeepClickListener { override fun onPeepClick(userPeepPair: Pair<UserDetails, List<Peep>>) { alteViewModel.setPeepItem(userPeepPair) findNavController().navigate(R.id.action_messagesFragment_to_peepsFragment) } }) // Set up the planetRecyclerView to scroll horizontally peepRecyclerView.setHasFixedSize(true) peepRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) peepRecyclerView.adapter = peepAdapter // Set up the Convo adapter convoAdapter = ConvoAdapter(requireContext(), alteViewModel, object : ConvoAdapter.ConvoClickListener { override fun onConvoClick(user: UserDetails) { val currentUserId = alteViewModel.currentUser.value?.uid ?: "" alteViewModel.startChatListener(currentUserId, user) navigateToChatFragment() } override fun onAvatarClick(user: UserDetails) { alteViewModel.setSelectedCitizen(user) findNavController().navigate(R.id.action_messagesFragment_to_citizenProfileFragment) } }) // Set up the convoRecyclerView convoRecyclerView.layoutManager = LinearLayoutManager(context) convoRecyclerView.adapter = convoAdapter myPeepLayout.setOnClickListener { // TODO Change to open camera // TODO Change to open dialog of list of peeps and view plus a add new peep button pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } moreOptions.setOnClickListener { view -> showOverflowMenu(view) } fab.setOnClickListener { findNavController().navigate(R.id.action_messagesFragment_to_alteVerseFragment) } /** * ----chatSelectedLayout buttons----------------------------- */ selectAllIV.setOnClickListener { if (isFilledList) { convoAdapter.clearSelection() } else { convoAdapter.fillSelection() } } markUnreadIV.setOnClickListener { // TODO mark unread leaveSelectionMode() } clearChatIV.setOnClickListener { // TODO clear Chat leaveSelectionMode() } /** * ---------------------------------------------------------- */ swipeRefreshLayout.setOnRefreshListener { // Update data from database when the user performs the pull-to-refresh action if (currentUser != null) { updateLists() } } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(query: String?): Boolean { isSearchResultsShowing = if (query.isNullOrEmpty()) { convoAdapter.updateConvoList(allConvoList.reversed()) false } else { val searchResults = allConvoList.filter { it.first.message.lowercase().contains(query) } convoAdapter.updateConvoList(searchResults) true } return true } }) /** * ----observers--------------------------------------------- */ alteViewModel.allUsersList.observe(viewLifecycleOwner) { users -> if (users != null) { alteViewModel.folksPeeps.observe(viewLifecycleOwner) { uidListPair -> if (uidListPair != null) { val updatePeepsList = mutableListOf<Triple<UserDetails, List<Peep>, String>>() uidListPair.forEach { pair -> val folkUid = pair.first val folkDetails = users.find { it.uid == folkUid } val peepList = pair.second if (folkDetails != null && peepList.isNotEmpty()) { val currentUsername = alteViewModel.currentUser.value?.username if (currentUsername != null) { val peepTriple = Triple(folkDetails, pair.second, currentUsername) updatePeepsList.add(peepTriple) } } } updatePeepsList.find { it.first.uid == currentUser?.uid } ?.let { foundPair -> // Remove your peep from its current position updatePeepsList.remove(foundPair) // Add it to the top of the list updatePeepsList.add(0, foundPair) } peepAdapter.updatePeeps(updatePeepsList) } } } } alteViewModel.convoList.observe(viewLifecycleOwner) { latestConvo -> val currentUsername = alteViewModel.currentUser.value?.username if (currentUsername != null) { welcomeTV.text = getString(R.string.welcome_message, currentUsername) } if (latestConvo != null) { if (latestConvo.isEmpty()) { emptyConvoLayout.visibility = View.VISIBLE } else { emptyConvoLayout.visibility = View.GONE convoAdapter.updateConvoList(latestConvo.reversed()) allConvoList = latestConvo } } lottieAnimationView.visibility = View.GONE } alteViewModel.selectedConvoItems.observe(viewLifecycleOwner) { convoList -> if (convoList != null) { selectedConvoList = convoList isInSelectionMode = if (convoList.isNotEmpty()) { chatSelectedLayout.visibility = View.VISIBLE true } else { chatSelectedLayout.visibility = View.GONE false } callback.isEnabled = isInSelectionMode isFilledList = convoList.size == allConvoList.size selectionCounter.text = selectedConvoList.size.toString() } } //Set up back pressed call back callback = requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { if (isInSelectionMode) { leaveSelectionMode() } else if (isCropImageLayoutVisible) { cropImageLayout.visibility = View.GONE isCropImageLayoutVisible = false } callback.isEnabled = false } // Disable the callback by default callback.isEnabled = false } } private fun navigateToChatFragment() { findNavController().navigate(R.id.action_messagesFragment_to_chatFragment) } private val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> if (uri != null) { binding.apply { cropImageView.setImageUriAsync(uri) cropImageView.setAspectRatio(1, 1) // show the cropping layout cropImageLayout.visibility = View.VISIBLE isCropImageLayoutVisible = true callback.isEnabled = isCropImageLayoutVisible doneCrop.setOnClickListener { // Show the loading animation myPeepProgressBar.visibility = View.VISIBLE cropImageLayout.visibility = View.GONE isCropImageLayoutVisible = false val croppedBitmap = cropImageView.getCroppedImage() val compressedBitmap = croppedBitmap?.let { it1 -> imageHandler.compressBitmap(it1) } // Upload the Bitmap if (currentUser != null && compressedBitmap != null) { val currentTime = dateTimeManager.getCurrentTimeFormatted() val peepCaption = captionCrop.text.toString().trim() captionCrop.text.clear() alteViewModel.uploadPeep( currentUser!!.uid, currentTime, compressedBitmap, peepCaption, requireActivity().applicationContext ) { uploadSuccessful -> if (uploadSuccessful) { toastManager.showShortToast( requireContext(), "Peep uploaded successfully" ) } else { toastManager.showShortToast( requireContext(), "Peep upload failed" ) } myPeepProgressBar.visibility = View.GONE } } } cancelCrop.setOnClickListener { cropImageLayout.visibility = View.GONE captionCrop.text.clear() isCropImageLayoutVisible = false callback.isEnabled = isCropImageLayoutVisible } rotateCrop.setOnClickListener { cropImageView.rotateImage(90) } binding.captionCrop.filters = arrayOf(InputFilter { source, _, _, _, _, _ -> // Replace newline characters with an empty string source?.toString()?.replace("\n", "") ?: "" }) binding.captionCrop.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { // Perform your custom action when the "Done" action is triggered return@setOnEditorActionListener true } false } } } } private fun updateLists() { alteViewModel.startDatabaseListeners(requireActivity().applicationContext) stopRefreshing() } private fun stopRefreshing() { binding.swipeRefreshLayout.isRefreshing = false } private fun showOverflowMenu(view: View) { val popupMenu = PopupMenu(requireContext(), view) // Inflate the menu resource popupMenu.menuInflater.inflate(R.menu.messages_overflow_menu, popupMenu.menu) // Set an OnMenuItemClickListener for the menu items popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.search_messages -> { if (allConvoList.isNotEmpty()) { binding.searchView.visibility = View.VISIBLE isSearchViewVisible = true } true } R.id.new_circle -> { findNavController().navigate(R.id.action_messagesFragment_to_circlesFragment) true } R.id.new_broadcast -> { findNavController().navigate(R.id.action_messagesFragment_to_broadcastFragment) true } R.id.starred_messages -> { findNavController().navigate(R.id.action_messagesFragment_to_starredMessagesFragment) true } R.id.profile_messages -> { findNavController().navigate(R.id.action_messagesFragment_to_profileFragment) true } R.id.settings -> { findNavController().navigate(R.id.action_messagesFragment_to_settingsFragment) true } R.id.logout -> { // Show confirm dialog dialogManager.showLogoutConfirmationDialog( this, alteViewModel ) { isSuccessful -> if (isSuccessful) { // Navigate to SignInFragment findNavController().navigate(R.id.action_messagesFragment_to_signInFragment) } } true } else -> { false } } } // Show the popup menu popupMenu.show() } private fun leaveSelectionMode() { binding.apply { convoAdapter.clearSelection() chatSelectedLayout.visibility = View.GONE isInSelectionMode = false } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Save the state of flags outState.putBoolean("isCropImageLayoutVisible", isCropImageLayoutVisible) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) // Restore the state of flags isCropImageLayoutVisible = savedInstanceState?.getBoolean("isCropImageLayoutVisible") ?: false binding.apply { // Reset cropImage layout visibility if (isCropImageLayoutVisible) { cropImageLayout.visibility = View.VISIBLE } } } }
0
null
0
1
226e188bba7c7c29479d6d795d036ad5a979d4c8
18,619
Alte
MIT License
androidApp/src/main/java/com/vasanth/kmm/apparchitecture/android/ui/common/base/BaseComponentFragment.kt
Hynsn
574,784,028
false
{"Kotlin": 48714, "Swift": 12582}
package com.vasanth.kmm.apparchitecture.android.ui.common.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.runtime.Composable import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.fragment.app.Fragment abstract class BaseComponentFragment : Fragment() { // region Fragment Methods. override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { CreateContent() } } } // endregion // region Abstract Methods @Composable abstract fun CreateContent() // endregion }
0
Kotlin
0
0
7cb2d9939ece92c22d27655da229e9c65959e530
956
KMM-SharedCode
Apache License 2.0
app/src/main/java/com/twilio/chat/app/data/models/MemberListViewItem.kt
twilio
333,359,260
false
null
package com.twilio.chat.app.data.models data class MemberListViewItem( val sid: String, val identity: String, val channelSid: String, val friendlyName: String, val isOnline: Boolean )
0
Kotlin
4
4
7a280eac3a47b805c035a891d2a014f99e50fc0c
205
twilio-chat-demo-kotlin
MIT License
app/src/main/java/com/cognizant/caponeteambuild/data/Home.kt
santhana2022
459,236,428
false
{"Kotlin": 44597}
package com.cognizant.caponeteambuild.data class Home( val articleName: String, val articleImage: Int, val apiKey: String )
0
Kotlin
0
0
b347fa7de54b48dfbe3b86ef90464826ece0fbab
136
CogDemoNYTimes
Apache License 2.0
commonDomain/src/commonMain/kotlin/com/netguru/commondomain/product/model/ShoppingCartInfo.kt
netguru
532,784,187
false
null
package com.netguru.commondomain.product.model import com.netguru.commondomain.shop.model.Price data class ShoppingCartInfo( val numOfItemsInCart: Int = 1, val totalPrice: Price = Price(), val canDecrement: Boolean = true, val canIncrement: Boolean = true ) { companion object { val empty: ShoppingCartInfo get() = ShoppingCartInfo() } }
0
Kotlin
0
9
d755ffe5cf9f87d7c461f029ce6364ce655741e2
384
rnd-retail-multiplatform-public
MIT License
shared/src/commonMain/kotlin/com/joetr/sync/sphere/ui/results/availability/AvailabilityScreen.kt
j-roskopf
712,951,839
false
{"Kotlin": 1460549, "Ruby": 3061, "Shell": 1516, "Swift": 588}
package com.joetr.sync.sphere.ui.results.availability import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Event import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Divider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.lifecycle.LifecycleEffect import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import com.joetr.sync.sphere.design.button.PrimaryButton import com.joetr.sync.sphere.design.theme.conditional import com.joetr.sync.sphere.design.toolbar.DefaultToolbar import com.joetr.sync.sphere.design.toolbar.backOrNull import com.joetr.sync.sphere.ui.ProgressIndicator import com.joetr.sync.sphere.ui.results.availability.data.DayStatus import com.joetr.sync.sphere.ui.time.DayTime import com.joetr.sync.sphere.ui.time.getDisplayText import kotlinx.datetime.LocalDate import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource class AvailabilityScreen( val data: Map<String, DayTime>, ) : Screen { @Composable override fun Content() { val screenModel = getScreenModel<AvailabilityScreenModel>() val viewState = screenModel.state.collectAsState().value LifecycleEffect( onStarted = { screenModel.init(data) }, ) Scaffold( topBar = { DefaultToolbar( onBack = LocalNavigator.currentOrThrow.backOrNull(), ) }, ) { paddingValues -> AnimatedContent( targetState = viewState, ) { targetState -> when (targetState) { is AvailabilityScreenState.Content -> AvailabilityState( modifier = Modifier.padding(paddingValues), data = targetState.data, ) { localDate, dayTime -> screenModel.addToCalendar(localDate, dayTime) } is AvailabilityScreenState.Loading -> LoadingState( modifier = Modifier.padding( paddingValues, ), ) } } } } @Composable private fun AvailabilityState( modifier: Modifier = Modifier, data: Map<DayStatus, List<Pair<String, DayTime>>>, addToCalendar: (LocalDate, DayTime) -> Unit, ) { Column( modifier = modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, ) { LazyColumn { val daysDoWorkEntry = data[DayStatus.DAY_WORKS]!! daysDoWorkEntry.onEachIndexed { index, entry -> item { AvailabilityDayItem( displayDay = entry.first, dayTime = entry.second, addToCalendar = addToCalendar, ) if (index != daysDoWorkEntry.size - 1) { Divider(modifier = Modifier.padding(horizontal = 8.dp)) } } } val daysDoNotWorkEntry = data[DayStatus.DAY_DOES_NOT_WORK]!! if (daysDoNotWorkEntry.isNotEmpty()) { item { Text( modifier = Modifier.padding(16.dp), text = "Days That Do Not Work For Everyone", style = MaterialTheme.typography.headlineMedium, ) } } daysDoNotWorkEntry.onEachIndexed { index, entry -> item { AvailabilityDayItem( displayDay = entry.first, dayTime = entry.second, addToCalendar = addToCalendar, ) if (index != daysDoNotWorkEntry.size - 1) { Divider(modifier = Modifier.padding(horizontal = 8.dp)) } } } } } } @OptIn(ExperimentalResourceApi::class) @Composable @Suppress("MagicNumber") private fun AvailabilityDayItem( displayDay: String, dayTime: DayTime, addToCalendar: (LocalDate, DayTime) -> Unit, ) { val isActionRowVisible = remember { mutableStateOf(false) } val shouldDisplayActionRow = dayTime is DayTime.AllDay || dayTime is DayTime.Range Column( modifier = Modifier.fillMaxWidth() .conditional( shouldDisplayActionRow, { Modifier.clickable { isActionRowVisible.value = isActionRowVisible.value.not() } }, ) .padding(16.dp), ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically, ) { val image = when (dayTime) { is DayTime.AllDay -> "full_availability.png" is DayTime.NotSelected -> "no_availability.png" is DayTime.Range -> "partial_availability.png" } Image( painter = painterResource(image), contentDescription = null, modifier = Modifier.size(32.dp), ) Spacer(modifier = Modifier.size(8.dp)) Text( modifier = Modifier.weight(1.5f), text = displayDay, ) val text = when (dayTime) { is DayTime.AllDay -> "This day works for everyone all day" is DayTime.NotSelected -> "No availability on day" is DayTime.Range -> "This day works for everyone between ${dayTime.getDisplayText()}" } Text( modifier = Modifier.weight(3f), text = text, ) if (shouldDisplayActionRow) { Icon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurface, ) } } if (shouldDisplayActionRow) { AnimatedVisibility( visible = isActionRowVisible.value, ) { PrimaryButton( modifier = Modifier.padding(16.dp), onClick = { val availability = LocalDate.parse(displayDay) addToCalendar(availability, dayTime) }, ) { Icon( imageVector = Icons.Default.Event, contentDescription = null, ) Spacer(modifier = Modifier.width(4.dp)) Text("Add To Calendar") } } } } } @Composable private fun LoadingState(modifier: Modifier = Modifier) { Box( modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { ProgressIndicator() } } }
0
Kotlin
0
1
cc4edd6906783e220066f4f261d6f60193effb29
9,159
SyncSphere
MIT License
src/factory_method/main/Run.kt
yorae39
464,176,357
false
{"Kotlin": 60335}
package factory_method.main import factory_method.api.Issuer import factory_method.api.IssuerCreator import factory_method.api.Type.EMAIL import factory_method.api.Type.SMS import factory_method.api.Type.JMS fun main() { issuerTest() } fun issuerTest() { val issuerOfEmail = IssuerCreator().issuerFoType(EMAIL) val issuerOfSMS = IssuerCreator().issuerFoType(SMS) val issuerOfJMS = IssuerCreator().issuerFoType(JMS) send(issuerOfEmail, "Factory Method - Email send!") send(issuerOfSMS, "Factory Method - SMS send!") send(issuerOfJMS, "Factory Method - JMS send!") } fun send(issuer: Issuer, message: String) { issuer.send(message) }
0
Kotlin
0
0
2d5a321f6e60ae91028adda860ab2d75c0b37ed1
669
design-patterns-kotlin
MIT License
goty-server/src/main/kotlin/com/aleinin/goty/submit/SubmissionRepository.kt
aleinin
319,066,220
false
{"Kotlin": 80296, "TypeScript": 80279, "SCSS": 8199, "JavaScript": 959, "HTML": 881, "Dockerfile": 148, "CSS": 129}
package com.aleinin.goty.submit import org.springframework.data.mongodb.repository.MongoRepository import java.util.UUID interface SubmissionRepository : MongoRepository<Submission, UUID>
6
Kotlin
1
2
52e202a99de3d251aacc19ad657909ae075e6114
190
game-of-the-year
MIT License
src/main/kotlin/me/samboycoding/sambotv6/commands/AddCustomRoleCommand.kt
SamboyCoding
214,277,724
false
null
package me.samboycoding.sambotv6.commands import me.liuwj.ktorm.dsl.and import me.liuwj.ktorm.dsl.eq import me.liuwj.ktorm.entity.find import me.samboycoding.sambotv6.SambotV6 import me.samboycoding.sambotv6.customRoles import me.samboycoding.sambotv6.getCommandData import me.samboycoding.sambotv6.isModerator import me.samboycoding.sambotv6.orm.entities.GuildConfiguration import me.samboycoding.sambotv6.orm.tables.CustomRoles import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.TextChannel class AddCustomRoleCommand : BaseCommand() { override fun execute(msg: Message, author: Member, guild: Guild, channel: TextChannel, config: GuildConfiguration) { //The feature needs to be enabled if (!config.customRolesEnabled) return msg.sendModuleDisabledMessage(getString("moduleNameCustomRoles")) //We need manage roles if (!failIfBotMissingPerm(Permission.MANAGE_ROLES)) return //They need to be a mod if (!author.isModerator()) return msg.sendMissingPermissionMessage() val data = msg.getCommandData(config) //Need at least a tag and a name if(data.argsCount < 2) { msg.delete().submit() return channel.doSend(getString("addCustomRoleMissingArgs", author.asMention)) } //Get the tag (can't have spaces [that's why / because] it's first) val tag = data.getArg(0)!! //Check the tag isn't taken if(SambotV6.instance.db.customRoles.find { (it.guild eq guild.id) and (it.id eq tag) } != null) { msg.delete().submit() return channel.doSend(getString("addCustomRoleTagTaken", author.asMention, tag)) } //Check to see if they've @'d a role to use var role = data.getRoleArg(1, true) //If not, create one using the remainder arg idx 1 if(role == null) { val roleName = data.getArg(1, true) role = guild.createRole() .setHoisted(false) .setMentionable(true) .setPermissions(0) .setName(roleName) .complete() } //Insert into the database with the role id CustomRoles.createForRole(role!!, tag) //Feedback to user msg.delete().submit() channel.doSend(getString("addCustomRoleSuccess", author.asMention, role.name, config.prefix, tag)) } override fun getCommandWords(): List<String> { return listOf("addrole", "addcustomrole") } }
0
Kotlin
0
2
8c3f96b8ec14422c92312d6d6c68083c258d2f27
2,694
SambotV6
Apache License 2.0
app/src/main/java/com/example/touristattractionsinbulgaria/ui/home/HomeFragment.kt
Kavertx
728,627,137
false
{"Kotlin": 27898}
package com.example.touristattractionsinbulgaria.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.example.touristattractionsinbulgaria.TouristAttractionApplication import com.example.touristattractionsinbulgaria.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null private val viewModel: HomeViewModel by activityViewModels { HomeViewModelFactory( (activity?.application as TouristAttractionApplication).database.districtDao(), (activity?.application as TouristAttractionApplication).database.attractionDao(), (activity?.application as TouristAttractionApplication).database.imageDao() ) } // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) // homeViewModel.text.observe(viewLifecycleOwner) { // textView.text = it // } return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
49af76842122f82771f71cdc40a884173a17cd16
1,479
TouristAttractionsinBulgaria
MIT License
libraries/core/src/main/kotlin/com/bumble/appyx/core/integrationpoint/activitystarter/CanProvideActivityStarter.kt
bumble-tech
493,334,393
false
null
package com.bumble.appyx.core.integrationpoint.activitystarter interface CanProvideActivityStarter { val activityStarter: ActivityStarter }
68
Kotlin
45
754
1c13ab49fb3e2eb0bcd192332d597f8c05d3f6a9
145
appyx
Apache License 2.0
app/src/main/java/br/com/fiap/locawebmailapp/components/general/ShadowBox.kt
pedroferrarezzo
800,793,379
false
{"Kotlin": 656574}
package br.com.fiap.locawebmailapp.components.general import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import br.com.fiap.locawebmailapp.R @Composable fun ShadowBox(expanded: MutableState<Boolean>) { if(expanded.value) { Box( modifier = Modifier .background(colorResource(id = R.color.lcweb_black_4)) .fillMaxSize() ) } }
0
Kotlin
0
0
1c160310c5578ffdd386052788bb6774cef4f79f
657
LocaWeb-LocaMail-Kotlin-Compose-Challenge-Fiap
MIT License
android/src/main/kotlin/me/anharu/video_editor/filter/GlTextOverlayFilter.kt
anharu2394
259,526,899
false
null
package me.anharu.video_editor.filter import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import com.daasuu.mp4compose.filter.GlOverlayFilter import me.anharu.video_editor.TextOverlay class GlTextOverlayFilter(textOverlay: TextOverlay) : GlOverlayFilter() { private val textOverlay: TextOverlay = textOverlay; protected override fun drawCanvas(canvas: Canvas) { val bitmap: Bitmap = textAsBitmap(textOverlay.text,textOverlay.size.toFloat(),textOverlay.color) canvas.drawBitmap(bitmap,textOverlay.x.toFloat(),textOverlay.y.toFloat(),null); } private fun textAsBitmap(text: String, textSize: Float, color: String): Bitmap { val paint = Paint(Paint.ANTI_ALIAS_FLAG) //TODO : Use specified font - via. Typeface //TODO : Support Text Bold, Italic & Bold Italic - via. Typeface paint.textSize = textSize paint.color = Color.parseColor(color) //TODO : Support Center & Right Aligns //TODO : Support text will be out of video boundaries check //TODO : Support fallback align if text will be out of video boundaries paint.textAlign = Paint.Align.LEFT val baseline = -paint.ascent() // ascent() is negative val width = (paint.measureText(text) + 0.5f).toInt() // round val height = (baseline + paint.descent() + 0.5f).toInt() val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(image) canvas.drawText(text, 0f, baseline, paint) return image } }
27
null
36
85
5094e559f698694d41cb82988af0365dd8f96381
1,613
tapioca
MIT License
dcache/src/main/java/dora/db/table/Table.kt
dora4
378,306,065
false
null
package dora.db.table import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) @Retention(RetentionPolicy.RUNTIME) annotation class Table(val value: String)
0
Kotlin
1
7
99b570a5e04b616ac1cd18be02d086b0f76cc3d9
251
dcache-android
Apache License 2.0
parent/src/main/java/sk/backbone/parent/application/services/ParentLifecycleService.kt
backbonesk
273,036,191
false
null
package sk.backbone.parent.application.services import androidx.lifecycle.LifecycleService import sk.backbone.parent.execution.IExecutioner import sk.backbone.parent.execution.scopes.ServiceScopes import javax.inject.Inject abstract class ParentLifecycleService : LifecycleService(), IExecutioner<ServiceScopes> { @Inject override lateinit var scopes: ServiceScopes override fun onDestroy() { scopes.cancel() super.onDestroy() } }
0
Kotlin
1
2
c09e3cf15f736ed4b52330c5f039c5af08f1193a
461
parent
MIT License
1er Corte/PropiedadesListas/src/ean/ejercicios/Ejercicios.kt
BrayanTorres2
197,484,467
false
null
package ean.ejercicios import ean.collections.IList import ean.collections.list // Imprimir una lista fun imprimir(lista: IList<Int>) { for (i in 0 until lista.size) { println(lista[i]) } } fun digitos(num: Int):IList<Int>{ val digs=list<Int>() var n=num while(n>0){ val u=n%10// binarios 2 digs.addToHead(u) n/=2 } return digs } fun contarImpares(lista: IList<Int>):Int{ var c=0 for(i in 0 until lista.size){ val elem=lista[i] //lista.get(i) if(elem%2!=0){ c++ } } return c } fun contarImpares2(lista: IList<Int>):Int{ var c=0 for(elem in lista){ if(elem%2!=0){ c+=1 } } return c } fun contarImpares3(lista: IList<Int>):Int{ var c=0 lista.forEach { if(it%2!=0){ c++ } } return c } fun contarImpares4(lista:IList<Int>):Int { var c = 0 var iter = lista.iterator() while (iter.hasNext()) { val elem = iter.next() if (elem % 2 != 0) { c++ } } return c } fun imprimirAlreves(lista: IList<Int>):Unit{ for(i in lista.size-1 downTo 0) println(lista[i]) } // Programa principal fun main(args: Array<String>) { val unaLista = list(4, 3, 1, 8) imprimir(unaLista) print("tamaño de la lista=${unaLista.size}") unaLista.add(18) unaLista.addToHead(5) println("la lista=$unaLista ") unaLista.add(3,7) println("ahora la sita es = $unaLista") unaLista.removeLast() println("la lista sin el 10=$unaLista") unaLista.removeElement(1) unaLista.remove(1) unaLista.set(4,11)//unaLista[4]=11 println("sin el 4 y cambio el 8=$unaLista") println("hay ${contarImpares(unaLista)} en esta lista") imprimirAlreves(unaLista) digitos(1234) }
0
Kotlin
0
0
3503489681196428d1acc505b01bc21dcc180e2e
1,853
Estructura-de-Datos-Kotlin
MIT License
domain/src/main/java/com/mewa/domain/usecase/DownloadCatsUseCase.kt
m-ewa
765,907,767
false
{"Kotlin": 29309}
package com.mewa.domain.usecase import com.mewa.domain.model.Cat import com.mewa.domain.repository.CatsRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class DownloadCatsUseCase @Inject constructor( private val catsRepository: CatsRepository ) { suspend operator fun invoke(): Flow<Result<List<Cat>>> { return catsRepository.getCats() } }
0
Kotlin
0
0
3d1558d4fc2fbe0624668b588ea4ba95b798de7b
386
FlickrApp
MIT License
library/modulon/src/main/java/modulon/extensions/view/LayoutComponents.kt
huskcasaca
464,732,039
false
null
package modulon.extensions.view import android.graphics.drawable.GradientDrawable import android.view.Gravity import android.view.ViewGroup import modulon.R import modulon.extensions.viewbinder.frameLayout import modulon.layout.frame.FrameLayout // TODO: 2022/2/19 remove fun ViewGroup.shader(gravity: Int, block: FrameLayout.() -> Unit = {}) { frameLayout { background = GradientDrawable(when (gravity) { Gravity.TOP -> GradientDrawable.Orientation.TOP_BOTTOM Gravity.BOTTOM -> GradientDrawable.Orientation.BOTTOM_TOP else -> throw IllegalArgumentException() }, intArrayOf(R.color.shader_start_alpha.contextColor(), R.color.shader_end_alpha.contextColor())) setFrameParamsRow(height = 4.dp, gravity = gravity) apply(block) } }
0
Kotlin
4
5
2522ec7169a5fd295225caf936bae2edf09b157e
807
bitshares-oases-android
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/MusicVideoSharp.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/MusicVideoSharp") @file:JsNonModule package mui.icons.material @JsName("default") external val MusicVideoSharp: SvgIconComponent
10
Kotlin
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
212
kotlin-wrappers
Apache License 2.0
src/main/kotlin/us/frollo/frollosdk/model/api/aggregation/transactions/TransactionResponse.kt
frollous
261,670,220
false
null
/* * Copyright 2019 Frollo * * 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 us.frollo.frollosdk.model.api.aggregation.transactions import com.google.gson.annotations.SerializedName import us.frollo.frollosdk.model.coredata.aggregation.accounts.Balance import us.frollo.frollosdk.model.coredata.aggregation.merchants.MerchantDetails import us.frollo.frollosdk.model.coredata.aggregation.transactioncategories.CategoryDetails import us.frollo.frollosdk.model.coredata.aggregation.transactions.TransactionBaseType import us.frollo.frollosdk.model.coredata.aggregation.transactions.TransactionDescription import us.frollo.frollosdk.model.coredata.aggregation.transactions.TransactionStatus import us.frollo.frollosdk.model.coredata.shared.BudgetCategory internal data class TransactionResponse( @SerializedName("id") val transactionId: Long, @SerializedName("base_type") val baseType: TransactionBaseType, @SerializedName("status") val status: TransactionStatus, @SerializedName("transaction_date") val transactionDate: String, // yyyy-MM-dd @SerializedName("post_date") val postDate: String?, // yyyy-MM-dd @SerializedName("amount") val amount: Balance, @SerializedName("description") var description: TransactionDescription?, @SerializedName("budget_category") var budgetCategory: BudgetCategory, @SerializedName("included") var included: Boolean, @SerializedName("memo") var memo: String?, @SerializedName("account_id") val accountId: Long, @SerializedName("category") var category: CategoryDetails, @SerializedName("merchant") val merchant: MerchantDetails, @SerializedName("bill_id") var billId: Long?, @SerializedName("bill_payment_id") var billPaymentId: Long?, @SerializedName("user_tags") val userTags: List<String>?, @SerializedName("external_id") val externalId: String?, @SerializedName("goal_id") val goalId: Long?, @SerializedName("reference") val reference: String?, @SerializedName("reason") val reason: String? )
7
Kotlin
1
2
bb026203a43a2f7d06cc8dd557ae1be4697d067e
2,530
frollo-android-sdk
Apache License 2.0
androidApp/src/main/java/com/makeevrserg/kmmplayground/android/MainActivity.kt
makeevrserg
583,260,374
false
null
package com.makeevrserg.kmmplayground.android import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material.MaterialTheme import androidx.compose.material.lightColors import com.arkivanov.decompose.defaultComponentContext import com.makeevrserg.kmmplayground.di.ServiceLocator import com.makeevrserg.kmmplayground.navigation.root.component.DefaultRootComponent import com.makeevrserg.kmmplayground.presentation.root.RootContentComponent import com.makeevrserg.kmmplayground.shared.PlatformConfiguration class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // TODO Move into Application val configuration = PlatformConfiguration(applicationContext) ServiceLocator.platformConfigurationModule.initialize(configuration) val componentContext = defaultComponentContext() val rootComponent = DefaultRootComponent(componentContext) setContent { MaterialTheme(lightColors()) { RootContentComponent(rootComponent) } } } }
0
Kotlin
0
0
d45757f0d948a4bd36e190d1b696e1e7fdb4bffa
1,188
KMM-Playground
MIT License
src/main/kotlin/com/khekrn/jobpull/process/impl/AsyncJobProcessor.kt
khekrn
589,942,220
false
null
package com.khekrn.jobpull.process.impl import com.khekrn.jobpull.domain.JobEntity import com.khekrn.jobpull.executor.JobExecutor import com.khekrn.jobpull.process.JobProcessor import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import kotlin.coroutines.CoroutineContext @Component class AsyncJobProcessor( private val jobExecutor: JobExecutor ) : JobProcessor, CoroutineScope { private val logger = LoggerFactory.getLogger(AsyncJobProcessor::class.java) private val supervisorJob = SupervisorJob() private val channel = Channel<Deferred<JobEntity>>() private var queueCount = 0 private val mx = Mutex() private val maxWorkers: Int = 5 private val halfWorkers = 2 private var canContinue = true private val defaultWaitTime = 5L override val coroutineContext: CoroutineContext get() = Dispatchers.IO + supervisorJob fun start() = launch { logger.info("In Start") repeat(maxWorkers) { launch { logger.info("Launching worker $it") for (job in channel) { try { jobExecutor.runJob(job.await()) } catch (ex: Exception) { logger.error( "Error: Problem while processing job = {} - {}", job, ex.toString() ) } finally { mx.withLock { queueCount-- } } } } } logger.info("Return from start") } fun stop() { logger.info("In stop") supervisorJob.cancel() logger.info("Return from stop") } override suspend fun executeJob(jobEntity: JobEntity) { coroutineScope { launch { logger.info("In executeJob") try { channel.send(async { jobEntity }) } catch (ex: Exception) { logger.error("Problem while sending data to the channel = {}", ex.toString()) throw ex } finally { mx.withLock { queueCount++ } } logger.info("Return from executeJob") } } } override suspend fun isFull(): Boolean { logger.info("Current queue size = {}", queueCount) return (queueCount >= halfWorkers) } }
0
Kotlin
0
0
2aee695dde59c8aa991b2a8a960da6afa396fe24
2,751
jobpull
Apache License 2.0
app/src/main/java/com/maku/pombe/common/domain/model/latest/LatestDomainResponse.kt
ma-za-kpe
373,888,998
false
null
package com.maku.pombe.common.domain.model.latest data class LatestDomainResponse( val drinks: List<LatestDrink> )
18
Kotlin
2
5
e62294e8e5a25774f5955aa3565f62c4ff589cd5
119
Pombe
The Unlicense
kaal-presentation/src/main/kotlin/cz/eman/kaal/presentation/util/DiffCallbacks.kt
eManPrague
189,150,130
false
{"Shell": 2, "Gradle Kotlin DSL": 9, "Markdown": 2, "Java Properties": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "XML": 18, "Proguard": 5, "Kotlin": 65, "INI": 1, "Java": 4}
package cz.eman.kaal.presentation.util import android.annotation.SuppressLint import androidx.recyclerview.widget.DiffUtil /** * Implementation of [DiffUtil.Callback] using the [DiffUtil.ItemCallback] to compare items * * @param T Type of the item * * @param oldItems The list of old items * @param newItems The list of new items which replace the [oldItems] * @param differ The implementation of comparative callback * * @author [<NAME>.](mailto:<EMAIL>) * * @see DiffUtil.Callback * @see DiffUtil.ItemCallback * * @since 0.8.0 */ class DiffCallback<in T>( private val oldItems: List<T>, private val newItems: List<T>, private val differ: DiffUtil.ItemCallback<T> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = differ.areItemsTheSame(oldItems[oldItemPosition], newItems[newItemPosition]) override fun getOldListSize() = oldItems.size override fun getNewListSize() = newItems.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = differ.areContentsTheSame(oldItems[oldItemPosition], newItems[newItemPosition]) } /** * Callback for calculating the diff between two non-null items in a list. * * The [DiffUtil.ItemCallback.areContentsTheSame] uses the [equals] method to compare items. * This class should by used with `data class` or class that is overriding [equals] method. * * @param T Type of items to compare * * @author [<NAME>.](mailto:<EMAIL>) * * @see DiffUtil.ItemCallback */ abstract class DiffItemCallback<T> : DiffUtil.ItemCallback<T>() { @SuppressLint("DiffUtilEquals") final override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem } /** * @param T Type of items to compare * @param ID Type of item identifier * * @param idSelector Function for selecting the item identifier * * @return Instance of the [DiffItemCallback] * * @see DiffItemCallback */ inline fun <T, ID> createDiffer(crossinline idSelector: (T) -> ID): DiffUtil.ItemCallback<T> { return object : DiffItemCallback<T>() { override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = idSelector(oldItem) == idSelector(newItem) } }
7
Kotlin
7
7
292284e771e512d7b068ff51b0a4ac5215364013
2,248
kaal
MIT License
src/main/kotlin/io/github/serpro69/kfaker/provider/GratefulDead.kt
jianfang-kso
204,592,729
true
{"Kotlin": 189205, "Groovy": 1142}
package io.github.serpro69.kfaker.provider import io.github.serpro69.kfaker.* import io.github.serpro69.kfaker.dictionary.* /** * [FakeDataProvider] implementation for [CategoryName.GRATEFUL_DEAD] category. */ class GratefulDead internal constructor(fakerService: FakerService) : AbstractFakeDataProvider(fakerService) { override val categoryName = CategoryName.GRATEFUL_DEAD val players = resolve { fakerService.resolve(Faker, it, "players") } val songs = resolve { fakerService.resolve(Faker, it, "songs") } }
0
Kotlin
0
0
36a77fb520f82a1a0b43cf6cd08c54c2c7b9d6d6
529
kotlin-faker
MIT License
simpleKafka/src/main/kotlin/io/violabs/kafka/domain/Being.kt
violabs
519,553,455
false
{"Kotlin": 25801}
package io.violabs.kafka.domain interface Being { var name: String? }
0
Kotlin
0
0
1203a070e7053af1a9fdebdebb91ddd11dce95eb
72
mimir
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Arrow.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup public val BoldGroup.Arrow: ImageVector get() { if (_arrow != null) { return _arrow!! } _arrow = Builder(name = "Arrow", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 22.75f) curveTo(11.59f, 22.75f, 11.25f, 22.41f, 11.25f, 22.0f) verticalLineTo(20.0f) curveTo(11.25f, 19.59f, 11.59f, 19.25f, 12.0f, 19.25f) curveTo(12.41f, 19.25f, 12.75f, 19.59f, 12.75f, 20.0f) verticalLineTo(22.0f) curveTo(12.75f, 22.41f, 12.41f, 22.75f, 12.0f, 22.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 18.75f) curveTo(11.59f, 18.75f, 11.25f, 18.41f, 11.25f, 18.0f) verticalLineTo(16.0f) curveTo(11.25f, 15.59f, 11.59f, 15.25f, 12.0f, 15.25f) curveTo(12.41f, 15.25f, 12.75f, 15.59f, 12.75f, 16.0f) verticalLineTo(18.0f) curveTo(12.75f, 18.41f, 12.41f, 18.75f, 12.0f, 18.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 14.75f) curveTo(11.59f, 14.75f, 11.25f, 14.41f, 11.25f, 14.0f) verticalLineTo(11.0f) curveTo(11.25f, 6.73f, 14.73f, 3.25f, 19.0f, 3.25f) horizontalLineTo(22.0f) curveTo(22.41f, 3.25f, 22.75f, 3.59f, 22.75f, 4.0f) curveTo(22.75f, 4.41f, 22.41f, 4.75f, 22.0f, 4.75f) horizontalLineTo(19.0f) curveTo(15.55f, 4.75f, 12.75f, 7.55f, 12.75f, 11.0f) verticalLineTo(14.0f) curveTo(12.75f, 14.41f, 12.41f, 14.75f, 12.0f, 14.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 14.75f) curveTo(11.59f, 14.75f, 11.25f, 14.41f, 11.25f, 14.0f) verticalLineTo(11.0f) curveTo(11.25f, 7.55f, 8.45f, 4.75f, 5.0f, 4.75f) horizontalLineTo(2.0f) curveTo(1.59f, 4.75f, 1.25f, 4.41f, 1.25f, 4.0f) curveTo(1.25f, 3.59f, 1.59f, 3.25f, 2.0f, 3.25f) horizontalLineTo(5.0f) curveTo(9.27f, 3.25f, 12.75f, 6.73f, 12.75f, 11.0f) verticalLineTo(14.0f) curveTo(12.75f, 14.41f, 12.41f, 14.75f, 12.0f, 14.75f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0014f, 6.7514f) curveTo(3.8114f, 6.7514f, 3.6214f, 6.6814f, 3.4714f, 6.5314f) lineTo(1.4714f, 4.5314f) curveTo(1.1814f, 4.2414f, 1.1814f, 3.7614f, 1.4714f, 3.4714f) lineTo(3.4714f, 1.4714f) curveTo(3.7614f, 1.1814f, 4.2414f, 1.1814f, 4.5314f, 1.4714f) curveTo(4.8214f, 1.7614f, 4.8214f, 2.2414f, 4.5314f, 2.5314f) lineTo(3.0614f, 4.0014f) lineTo(4.5314f, 5.4714f) curveTo(4.8214f, 5.7614f, 4.8214f, 6.2414f, 4.5314f, 6.5314f) curveTo(4.3814f, 6.6814f, 4.1914f, 6.7514f, 4.0014f, 6.7514f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0014f, 6.7514f) curveTo(19.8114f, 6.7514f, 19.6214f, 6.6814f, 19.4714f, 6.5314f) curveTo(19.1814f, 6.2414f, 19.1814f, 5.7614f, 19.4714f, 5.4714f) lineTo(20.9414f, 4.0014f) lineTo(19.4714f, 2.5314f) curveTo(19.1814f, 2.2414f, 19.1814f, 1.7614f, 19.4714f, 1.4714f) curveTo(19.7614f, 1.1814f, 20.2414f, 1.1814f, 20.5314f, 1.4714f) lineTo(22.5314f, 3.4714f) curveTo(22.8214f, 3.7614f, 22.8214f, 4.2414f, 22.5314f, 4.5314f) lineTo(20.5314f, 6.5314f) curveTo(20.3814f, 6.6814f, 20.1914f, 6.7514f, 20.0014f, 6.7514f) close() } } .build() return _arrow!! } private var _arrow: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
6,088
VuesaxIcons
MIT License
app/src/main/java/com/dongyang/android/youdongknowme/ui/view/keyword/KeywordViewModel.kt
TeamDMU
470,044,500
false
{"Kotlin": 147602}
package com.dongyang.android.youdongknowme.ui.view.keyword import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.dongyang.android.youdongknowme.data.local.entity.KeywordEntity import com.dongyang.android.youdongknowme.data.repository.KeywordRepository import com.dongyang.android.youdongknowme.standard.base.BaseViewModel import com.google.firebase.messaging.FirebaseMessaging import kotlinx.coroutines.launch class KeywordViewModel( private val keywordRepository: KeywordRepository ) : BaseViewModel() { private val firebaseMessaging = FirebaseMessaging.getInstance() private val _isFirstLaunch: MutableLiveData<Boolean> = MutableLiveData(false) val isFirstLaunch: LiveData<Boolean> get() = _isFirstLaunch private val _localKeywordList: MutableLiveData<List<KeywordEntity>> = MutableLiveData() val localKeywordList: LiveData<List<KeywordEntity>> get() = _localKeywordList private val _checkKeywordList = mutableSetOf<String>() val checkKeywordList get() = _checkKeywordList fun getLocalKeywordList() { viewModelScope.launch { keywordRepository.getUserKeywords().collect { keywordList -> _localKeywordList.postValue(keywordList) } } } fun checkFirstLaunch() { if (keywordRepository.getIsFirstLaunch()) { _isFirstLaunch.value = true } } fun setFirstLaunch(isFirstLaunch: Boolean) { keywordRepository.setIsFirstLaunch(isFirstLaunch) } fun subscribeCheckedKeyword() { for (localKeyword in localKeywordList.value ?: emptyList()) { if (checkKeywordList.contains(localKeyword.name)) { // 선택했던 데이터를 중첩해서 바꾸면 효율성이 떨어지고, 파이어베이스 구독에 문제가 생길 수 있으므로 구독 여부도 함께 체크 if (!localKeyword.isSubscribe) { viewModelScope.launch { keywordRepository.updateUserKeywords(true, localKeyword.name) } firebaseMessaging.subscribeToTopic(localKeyword.englishName) } } else { if (localKeyword.isSubscribe) { viewModelScope.launch { keywordRepository.updateUserKeywords(false, localKeyword.name) } firebaseMessaging.unsubscribeFromTopic(localKeyword.englishName) } } } } fun setAllKeywords(keyword: List<String>) { _checkKeywordList.addAll(keyword) } fun setCheckedKeywords(keyword: String) { _checkKeywordList.add(keyword) } fun removeCheckedKeywords(keyword: String) { _checkKeywordList.remove(keyword) } }
9
Kotlin
0
8
caa3799dbf0c580b02251047add9a5e3abc5d96f
2,766
DMU-Android
Apache License 2.0
orbit/src/test/java/com/babylon/orbit/OrbitSpek.kt
amrfarid140
218,797,342
true
{"Kotlin": 81090}
/* * Copyright 2019 Babylon Partners Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.babylon.orbit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.TestCoroutineScope import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature @ExperimentalCoroutinesApi @FlowPreview internal class OrbitSpek : Spek({ val testCoroutineDispatcher = TestCoroutineDispatcher() val testScope = TestCoroutineScope() beforeEachTest { Dispatchers.setMain(testCoroutineDispatcher) } fun <T : Any> Flow<T>.startCollecting(result: MutableList<T>) = testScope.launch { collect { result.add(it) } } Feature("Orbit DSL") { Scenario("no flows") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with no flows") { middleware = createTestMiddleware {} orbitContainer = BaseOrbitContainer(middleware) } When("connecting to the middleware") { runBlocking { orbitContainer.orbit.collect { result.add(it) } } } Then("emits the initial state") { assertThat(result).isEqualTo(listOf(middleware.initialState)) } } Scenario("a flow that reduces an action") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with one reducer flow") { middleware = createTestMiddleware { perform("something") .on<Int>() .withReducer { State(currentState.id + event) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct end state") { assertThat(result).isEqualTo(listOf(State(42), State(47))) } } Scenario("a flow with a transformer and reducer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with a transformer and reducer") { middleware = createTestMiddleware { perform("something") .on<Int>() .transform { map { it.action * 2 } } .withReducer { State(currentState.id + event) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct end state") { assertThat(result).isEqualTo(listOf(State(42), State(52))) } } Scenario("a flow with two transformers and a reducer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with two transformers and a reducer") { middleware = createTestMiddleware { perform("something") .on<Int>() .transform { map { it.action * 2 } } .transform { map { it * 2 } } .withReducer { State(currentState.id + event) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct end state") { assertThat(result).isEqualTo(listOf(State(42), State(62))) } } Scenario("a flow with two transformers that is ignored") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with two transformer flows") { middleware = createTestMiddleware { perform("something") .on<Int>() .transform { map { it.action * 2 } } .transform { map { it * 2 } } .ignoringEvents() perform("unlatch") .on<Int>() .transform { this } .ignoringEvents() } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("emits just the initial state after connecting") { assertThat(result).isEqualTo(listOf(State(42))) } } Scenario("a flow with a transformer loopback and a flow with a transformer and reducer") { data class IntModified(val value: Int) lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() Given("A middleware with a transformer loopback flow and transform/reduce flow") { middleware = createTestMiddleware { perform("something") .on<Int>() .transform { map { it.action * 2 } } .loopBack { IntModified(event) } perform("something") .on<IntModified>() .transform { map { it.action.value * 2 } } .withReducer { State(currentState.id + event) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct end state") { assertThat(result).isEqualTo(listOf(State(42), State(62))) } } Scenario("a flow with two transformers with reducers") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() fun myReducer(event: Int): State { return State(event) } Given("A middleware with two transform/reduce flows") { middleware = createTestMiddleware { perform("something") .on<Int>() .transform { map { it.action * 2 } } .withReducer { myReducer(event) } perform("something") .on<Int>() .transform { map { it.action + 2 } } .withReducer { State(event) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending an action") { orbitContainer.orbit.startCollecting(result) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct series of states") { assertThat(result).isEqualTo(listOf(State(42), State(10), State(7))) } } Scenario("a flow with three transformers with reducers") { class One class Two class Three lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() val expectedOutput = mutableListOf(State(0)) Given("A middleware with three transform/reduce flows") { middleware = createTestMiddleware(State(0)) { perform("one") .on<One>() .withReducer { State(1) } perform("two") .on<Two>() .withReducer { State(2) } perform("three") .on<Three>() .withReducer { State(3) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending actions") { orbitContainer.orbit.startCollecting(result) for (i in 0 until 99) { val value = (i % 3) expectedOutput.add(State(value + 1)) runBlocking { orbitContainer.sendAction( when (value) { 0 -> One() 1 -> Two() 2 -> Three() else -> throw IllegalStateException("misconfigured test") } ) } } } Then("produces a correct series of states") { assertThat(result).isEqualTo(expectedOutput) } } Scenario("posting side effects as first transformer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() val sideEffects = mutableListOf<String>() Given("A middleware with a single post side effect as the first transformer") { middleware = createTestMiddleware(State(1)) { perform("something") .on<Int>() .postSideEffect { "${inputState.id + action}" } .withReducer { currentState.copy(id = currentState.id + 1) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending actions") { orbitContainer.orbit.startCollecting(result) orbitContainer.sideEffect.startCollecting(sideEffects) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct series of states") { assertThat(result).isEqualTo(listOf(State(1), State(2))) } And("posts a correct series of side effects") { assertThat(sideEffects).isEqualTo(listOf("6")) } } Scenario("posting side effects as non-first transformer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() val sideEffects = mutableListOf<String>() Given("A middleware with a single post side effect as the second transformer") { middleware = createTestMiddleware(State(1)) { perform("something") .on<Int>() .transform { map { it.action * 2 } } .postSideEffect { event.toString() } .withReducer { currentState.copy(id = currentState.id + 1) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending actions") { orbitContainer.orbit.startCollecting(result) orbitContainer.sideEffect.startCollecting(sideEffects) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct series of states") { assertThat(result).isEqualTo(listOf(State(1), State(2))) } And("posts a correct series of side effects") { assertThat(sideEffects).isEqualTo(listOf("10")) } } Scenario("non-posting side effects as first transformer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() val sideEffects = mutableListOf<String>() val sideEffectList = mutableListOf<String>() Given("A middleware with a single side effect as the first transformer") { middleware = createTestMiddleware(State(1)) { perform("something") .on<Int>() .sideEffect { sideEffectList.add("${inputState.id + action}") } .withReducer { currentState.copy(id = currentState.id + 1) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending actions") { orbitContainer.orbit.startCollecting(result) orbitContainer.sideEffect.startCollecting(sideEffects) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct series of states") { assertThat(result).isEqualTo(listOf(State(1), State(2))) } And("posts no side effects") { assertThat(sideEffects.isEmpty()).isTrue() } And("the side effect is executed") { assertThat(sideEffectList).containsExactly("6") } } Scenario("non-posting side effects as non-first transformer") { lateinit var middleware: Middleware<State, String> lateinit var orbitContainer: BaseOrbitContainer<State, String> val result = mutableListOf<State>() val sideEffects = mutableListOf<String>() val sideEffectList = mutableListOf<String>() Given("A middleware with a single side effect as the second transformer") { middleware = createTestMiddleware(State(1)) { perform("something") .on<Int>() .transform { map { it.action * 2 } } .sideEffect { sideEffectList.add(event.toString()) } .withReducer { currentState.copy(id = currentState.id + 1) } } orbitContainer = BaseOrbitContainer(middleware) } When("sending actions") { orbitContainer.orbit.startCollecting(result) orbitContainer.sideEffect.startCollecting(sideEffects) runBlocking { orbitContainer.sendAction(5) } } Then("produces a correct series of states") { assertThat(result).isEqualTo(listOf(State(1), State(2))) } And("posts no side effects") { assertThat(sideEffects.isEmpty()).isTrue() } And("the side effect is executed") { assertThat(sideEffectList).containsExactly("10") } } } afterEachTest { Dispatchers.resetMain() testScope.cleanupTestCoroutines() } }) @ExperimentalCoroutinesApi @FlowPreview private fun createTestMiddleware( initialState: State = State(42), block: OrbitsBuilder<State, String>.() -> Unit ) = middleware<State, String>(initialState) { this.apply(block) } private data class State(val id: Int)
0
Kotlin
0
0
ad01007844e89572f0ff60c99c1322fed8c0bd77
17,290
orbit-mvi
Apache License 2.0
src/main/kotlin/kossh/impl/SSHPowerShell.kt
jkelly467
142,593,902
false
{"Kotlin": 102111}
package kossh.impl import com.jcraft.jsch.ChannelShell import kossh.operations.PowerShellOperations import kossh.util.Producer import kossh.util.SSHTimeoutException import java.io.Closeable import java.io.OutputStream import java.io.PipedInputStream import java.io.PipedOutputStream import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.TimeUnit class SSHPowerShell(val ssh: SSH) : PowerShellOperations, Closeable { private var doInit = true private val defaultPrompt = """_T-:+""" val prompt = ssh.options.prompt ?: defaultPrompt val channel = ssh.jschsession().openChannel("shell") as ChannelShell val toServer: Producer val fromServer: ConsumerOutputStream init { channel.setPtyType("dumb") channel.setXForwarding(false) val pos = PipedOutputStream() val pis = PipedInputStream(pos) toServer = Producer(pos) channel.inputStream = pis fromServer = ConsumerOutputStream() channel.outputStream = fromServer channel.connect(ssh.options.connectTimeout.toInt()) } override fun close() { fromServer.close() toServer.close() channel.disconnect() } /** * Executes the given [cmd] and returns the result as a String */ @Synchronized override fun execute(cmd: String): String { sendCommand(cmd.replace('\n', ' ')) return fromServer.getResponse() } private fun shellInit() { toServer.send("""function prompt {"$prompt"}""") //Must read output twice to get through the set prompt command echo and then the initial prompt fromServer.getResponse() fromServer.getResponse() } private fun sendCommand(cmd: String) { if (doInit) { shellInit() doInit = false } toServer.send(cmd) } inner class ConsumerOutputStream: OutputStream() { private val resultsQueue = ArrayBlockingQueue<String>(10) private val consumerAppender = StringBuilder(8192) private val promptSize = prompt.length fun hasResponse() = resultsQueue.size > 0 fun getResponse(timeout: Long = ssh.options.timeout): String { if (timeout == 0L) { return resultsQueue.take() } else { val rval = resultsQueue.poll(timeout, TimeUnit.MILLISECONDS) if (rval == null) { toServer.brk() val output = resultsQueue.poll(5, TimeUnit.SECONDS) ?: "**no return value - could not break current operation**" throw SSHTimeoutException(output, "") } else { return rval } } } override fun write(b: Int) { if (b != 13) { //CR removed... CR is always added by JSch val ch = b.toChar() consumerAppender.append(ch) if (consumerAppender.endsWith(prompt)) { val promptIndex = consumerAppender.length - promptSize val firstNIndex = consumerAppender.indexOf("\n") val result = consumerAppender.substring(firstNIndex+1, promptIndex) resultsQueue.put(result) consumerAppender.setLength(0) } } } } }
4
Kotlin
12
29
fc4ab7654cd980672535dee028c623bdf4bd767a
3,381
kossh
MIT License
app/src/main/java/soup/stamp/ui/Screen.kt
fornewid
362,494,946
false
null
package soup.stamp.ui sealed class Screen { object OnBoarding : Screen() object Login : Screen() object Home : Screen() }
1
Kotlin
0
2
39016bd5a81c1bc56b2fcb4fe59c3739552d96fb
135
stamp
Apache License 2.0
app/src/main/java/com/breezefsmpriyankaenterprises/features/weather/api/WeatherRepo.kt
DebashisINT
650,050,446
false
null
package com.breezefsmpriyankaenterprises.features.weather.api import com.breezefsmpriyankaenterprises.base.BaseResponse import com.breezefsmpriyankaenterprises.features.task.api.TaskApi import com.breezefsmpriyankaenterprises.features.task.model.AddTaskInputModel import com.breezefsmpriyankaenterprises.features.weather.model.ForeCastAPIResponse import com.breezefsmpriyankaenterprises.features.weather.model.WeatherAPIResponse import io.reactivex.Observable class WeatherRepo(val apiService: WeatherApi) { fun getCurrentWeather(zipCode: String): Observable<WeatherAPIResponse> { return apiService.getTodayWeather(zipCode) } fun getWeatherForecast(zipCode: String): Observable<ForeCastAPIResponse> { return apiService.getForecast(zipCode) } }
0
Kotlin
0
0
e7c2a9f2e7c5f4ef2d8067a0b7fdf5bb752ebfbd
778
PriyankaEnterprises
Apache License 2.0
plugins/symbol-processor/src/main/kotlin/org/jetbrains/dataframe/ksp/DataFrameSymbolProcessorProvider.kt
Kotlin
259,256,617
false
null
package org.jetbrains.dataframe.ksp import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider class DataFrameSymbolProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return DataFrameSymbolProcessor(environment.codeGenerator, environment.logger) } }
8
Kotlin
3
82
db6726837c939358e63246a545b1582818c4badc
477
dataframe
Apache License 2.0