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
src/main/kotlin/org/quiltmc/loader/api/LoaderValue.kt
KiltMC
763,325,301
false
{"Kotlin": 78977, "Java": 848}
package org.quiltmc.loader.api import net.fabricmc.loader.api.metadata.CustomValue import xyz.bluspring.argyle.wrappers.QuiltLoaderValueArrayWrapper import xyz.bluspring.argyle.wrappers.QuiltLoaderValueObjectWrapper interface LoaderValue : CustomValue { fun type(): LType? fun location(): String? fun asObject(): LObject? fun asArray(): LArray? fun asString(): String? fun asNumber(): Number? fun asBoolean(): Boolean interface LObject : LoaderValue, MutableMap<String?, LoaderValue?> { fun toFabric(): CustomValue.CvObject { return QuiltLoaderValueObjectWrapper(this) } } interface LArray : LoaderValue, MutableList<LoaderValue> { fun toFabric(): CustomValue.CvArray { return QuiltLoaderValueArrayWrapper(this) } } enum class LType { OBJECT, ARRAY, STRING, NUMBER, BOOLEAN, NULL } override fun getAsArray(): CustomValue.CvArray? { return this.asArray()?.toFabric() } override fun getAsBoolean(): Boolean { return this.asBoolean() } override fun getAsNumber(): Number? { return this.asNumber() } override fun getAsObject(): CustomValue.CvObject? { return this.asObject()?.toFabric() } override fun getAsString(): String? { return this.asString() } override fun getType(): CustomValue.CvType { return CustomValue.CvType.valueOf(this.type()?.name ?: "NULL") } }
0
Kotlin
0
2
7c65fe265935b98534e3d1a36d6600df1a8f93bf
1,524
Argyle
Apache License 2.0
shared/domain/seasons/api/src/commonMain/kotlin/com/thomaskioko/tvmaniac/seasons/api/SeasonsRepository.kt
c0de-wizard
361,393,353
false
null
package com.thomaskioko.tvmaniac.seasons.api import com.thomaskioko.tvmaniac.core.db.SelectSeasonsByShowId import com.thomaskioko.tvmaniac.core.util.network.Resource import kotlinx.coroutines.flow.Flow interface SeasonsRepository { fun observeShowSeasons(traktId: Int): Flow<Resource<List<SelectSeasonsByShowId>>> }
3
Kotlin
8
81
9df7429257c4cff0346734392c89b8017b90bd45
323
tv-maniac
Apache License 2.0
hr-worker/src/main/kotlin/com/almeida/hrworker/HrWorkerApplication.kt
luc4salmeida
341,186,311
false
{"Kotlin": 24253}
package com.almeida.hrworker import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.netflix.eureka.EnableEurekaClient @EnableEurekaClient @SpringBootApplication class HrWorkerApplication fun main(args: Array<String>) { runApplication<HrWorkerApplication>(*args) }
0
Kotlin
0
0
91850bb66a5fc3ce8d734329d485d30edd1a1737
361
ms-spring
MIT License
walletconnectv2/src/main/kotlin/com/walletconnect/walletconnectv2/core/model/vo/sequence/SessionVO.kt
mobilekosmos
440,628,145
true
{"Kotlin": 442588}
package com.walletconnect.walletconnectv2.core.model.vo.sequence import com.walletconnect.walletconnectv2.core.model.type.Sequence import com.walletconnect.walletconnectv2.core.model.vo.ExpiryVO import com.walletconnect.walletconnectv2.core.model.vo.PublicKey import com.walletconnect.walletconnectv2.core.model.vo.TopicVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.common.MetaDataVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.common.SessionParticipantVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.pairing.params.PairingParamsVO import com.walletconnect.walletconnectv2.core.model.vo.clientsync.session.params.SessionParamsVO internal data class SessionVO( override val topic: TopicVO, override val expiry: ExpiryVO, val relayProtocol: String, val relayData: String?, val controllerKey: PublicKey? = null, val selfPublicKey: PublicKey, val selfMetaData: MetaDataVO? = null, val peerPublicKey: PublicKey? = null, val peerMetaData: MetaDataVO? = null, val accounts: List<String> = emptyList(), val methods: List<String>, val events: List<String>, val isAcknowledged: Boolean, ) : Sequence { val isPeerController: Boolean = peerPublicKey?.keyAsHex == controllerKey?.keyAsHex val isSelfController: Boolean = selfPublicKey.keyAsHex == controllerKey?.keyAsHex val chains: List<String> get() = getChainIds(accounts) internal companion object { @JvmSynthetic internal fun createUnacknowledgedSession( sessionTopic: TopicVO, proposal: PairingParamsVO.SessionProposeParams, selfParticipant: SessionParticipantVO, sessionExpiry: Long, accounts: List<String>, methods: List<String>, events: List<String>, ): SessionVO { return SessionVO( sessionTopic, ExpiryVO(sessionExpiry), relayProtocol = proposal.relays.first().protocol, relayData = proposal.relays.first().data, peerPublicKey = PublicKey(proposal.proposer.publicKey), peerMetaData = proposal.proposer.metadata, selfPublicKey = PublicKey(selfParticipant.publicKey), selfMetaData = selfParticipant.metadata, controllerKey = PublicKey(selfParticipant.publicKey), methods = methods, events = events, accounts = accounts, isAcknowledged = false ) } @JvmSynthetic internal fun createAcknowledgedSession( sessionTopic: TopicVO, settleParams: SessionParamsVO.SessionSettleParams, selfPublicKey: PublicKey, selfMetadata: MetaDataVO, ): SessionVO { return SessionVO( sessionTopic, ExpiryVO(settleParams.expiry), relayProtocol = settleParams.relay.protocol, relayData = settleParams.relay.data, peerPublicKey = PublicKey(settleParams.controller.publicKey), peerMetaData = settleParams.controller.metadata, selfPublicKey = selfPublicKey, selfMetaData = selfMetadata, controllerKey = PublicKey(settleParams.controller.publicKey), methods = settleParams.methods, events = settleParams.events, accounts = settleParams.accounts, isAcknowledged = true ) } fun getChainIds(accountIds: List<String>): List<String> { return accountIds.map { accountId -> accountId.split(":").take(2).joinToString(":") } } } }
0
Kotlin
0
0
e5b22bf3dea35cfa4c2c89c56e402bf97e7297bd
3,768
WalletConnectKotlinV2-1
Apache License 2.0
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/serialization/events/EventTypeSerializer.kt
benkuly
330,904,570
false
{"Kotlin": 4242169, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454}
package net.folivo.trixnity.core.serialization.events import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import net.folivo.trixnity.core.model.events.EventType class EventTypeSerializer( val mappings: EventContentSerializerMappings, ) : KSerializer<EventType> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("EventTypeSerializer", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): EventType { val type = decoder.decodeString() val mapping = mappings.message.find { it.type == type } ?: mappings.state.find { it.type == type } ?: mappings.ephemeral.find { it.type == type } ?: mappings.toDevice.find { it.type == type } ?: mappings.globalAccountData.find { it.type == type } ?: mappings.roomAccountData.find { it.type == type } return EventType(mapping?.kClass, type) } override fun serialize(encoder: Encoder, value: EventType) { encoder.encodeString(value.name) } }
0
Kotlin
3
30
96c656e1c20d60518b61884efe88ceaa9e899d75
1,296
trixnity
Apache License 2.0
app/src/main/java/me/pblinux/tvmaze/ui/theme/Theme.kt
pblinux
374,239,080
false
null
package me.pblinux.tvmaze.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import com.google.accompanist.systemuicontroller.rememberSystemUiController private val DarkColorPalette = darkColors( primary = Lavender, primaryVariant = DarkLavender, secondary = LightGreen, background = RichBlack, surface = Color.Transparent, ) private val LightColorPalette = lightColors( primary = Lavender, primaryVariant = DarkLavender, secondary = LightGreen, background = White, surface = Color.Transparent, ) @Composable fun TVMazeTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val systemUiController = rememberSystemUiController() val useDarkIcons = !darkTheme val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } val typography = if (darkTheme) { DarkTypography } else { LightTypography } SideEffect { systemUiController.setSystemBarsColor(Color.Transparent, darkIcons = useDarkIcons) } MaterialTheme( colors = colors, typography = typography, shapes = Shapes, content = content ) }
0
Kotlin
0
0
4f5644cb8fce8f97992df0d9ef96424f8780cffc
1,479
tvmaze
MIT License
implementation/src/main/java/pcb/uwu/unit/base/OunceUnit.kt
pedro-borges
105,442,770
false
{"Kotlin": 295141}
package pcb.uwu.unit.base import pcb.uwu.unit.base.OunceUnit.CONVERT object OunceUnit : MassUnit(symbol = "oz", singularName = "ounce", pluralName = "ounces", translationToCanonical = { it * CONVERT }, translationFromCanonical = { it / CONVERT }) { const val CONVERT = 28.349523125 }
10
Kotlin
0
2
4a2e79272dd83e3d47d8fac6677471add4be02ad
354
units
Apache License 2.0
authorization/src/main/java/com/fitless/authorization/registration/registration/domain/model/PasswordStatus.kt
SultanS1
767,628,796
false
{"Kotlin": 76907}
package com.fitless.authorization.registration.registration.domain.model enum class PasswordStatus { TOO_SHORT, OK, }
0
Kotlin
0
0
1db95bc29e02cfa548dac4c8dd51524daa6bac9a
126
FitnesX
MIT License
app/src/main/java/mil/nga/msi/datasource/port/PortMapItem.kt
ngageoint
588,211,646
false
null
package mil.nga.msi.datasource.port import androidx.room.ColumnInfo data class PortMapItem( @ColumnInfo(name = "port_number") val portNumber: Int, @ColumnInfo(name = "latitude") val latitude: Double, @ColumnInfo(name = "longitude") val longitude: Double )
0
Kotlin
0
0
233fec1388f5036c17ae5d99b8c0372e22630240
266
marlin-android
MIT License
app/src/main/java/com/dnnt/touch/ui/chat/ChatAdapter.kt
zhoujucheng
119,154,071
false
null
package com.dnnt.touch.ui.chat import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.dnnt.touch.BR import com.dnnt.touch.MyApplication import com.dnnt.touch.R import com.dnnt.touch.been.IMMsg import com.dnnt.touch.been.User import com.dnnt.touch.ui.base.BaseAdapter import com.dnnt.touch.ui.main.contact.ItemEvenHandler /** * Created by dnnt on 18-4-7. */ class ChatAdapter(var mUser: User) : BaseAdapter<IMMsg>() { companion object { const val TYPE_SEND = 1 const val TYPE_RECEIVE = 2 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<IMMsg> { val binding = if (viewType == TYPE_SEND){ DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context),R.layout.msg_send_item,parent,false) }else{ DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context),R.layout.msg_receive_item,parent,false) } return ChatViewHolder(binding) } override fun getItemViewType(position: Int) = //如果发送者是本用户,则使用msg_send_item布局,如果发送者是与本用户对话的用户则使用msg_receive_item if (mList[position].from == MyApplication.mUser?.id){ TYPE_SEND }else { TYPE_RECEIVE } override fun onBindViewHolder(holder: BaseViewHolder<IMMsg>, position: Int) { holder as ChatViewHolder if (mList[position].from == MyApplication.mUser?.id){ holder.bind(mList[position],MyApplication.mUser as User) }else { holder.bind(mList[position],mUser) } } override fun getItemEvenHandler(): ItemEvenHandler<IMMsg> = object : ItemEvenHandler<IMMsg>{ override fun onItemClick(view: View, item: IMMsg) {} } override fun getLayoutId(): Int = -1 class ChatViewHolder(binding: ViewDataBinding) : BaseViewHolder<IMMsg>(binding){ fun bind(item: IMMsg, user: User) { mBinding.setVariable(BR.item,item) mBinding.setVariable(BR.user,user) mBinding.executePendingBindings() } } }
0
Kotlin
0
1
b7a85731b95beb93c5f6f18482f4efbe38935d7d
2,217
Touch
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/aws/api/Resource.kt
atlassian-labs
314,701,354
false
{"Kotlin": 143884}
package com.atlassian.performance.tools.aws.api import java.util.concurrent.CompletableFuture /** * We need to [release] unnecessary AWS resources to keep our bills sustainable. * Code, which allocates these resources should release them after the resources are no longer necessary. * However, every process can fail and might not reach its release phase. That's why a secondary, external cleanup * process is necessary. The external processes are allowed to [release] the resource if it [isExpired]. */ interface Resource { fun isExpired(): Boolean fun release(): CompletableFuture<*> }
0
Kotlin
1
2
aa41e0843b6beaf4e4f711f5cce6839a1deffa82
604
aws-resources
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/BurstModeTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/BurstModeTwoTone") @file:JsNonModule package mui.icons.material @JsName("default") external val BurstModeTwoTone: SvgIconComponent
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
214
kotlin-wrappers
Apache License 2.0
smash-ranks-android/app/src/androidTest/java/com/garpr/android/features/deepLink/DeepLinkViewModelTest.kt
charlesmadere
41,832,700
true
null
package com.garpr.android.features.deepLink import com.garpr.android.data.models.Endpoint import com.garpr.android.data.models.Region import com.garpr.android.data.models.RegionsBundle import com.garpr.android.extensions.require import com.garpr.android.features.common.viewModels.BaseViewModelTest import com.garpr.android.features.deepLink.DeepLinkViewModel.Breadcrumb import com.garpr.android.features.home.HomeTab import com.garpr.android.misc.Schedulers import com.garpr.android.misc.Timber import com.garpr.android.repositories.RegionRepository import com.garpr.android.repositories.RegionsRepository import io.reactivex.Single import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.koin.core.inject class DeepLinkViewModelTest : BaseViewModelTest() { private lateinit var viewModel: DeepLinkViewModel private val regionsRepository = RegionsRepositoryOverride() protected val regionRepository: RegionRepository by inject() protected val schedulers: Schedulers by inject() protected val timber: Timber by inject() companion object { private val CHICAGO = Region( displayName = "Chicago", id = "chicago", endpoint = Endpoint.NOT_GAR_PR ) private val NORCAL = Region( displayName = "Norcal", id = "norcal", endpoint = Endpoint.GAR_PR ) private val NYC = Region( displayName = "NYC Metro Area", id = "nyc", endpoint = Endpoint.NOT_GAR_PR ) private val REGIONS_BUNDLE = RegionsBundle( regions = listOf(CHICAGO, NORCAL, NYC) ) private const val PLAYER_GINGER_ID = "57983b42e592573cf1845ff2" private const val PLAYER_SFAT_ID = "588852e8d2994e3bbfa52d88" private const val PLAYER_SWEDISH_DELIGHT_ID = "545b240b8ab65f7a95f74940" private const val PLAYER_GINGER = "https://www.notgarpr.com/#/chicago/players/$PLAYER_GINGER_ID" private const val PLAYER_SFAT = "https://www.garpr.com/#/norcal/players/$PLAYER_SFAT_ID" private const val PLAYER_SWEDISH_DELIGHT = "https://www.notgarpr.com/#/nyc/players/$PLAYER_SWEDISH_DELIGHT_ID" private const val PLAYERS_GEORGIA = "https://www.notgarpr.com/#/georgia/players" private const val PLAYERS_NORCAL = "https://www.garpr.com/#/norcal/players" private const val RANKINGS_NORCAL = "https://www.garpr.com/#/norcal/rankings" private const val RANKINGS_NYC = "https://www.notgarpr.com/#/nyc/rankings" private const val TOURNAMENT_APOLLO_III_ID = "58c72c801d41c8259fa1f8bf" private const val TOURNAMENT_NORCAL_VALIDATED_2_ID = "58a00514d2994e4d0f2e25a6" private const val TOURNAMENT_APOLLO_III = "https://www.notgarpr.com/#/nyc/tournaments/$TOURNAMENT_APOLLO_III_ID" private const val TOURNAMENT_NORCAL_VALIDATED_2 = "https://www.garpr.com/#/norcal/tournaments/$TOURNAMENT_NORCAL_VALIDATED_2_ID" private const val TOURNAMENTS_NORCAL = "https://www.garpr.com/#/norcal/tournaments" private const val TOURNAMENTS_NYC = "https://www.notgarpr.com/#/nyc/tournaments" } @Before override fun setUp() { super.setUp() viewModel = DeepLinkViewModel(regionRepository, regionsRepository, schedulers, timber) } @Test fun testBreadcrumbsWithChicagoAndNorcalValidated2Tournament() { regionRepository.region = CHICAGO viewModel.initialize(TOURNAMENT_NORCAL_VALIDATED_2) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(3, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val tournaments = breadcrumbs.require(1) as Breadcrumb.Tournaments assertEquals(NORCAL, tournaments.region) val tournament = breadcrumbs.require(2) as Breadcrumb.Tournament assertEquals(NORCAL, tournament.region) assertEquals(TOURNAMENT_NORCAL_VALIDATED_2_ID, tournament.tournamentId) } @Test fun testBreadcrumbsWithNorcalAndEmptyString() { regionRepository.region = NORCAL viewModel.initialize("") var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNull(breadcrumbs) assertNull(networkError) assertNotNull(urlParseError) } @Test fun testBreadcrumbsWithNorcalAndNull() { regionRepository.region = NORCAL viewModel.initialize(null) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNull(breadcrumbs) assertNull(networkError) assertNotNull(urlParseError) } @Test fun testBreadcrumbsWithNorcalAndGeorgiaPlayers() { regionRepository.region = NORCAL viewModel.initialize(PLAYERS_GEORGIA) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) // this should be null/empty because we're not including Georgia in the RegionsBundle assertTrue(breadcrumbs.isNullOrEmpty()) } @Test fun testBreadcrumbsWithNorcalAndGinger() { regionRepository.region = NORCAL viewModel.initialize(PLAYER_GINGER) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(3, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val players = breadcrumbs.require(1) as Breadcrumb.Players assertEquals(CHICAGO, players.region) val player = breadcrumbs.require(2) as Breadcrumb.Player assertEquals(CHICAGO, player.region) assertEquals(PLAYER_GINGER_ID, player.playerId) } @Test fun testBreadcrumbsWithNorcalAndNorcalRankings() { regionRepository.region = NORCAL viewModel.initialize(RANKINGS_NORCAL) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(1, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertEquals(HomeTab.HOME, home.initialPosition) } @Test fun testBreadcrumbsWithNorcalAndNorcalTournaments() { regionRepository.region = NORCAL viewModel.initialize(TOURNAMENTS_NORCAL) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(1, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertEquals(HomeTab.TOURNAMENTS, home.initialPosition) } @Test fun testBreadcrumbsWithNorcalAndNycRankings() { regionRepository.region = NORCAL viewModel.initialize(RANKINGS_NYC) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(2, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val players = breadcrumbs.require(1) as Breadcrumb.Rankings assertEquals(NYC, players.region) } @Test fun testBreadcrumbsWithNorcalAndSfat() { regionRepository.region = NORCAL viewModel.initialize(PLAYER_SFAT) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(3, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val players = breadcrumbs.require(1) as Breadcrumb.Players assertNull(players.region) val player = breadcrumbs.require(2) as Breadcrumb.Player assertNull(player.region) assertEquals(PLAYER_SFAT_ID, player.playerId) } @Test fun testBreadcrumbsWithNycAndNorcalPlayers() { regionRepository.region = NYC viewModel.initialize(PLAYERS_NORCAL) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(2, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val players = breadcrumbs.require(1) as Breadcrumb.Players assertEquals(NORCAL, players.region) } @Test fun testBreadcrumbsWithNycAndNycTournaments() { regionRepository.region = NYC viewModel.initialize(TOURNAMENTS_NYC) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(1, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertEquals(HomeTab.TOURNAMENTS, home.initialPosition) } @Test fun testBreadcrumbsWithNycAndNycApolloIiiTournament() { regionRepository.region = NYC viewModel.initialize(TOURNAMENT_APOLLO_III) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(2, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertEquals(HomeTab.TOURNAMENTS, home.initialPosition) val tournament = breadcrumbs.require(1) as Breadcrumb.Tournament assertNull(tournament.region) assertEquals(TOURNAMENT_APOLLO_III_ID, tournament.tournamentId) } @Test fun testBreadcrumbsWithNycAndSwedishDelight() { regionRepository.region = NYC viewModel.initialize(PLAYER_SWEDISH_DELIGHT) var breadcrumbs: List<Breadcrumb>? = null var networkError: Unit? = null var urlParseError: Unit? = null viewModel.breadcrumbsLiveData.observeForever { breadcrumbs = it } viewModel.networkErrorLiveData.observeForever { networkError = it } viewModel.urlParseErrorLiveData.observeForever { urlParseError = it } viewModel.fetchBreadcrumbs() assertNotNull(breadcrumbs) assertNull(networkError) assertNull(urlParseError) assertEquals(3, breadcrumbs?.size) val home = breadcrumbs.require(0) as Breadcrumb.Home assertNull(home.initialPosition) val players = breadcrumbs.require(1) as Breadcrumb.Players assertNull(players.region) val player = breadcrumbs.require(2) as Breadcrumb.Player assertNull(player.region) assertEquals(PLAYER_SWEDISH_DELIGHT_ID, player.playerId) } private class RegionsRepositoryOverride( internal var regionsBundle: RegionsBundle? = REGIONS_BUNDLE ) : RegionsRepository { override fun getRegions(): Single<RegionsBundle> { val bundle = regionsBundle return if (bundle == null) { Single.error(NullPointerException()) } else { Single.just(bundle) } } } }
0
Kotlin
0
9
151b2a0f9b4d38be60c3f73344ca444f17810bfd
16,492
smash-ranks-android
The Unlicense
java/io/jackbradshaw/otter/engine/core/EngineCoreModule.kt
jack-bradshaw
468,854,318
false
null
package io.jackbradshaw.otter.engine.core import dagger.Binds import dagger.Module @Module interface EngineCoreModule { @Binds fun bindEngine(impl: EngineCoreImpl): EngineCore }
4
Kotlin
0
7
1c132a27263a53828253ab76a35c8cd8fecce0ec
182
monorepo
MIT License
composeApp/src/desktopMain/kotlin/me/gustavolopezxyz/desktop/services/BackupService.kt
gusaln
736,062,721
false
{"Kotlin": 304914}
/* * Copyright (c) 2023. <NAME>. All rights reserved. */ package me.gustavolopezxyz.desktop.services import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.toLocalDateTime import me.gustavolopezxyz.common.data.Database import me.gustavolopezxyz.common.ext.datetime.currentTimeZone import me.gustavolopezxyz.common.logging.logger import me.gustavolopezxyz.desktop.Config import java.io.File import kotlin.io.path.Path import kotlin.io.path.absolutePathString import kotlin.math.max class BackupService(private val config: Config) { private val canMakeBackups get() = isBackupDirValid() private val backupDir get() = File(config.backupDirPath) private val backupsToKeep get() = config.backupsToKeep.toInt() private val logger by logger() private fun isBackupDirValid(): Boolean { return (backupDir.isDirectory || backupDir.mkdirs()) && backupDir.canRead() && backupDir.canWrite() } fun run() { makeBackup() deleteExcessBackups() } private fun listBackups(): List<Backup> { if (!canMakeBackups) { return emptyList() } return backupDir.walkTopDown() .maxDepth(1) .filter { it.isFile && it.name.matches(Regex("\\d+[.]\\d+[.]backup[.]db")) } .map { try { Backup(it) } catch (e: Throwable) { null } } .filterNotNull() .sortedBy { it.date } .toList() } fun makeBackup(): Backup? { val dataFile = File(config.dataFilePath) val backup = Backup() try { dataFile.copyTo(File(backup.path)) } catch (ex: Throwable) { return null } return backup.also { logger.info("Backup $it created") } } @OptIn(DelicateCoroutinesApi::class) fun deleteExcessBackups() { GlobalScope.launch(Dispatchers.IO) { logger.info("Checking for old backups") val backups = listBackups() if (backups.size < max(backupsToKeep, 1)) { return@launch } backups.dropLast(backupsToKeep).forEach { it.file.delete() logger.info("Backup $it deleted as excess") } } } data class Backup(val path: String, val date: LocalDateTime) { val file: File get() = File(path) } private fun Backup(file: File): Backup { val datePart = file.name.substringBefore('.') val date = LocalDateTime( datePart.substring(0, 4).toInt(), datePart.substring(4, 6).toInt(), datePart.substring(6, 8).toInt(), datePart.substring(8, 10).toInt(), datePart.substring(10, 12).toInt(), datePart.substring(12, 14).toInt(), ) return Backup(file.absolutePath, date) } private fun Backup(): Backup { val date = Clock.System.now().toLocalDateTime(currentTimeZone()) val backupPath = Path( config.backupDirPath, "%04d%02d%02d%02d%02d%02d.%d.backup.db".format( date.year, date.monthNumber, date.dayOfMonth, date.hour, date.minute, date.second, Database.Schema.version ) ) return Backup( backupPath.absolutePathString(), date = date ) } }
0
Kotlin
0
1
d1e56bb6dce4a0d9c430a8d4f6bcf67b1249ea52
3,651
wimm
MIT License
Fiber-Node/src/main/kotlin/app/fiber/project/node/configuration/RunConfiguration.kt
fiber-cloud
186,826,312
false
null
package app.fiber.project.node.configuration import app.fiber.project.node.software.proxy.ProxyGroupRegistry import app.fiber.project.node.software.server.ServerGroupRegistry data class RunConfiguration( val name: String, val proxyGroupRegistry: ProxyGroupRegistry, val serverGroupRegistry: ServerGroupRegistry )
0
Kotlin
2
7
65ba7b647f2bdd13ee0259555aaf45c7efc03f52
326
Fiber
MIT License
src/commonMain/kotlin/msw/extras/kxsmine/tree/decoding/tag/LongArrayTagDecoder.kt
RaphaelTarita
339,542,946
false
null
package msw.extras.kxsmine.tree.decoding.tag import msw.extras.kxsmine.tree.TagType import msw.extras.kxsmine.tree.decoding.payload.LongArrayPayloadDecoder import msw.extras.kxsmine.tree.decoding.payload.PayloadDecoder import msw.extras.kxsmine.tree.node.tag.LongArrayTagNode import msw.extras.kxsmine.tree.node.tag.TagNode public object LongArrayTagDecoder : TagDecoder<LongArray>() { override val type: TagType = TagType.LONGARRAY override val payloadDecoder: PayloadDecoder<LongArray> = LongArrayPayloadDecoder override val nodeSupplier: (String, LongArray) -> TagNode<LongArray> = ::LongArrayTagNode }
0
Kotlin
0
4
a4ee46c03114463787a0573c41395d02afb468ef
619
KXSmine
MIT License
core/src/main/java/com/depromeet/threedays/core/analytics/AnalyticsSdk.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.core.analytics import android.content.Context interface AnalyticsSdk { fun init(context: Context) fun isInitialized(): Boolean fun event(name:String, properties: Map<String, Any>) }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
228
three-days-android
MIT License
app/src/main/java/com/example/android/newsupdate/activity/TechActivity.kt
PrincePandey1
389,986,595
false
null
package com.example.android.newsupdate.activity import Adapter.HealthAdapter import Adapter.TechAdapter import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.newsupdate.R import dataclass.News import kotlinx.android.synthetic.main.activity_sign_up.* import kotlinx.android.synthetic.main.activity_tech.* import kotlinx.android.synthetic.main.content_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class TechActivity : BaseActivity() { lateinit var adapter: TechAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tech) setUpActionBar() getTechNews() btn_tech.setBackgroundColor(Color.BLUE) btn_health.setOnClickListener { startActivity(Intent(this,HealthActivity::class.java)) } btn_sport.setOnClickListener { startActivity(Intent(this,SportActivity::class.java)) } btn_business.setOnClickListener { startActivity(Intent(this,BusinessActivity::class.java)) } btn_media.setOnClickListener { startActivity(Intent(this,MediaActivity::class.java)) } btn_foreign.setOnClickListener { startActivity(Intent(this,ForeignActivity::class.java)) } } private fun setUpActionBar(){ setSupportActionBar(toolbar_tech_activity) val actionBar = supportActionBar if(actionBar != null){ actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setHomeAsUpIndicator(R.drawable.ic_back_white) } toolbar_tech_activity.setNavigationOnClickListener { onBackPressed() } } private fun getTechNews(){ showProgressDialog("Please wait..") val news = NewsService.newsInstance.getTechHeadlines("in","technology",1) news.enqueue(object: Callback<News>{ override fun onResponse(call: Call<News>, response: Response<News>) { hideProgressDialog() var news = response.body() Log.d("Success",news.toString()) if(news != null){ adapter = TechAdapter(this@TechActivity , news.articles ) rv_boards_list.adapter = adapter rv_boards_list.layoutManager = LinearLayoutManager(this@TechActivity) } } override fun onFailure(call: Call<News>, t: Throwable) { hideProgressDialog() Log.d("Failure","No Response From Server" , t) } }) } }
0
Kotlin
0
0
673f505e16ddb9ecbe9a9a92b91169df9c029e88
2,862
NewsUpdate
Apache License 2.0
src/test/kotlin/test_env/features/feature3/Feature3.kt
MobileUpLLC
499,206,031
false
{"Kotlin": 27728}
package test_env.features.feature3 import test_env.features.cycle.Cycle class Feature3 { val a = Cycle() }
0
Kotlin
0
4
9036d9987898ec821caed2da236a1a9e6925c280
113
Module-Graph-Gradle-Plugin
MIT License
composeApp/src/commonMain/kotlin/org/sam/app/domain/model/MoviesModel.kt
Usama-Aman
737,119,593
false
{"Kotlin": 52440, "Swift": 532, "JavaScript": 475, "HTML": 280}
package org.sam.app.domain.model import org.sam.app.common.Constants data class MoviesModel( var adult: Boolean? = null, var genreIds: List<Int?>? = null, var id: Int = -1, var originalLanguage: String? = null, var originalTitle: String? = null, var overview: String? = null, var posterPath: String? = null, var releaseDate: String? = null, var title: String? = null, ){ val fullPosterPath = "${Constants.IMAGE_URL}/$posterPath" }
0
Kotlin
0
0
98f3f06134bac50f7c502aebf2cc5f2e8332a924
473
compose-multiplatform-movies-app
Apache License 2.0
app/src/main/java/com/bed/seller/data/repositories/StorageRepositoryImpl.kt
bed72
674,410,644
false
{"Kotlin": 172874}
package com.bed.seller.data.repositories import javax.inject.Inject import kotlinx.coroutines.flow.Flow import com.bed.seller.data.datasources.StorageDatasource interface StorageRepository { suspend fun get(value: String): Flow<String> suspend fun save(value: Pair<String, String>) } class StorageRepositoryImpl @Inject constructor( private val datasource: StorageDatasource ) : StorageRepository { override suspend fun get(value: String): Flow<String> = datasource.get(value) override suspend fun save(value: Pair<String, String>) { datasource.save(value) } }
0
Kotlin
0
1
c17673d01f564400ee17d456315d3437ce078396
589
Hogwarts
MIT License
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/junit5assertionsconverter/AssertThat.after.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. import org.junit.Assert.* import org.hamcrest.Matcher import org.hamcrest.MatcherAssert import org.junit.jupiter.api.Test internal class Test1 { @Test fun testFirst(matcher: Matcher<String>) { MatcherAssert.assertThat("reason", "null", matcher) } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
428
intellij-community
Apache License 2.0
node-kotlin/src/jsMain/kotlin/node/childProcess/ExecFileSyncOptionsWithStringEncoding.kt
karakum-team
393,199,102
false
{"Kotlin": 7083457}
// Automatically generated - do not modify! package node.childProcess sealed external interface ExecFileSyncOptionsWithStringEncoding : ExecFileSyncOptions { override var encoding: Any? /* BufferEncoding */ }
0
Kotlin
6
26
3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18
215
types-kotlin
Apache License 2.0
app/src/main/java/com/mnnit/moticlubs/ui/components/channelscreen/PostGuidanceDialog.kt
CC-MNNIT
576,708,897
false
{"Kotlin": 563214, "Shell": 212}
package com.mnnit.moticlubs.ui.components.channelscreen import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.mnnit.moticlubs.domain.util.PublishedState import com.mnnit.moticlubs.ui.components.MarkdownText import com.mnnit.moticlubs.ui.theme.colorScheme @Composable fun PostGuidanceDialog( showDialog: PublishedState<Boolean>, modifier: Modifier = Modifier, ) { val scrollState = rememberScrollState() Dialog(onDismissRequest = { showDialog.value = false }, DialogProperties(usePlatformDefaultWidth = false)) { Box( modifier = modifier .fillMaxWidth(0.9f) .wrapContentHeight() .padding(16.dp) .clip(RoundedCornerShape(24.dp)) .background(colorScheme.background), ) { Column( modifier = Modifier .padding(16.dp) .heightIn(128.dp, 512.dp), ) { MarkdownText( markdown = MKD_GUIDE, modifier = Modifier .fillMaxWidth() .verticalScroll(scrollState), color = contentColorFor(backgroundColor = colorScheme.background), ) } } } } private const val MKD_GUIDE = "<align><h2>Markdown Formatting</h2></align>\n\n" + "Here are some syntax you can use for formatting your post.\n\n" + "### Headers: \n" + "```\n" + "# Header 1\n" + "## Header 2\n" + "### Header 3\n" + "```\n" + "# Header 1\n" + "## Header 2\n" + "### Header 3\n\n" + "--------------------------\n" + "### Styles:\n" + "```\n" + "**bold** or 'B' icon\n" + "_italics_ or 'I' icon\n" + "~~strike~~ or 'T' icon\n" + "```\n" + "**bold**\n" + "_italics_\n" + "~~strike~~\n\n" + "-------------------------\n" + "### Listing:\n" + "```\n" + "- item 1\n" + "- item 2\n" + "- item 3\n" + "```\n" + "- item 1\n" + "- item 2\n" + "- item 3\n\n" + "-------------------------\n" + "### Table:\n" + "```\n" + "| Name | Reg No |\n" + "|----|----|\n" + "|Shashank|20204184|\n" + "|Hitesh|20204085|\n" + "|Amit|20204022|\n" + "```\n" + "| Name | Reg No |\n" + "|----|----|\n" + "|Shashank|20204184|\n" + "|Hitesh|20204085|\n" + "|Amit|20204022|\n\n" + "-------------------------\n" + "### Links:\n" + "```\n" + "[link_name](url)\n" + "Eg:\n" + "[Rick Roll](https://youtu.be/xvFZjo5PgG0)\n" + "```\n" + "[Rick Roll](https://youtu.be/xvFZjo5PgG0)\n\n" + "-------------------------\n" + "### Quoting:\n" + "```\n" + "> This is quoted text\n" + "```\n" + "> This is quoted text\n\n" + "**Good Luck !**"
0
Kotlin
1
1
6be5e334b94b0bc89c3f33bd6f581fd739e14786
3,614
MotiClubs
MIT License
gradle-plugins/core/src/main/kotlin/com/varabyte/kobweb/gradle/core/kmp/MultiplatformExtensions.kt
varabyte
389,223,226
false
null
package com.varabyte.kobweb.gradle.core.kmp import org.gradle.api.Action import org.gradle.api.NamedDomainObjectCollection import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.plugin.KotlinTarget val Project.kotlin get() = extensions.getByName("kotlin") as KotlinMultiplatformExtension fun Project.kotlin(configure: Action<KotlinMultiplatformExtension>): Unit = (this as ExtensionAware).extensions.configure("kotlin", configure) fun KotlinMultiplatformExtension.sourceSets(configure: Action<NamedDomainObjectContainer<KotlinSourceSet>>): Unit = (this as ExtensionAware).extensions.configure("sourceSets", configure) val Project.buildTargets: NamedDomainObjectCollection<KotlinTarget> get() = kotlin.targets
100
Kotlin
31
771
fcda655ef9ba10512377c925ccde758517bf12ea
955
kobweb
Apache License 2.0
Android/app/src/main/java/ru/alexskvortsov/policlinic/domain/states/records/list/Record.kt
AlexSkvor
244,438,301
false
null
package ru.alexskvortsov.policlinic.domain.states.records.list import org.threeten.bp.LocalDateTime import ru.alexskvortsov.policlinic.data.storage.database.entities.* data class Record( val consultationId: String, val doctorEntity: DoctorEntity, val patientEntity: PatientEntity, val competenceEntity: CompetenceEntity, val createdUserEntity: UserEntity, val startTimePlan: LocalDateTime, val endTimePlan: LocalDateTime, val reason: String, val cancelled: Boolean, val proceduresUsed: List<ProcedureEntity>?, val startTimeFact: LocalDateTime?, val endTimeFact: LocalDateTime?, val doctorNotes: String? ) { val passed get() = endTimeFact != null || cancelled }
0
Kotlin
0
0
5cc6a10a1399ee08643e69308afd4626938882b0
726
polyclinic
Apache License 2.0
githubuserfavoriteapps/src/main/java/com/ferdyhaspin/githubuserfavoriteapps/User.kt
ferdyhaspin
262,837,173
false
null
package com.ferdyhaspin.githubuserfavoriteapps /** * Created by ferdyhaspin on 22/05/20. * Copyright (c) 2020 Github User Apps All rights reserved. */ data class User( val image: String, val username: String )
0
Kotlin
0
0
d129fbec737258e0582bb5abe01e54b54916fad0
221
github-user
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day8/Day8Puzzle1.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day8 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver class Day8Puzzle1 : PuzzleSolver { companion object { private val uniqueNumbersOfSegments = setOf( 2, // Digit 1 3, // Digit 7 4, // Digit 4 7 // Digit 8 ) } override fun solve(inputLines: Sequence<String>) = countDigitsWithUniqueNumberOfSegments(inputLines).toString() private fun countDigitsWithUniqueNumberOfSegments(digitSignalsAndReading: Sequence<String>) = digitSignalsAndReading .filter { it.isNotBlank() } .mapNotNull { it.split(" | ").lastOrNull() } .map { it.trim().split(' ') } .map { it.map { activeSegments -> activeSegments.length in uniqueNumbersOfSegments } } .flatMap { it } .count { it } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
869
AdventOfCode2021
Apache License 2.0
vertx-pac4j-async-demo/src/test/kotlin/org/pac4j/async/vertx/authserver/DummyAuthServer.kt
millross
77,838,408
false
{"Java": 588457, "Kotlin": 44532, "HTML": 448}
package org.pac4j.async.vertx.authserver import io.vertx.core.Vertx import io.vertx.core.http.HttpMethod import io.vertx.core.http.HttpServer import io.vertx.ext.web.Router import io.vertx.kotlin.coroutines.awaitResult import org.pac4j.async.vertx.AUTH_SERVER_PROFILE_ENDPOINT import org.pac4j.async.vertx.AUTH_SERVER_TOKEN_ENDPOINT import org.pac4j.async.vertx.authserver.handler.ProfileRequestHandler import org.pac4j.async.vertx.authserver.handler.TokenRequestHandler import org.slf4j.Logger import org.slf4j.LoggerFactory /** * */ class DummyAuthServer(val vertx: Vertx) { companion object { val LOG: Logger = LoggerFactory.getLogger(DummyAuthServer.javaClass) } suspend fun start() { val context = vertx.orCreateContext val router = Router.router(vertx) with(router) { route(HttpMethod.GET, AUTH_SERVER_TOKEN_ENDPOINT).handler(TokenRequestHandler(vertx, context)) route(HttpMethod.GET, AUTH_SERVER_PROFILE_ENDPOINT).handler(ProfileRequestHandler(vertx, context)) } LOG.info("Starting server") awaitResult<HttpServer> { vertx.createHttpServer().requestHandler(router::accept).listen(9292, it) } LOG.info("Server started") } }
1
null
1
1
bb4a5e03f279b2e50f228340b9607d1f1a3901a7
1,243
pac4j-async
Apache License 2.0
ServerChat/src/Server.kt
miroso22
326,056,790
false
{"Kotlin": 10361}
import java.net.ServerSocket private const val port = 6667 private val server = ServerSocket(port) val clients = ArrayList<Client>() fun main() { while (true) { val client = server.accept() clients.add(Client(client)) } }
0
Kotlin
0
1
8c108b206cf0c2f3a0b28086cf309966a4fe2213
248
Chat_Kotlin
MIT License
app/src/main/java/com/dicoding/submission/githubuser/others/DataStorePreferences.kt
muhammadhassan3
405,538,513
false
null
package com.dicoding.submission.githubuser.others import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class DataStorePreferences private constructor(private val datastore: DataStore<Preferences>) { fun getDarkMode(): Flow<Boolean> { return datastore.data.map { preferences -> preferences[DARK_MODE_KEY] ?: false } } suspend fun setDarkMode(value: Boolean) { datastore.edit { preferences -> preferences[DARK_MODE_KEY] = value } } companion object { private val DARK_MODE_KEY = booleanPreferencesKey("dark_mode") @Volatile private var INSTANCE: DataStorePreferences? = null fun getInstance(dataStore: DataStore<Preferences>): DataStorePreferences { return INSTANCE ?: synchronized(this) { val instance = DataStorePreferences(dataStore) INSTANCE = instance instance } } } }
0
Kotlin
0
0
c5434dc97345178d32fe4cace4502a67f5b19934
1,197
github-api-example
MIT License
app/src/main/java/com/github/drewstephensdesigns/astrofeed/ui/about/AboutFragment.kt
drewstephensdesigns
742,485,540
false
{"Kotlin": 126788}
package com.github.drewstephensdesigns.astrofeed.ui.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.github.drewstephensdesigns.astrofeed.R import com.github.drewstephensdesigns.astrofeed.databinding.FragmentAboutBinding import com.google.android.material.transition.MaterialSharedAxis class AboutFragment : Fragment() { private var _binding: FragmentAboutBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentAboutBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { initUI() } private fun initUI(){ with(binding){ textAboutCompany.text = getString(R.string.title_company) textAboutDeveloper.text = getString(R.string.title_about) textAboutCompany.setOnClickListener { findNavController().navigate(R.id.navigation_company) } textAboutDeveloper.setOnClickListener { findNavController().navigate(R.id.navigation_about_dev) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
a343890d6917abd5d9e7ad9362b35501264e80c6
1,723
AstroFeed
MIT License
src/main/kotlin/com/github/w0819/game/uhc/recipes/Bloodlust.kt
w0819
418,112,809
false
{"Kotlin": 174492}
package com.github.w0819.game.uhc.recipes import com.github.w0819.game.util.ExtraUltimates import org.bukkit.Material import org.bukkit.NamespacedKey import org.bukkit.inventory.ItemStack object Bloodlust : ExtraUltimates( NamespacedKey.minecraft("bloodlust"), Bloodlust, 100000, "BloodCraft","Invention" ) { init { shape( "121", "131", "141" ) setIngredient('1', Material.REDSTONE_BLOCK) setIngredient('2',Material.DIAMOND) setIngredient('3',Material.DIAMOND_SWORD) setIngredient('4',Material.EXPERIENCE_BOTTLE) } object Bloodlust : Item( ItemStack(Material.DIAMOND_SWORD) ) }
0
Kotlin
2
3
d3aa47c6be6330a10e6689ff89f161eccee25563
704
UHC_System
MIT License
core/src/main/kotlin/com/weedow/spring/data/search/descriptor/SearchDescriptorRegistry.kt
gitter-badger
310,432,814
true
{"Kotlin": 400259, "Java": 16661, "ANTLR": 2692}
package com.weedow.spring.data.search.descriptor /** * Register the [SearchDescriptor]s. */ interface SearchDescriptorRegistry { /** * Adds a [SearchDescriptor] in the registry. * * @param searchDescriptor [SearchDescriptor] to be added */ fun addSearchDescriptor(searchDescriptor: SearchDescriptor<*>) }
0
null
0
0
d6a214fa822bd2b694625358c157d2bf715de27e
337
spring-data-search
MIT License
foregroundsdk/src/main/java/com/rotemati/foregroundsdk/internal/connectivity/ConnectivityHandler.kt
ironSource
302,076,724
false
null
package com.rotemati.foregroundsdk.internal.connectivity import android.content.Context import com.rotemati.foregroundsdk.internal.extensions.getConnectivityManager internal interface ConnectivityHandler { fun register(context: Context) fun unregister(context: Context) val connected: Boolean val blocked: Boolean val roaming: Boolean fun setConnectivityListener(listener: ConnectivityChangedListener) fun isRoamingOld(context: Context): Boolean { val connectivityManager = context.getConnectivityManager() val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected && networkInfo.isRoaming } } internal interface ConnectivityChangedListener { fun onChanged() }
1
Kotlin
0
19
01a38f1f30a705a03b24731bac1909bcb16d1d75
738
alleviate
The Unlicense
app/src/main/java/com/example/napasin/SettingActivity.kt
iqbalanandra
816,686,689
false
{"Kotlin": 59322}
package com.example.napasin import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.BottomAppBar import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.text.font.FontWeight import kotlinx.coroutines.delay class SettingActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { MyApp5(currentActivity = "SettingActivity") } } } @Composable fun MyApp5(currentActivity: String) { Scaffold( bottomBar = { BottomNavigationBar4(currentActivity) } ) { MainContent4(Modifier.padding(it)) } } @Composable fun MainContent4(modifier: Modifier = Modifier) { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ){ Text( text = "Settings", fontFamily = poppinsFamily, fontWeight = FontWeight.SemiBold, color = Color(0xFF004A76), modifier = Modifier.padding(top = 24.dp, bottom = 24.dp), fontSize = 36.sp // Add padding between items ) Spacer(modifier = Modifier.height(40.dp)) // Language Setting Row( modifier = Modifier.fillMaxWidth().padding(top = 36.dp), horizontalArrangement = Arrangement.SpaceBetween ){ Row{ Image( painter = painterResource(id = R.drawable.group7), contentDescription = "Language", modifier = Modifier .padding(bottom = 16.dp) .size(60.dp) ) Text( text = "Language", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(start = 36.dp), fontSize = 14.sp ) } Row{ Text( text = "English", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF787878), modifier = Modifier.padding(start = 36.dp), fontSize = 10.sp ) IconButton(onClick = {}) { Icon( painter = painterResource(id = R.drawable.ic_arrow), contentDescription = "Language", tint = Color.White ) } } } // Notification Setting Row( modifier = Modifier.fillMaxWidth().padding(top = 36.dp), horizontalArrangement = Arrangement.SpaceBetween ){ Row{ Image( painter = painterResource(id = R.drawable.group8), contentDescription = "Notification", modifier = Modifier .padding(bottom = 16.dp) .size(60.dp) ) Text( text = "Notification", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(start = 36.dp), fontSize = 14.sp ) } Row{ IconButton(onClick = {}) { Icon( painter = painterResource(id = R.drawable.ic_arrow), contentDescription = "Notification", tint = Color.White ) } } } // DarkMode Setting Row( modifier = Modifier.fillMaxWidth().padding(top = 36.dp), horizontalArrangement = Arrangement.SpaceBetween ){ Row{ Image( painter = painterResource(id = R.drawable.group9), contentDescription = "Dark Mode", modifier = Modifier .padding(bottom = 16.dp) .size(60.dp) ) Text( text = "Dark Mode", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(start = 36.dp), fontSize = 14.sp ) } Row{ Text( text = "Off", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF787878), modifier = Modifier.padding(start = 36.dp), fontSize = 10.sp ) IconButton(onClick = {}) { Icon( painter = painterResource(id = R.drawable.ic_arrow), contentDescription = "Dark Mode", tint = Color.White ) } } } // Microphone Setting Row( modifier = Modifier.fillMaxWidth().padding(top = 36.dp), horizontalArrangement = Arrangement.SpaceBetween ){ Row{ Image( painter = painterResource(id = R.drawable.group10), contentDescription = "Microphone", modifier = Modifier .padding(bottom = 16.dp) .size(60.dp) ) Text( text = "Microphone", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(start = 36.dp), fontSize = 14.sp ) } Row{ IconButton(onClick = {}) { Icon( painter = painterResource(id = R.drawable.ic_arrow), contentDescription = "Microphone", tint = Color.White ) } } } // Help Setting Row( modifier = Modifier.fillMaxWidth().padding(top = 36.dp), horizontalArrangement = Arrangement.SpaceBetween ){ Row{ Image( painter = painterResource(id = R.drawable.group11), contentDescription = "Help", modifier = Modifier .padding(bottom = 16.dp) .size(60.dp) ) Text( text = "Help", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(start = 36.dp), fontSize = 14.sp ) } Row{ IconButton(onClick = {}) { Icon( painter = painterResource(id = R.drawable.ic_arrow), contentDescription = "Help", tint = Color.White ) } } } Column(){ Text( text = "Privacy Policy", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(36.dp), fontSize = 14.sp ) Text( text = "Terms & Conditions", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(36.dp), fontSize = 14.sp ) Text( text = "FAQ & Support", fontFamily = poppinsFamily, fontWeight = FontWeight.Normal, color = Color(0xFF004A76), modifier = Modifier.padding(36.dp), fontSize = 14.sp ) } } } @Composable fun BottomNavigationBar4(currentActivity: String) { val context = LocalContext.current BottomAppBar( modifier = Modifier .fillMaxWidth(), containerColor = Color(0xFF0086F6), contentPadding = PaddingValues(0.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = { if (currentActivity != "HomeActivity") { val navigate = Intent(context, HomeActivity::class.java) context.startActivity(navigate) } }) { Icon( painter = painterResource(id = R.drawable.ic_home), contentDescription = "Home", tint = Color.White ) } IconButton(onClick = { if (currentActivity != "MeditationActivity") { val navigate = Intent(context, MeditationActivity::class.java) context.startActivity(navigate) } }) { Icon( painter = painterResource(id = R.drawable.ic_favorite), contentDescription = "Favorite", tint = Color.White ) } IconButton(onClick = { if (currentActivity != "GuideActivity") { val navigate = Intent(context, GuideActivity::class.java) context.startActivity(navigate) } }) { Icon( painter = painterResource(id = R.drawable.ic_list), contentDescription = "List", tint = Color.White ) } IconButton(onClick = { if (currentActivity != "SettingActivity") { val navigate = Intent(context, SettingActivity::class.java) context.startActivity(navigate) } }) { Icon( painter = painterResource(id = R.drawable.ic_settings), contentDescription = "Settings", tint = Color.White ) } } } } @Preview(showBackground = true) @Composable fun GreetingPreview8() { MyApp5(currentActivity = "SettingActivity") }
0
Kotlin
0
0
1e74eb4654487612a15e4d5f3c937cacdd05df47
12,949
napasin
MIT License
microapp/gamepage/src/main/java/bruhcollective/itaysonlab/microapp/gamepage/ui/components/GamePeriodicChallengesCards.kt
iTaysonLab
525,967,051
false
{"Kotlin": 203833}
package bruhcollective.itaysonlab.microapp.gamepage.ui.components import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import bruhcollective.itaysonlab.jetisoft.uikit.SectionHeader import bruhcollective.itaysonlab.microapp.gamepage.R import bruhcollective.itaysonlab.microapp.gamepage.ui.components.datacards.PeriodicChallengePagerCard import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import ubi.PeriodicListQuery @OptIn(ExperimentalPagerApi::class) @Composable fun GamePeriodicChallengesCards ( data: List<PeriodicListQuery.Challenge>, ) { SectionHeader(header = stringResource(id = R.string.periodic_challenges)) HorizontalPager( count = data.size, contentPadding = PaddingValues(horizontal = 16.dp), itemSpacing = 8.dp ) { page -> val node = data[page].periodicChallengeData PeriodicChallengePagerCard( icon = node.imageUrl, name = node.name, type = node.type, progress = node.viewer.meta.progressPercentage, progressFormatted = node.viewer.meta.formattedProgress, totalFormatted = node.formattedValue, inProgress = node.viewer.meta.isInProgress ) } Spacer(modifier = Modifier.height(8.dp)) }
0
Kotlin
0
13
f651cfc692852c378c9cd3b4e41d8aa1b5a76eb5
1,581
jetisoft
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2018/calendar/day11/Day11.kt
peckb1
433,943,215
false
{"Kotlin": 818902}
package me.peckb.aoc._2018.calendar.day11 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.Int.Companion.MIN_VALUE class Day11 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { input -> val serialNumber = input.toInt() val fuelCells = Array(300) { Array(300) { 0 } } repeat(300) { y -> repeat(300) { x -> fuelCells[y][x] = calculatePowerLevel(x, y, serialNumber) } } var maxFuelCellArea: Pair<Pair<Int, Int>, Int> = (-1 to -1) to MIN_VALUE (1 until 299).forEach { y -> (1 until 299).forEach { x -> val sum = (y - 1..y + 1).sumOf { yy -> (x - 1..x + 1).sumOf { xx -> fuelCells[yy][xx] } } if (sum > maxFuelCellArea.second) maxFuelCellArea = (x - 1 to y - 1) to sum } } maxFuelCellArea.first } fun partTwo(filename: String) = generatorFactory.forFile(filename).readOne { input -> val serialNumber = input.toInt() val summedAreaFuelCells = Array(300) { Array(300) { 0 } } repeat(300) { y -> repeat(300) { x -> val ul = summedAreaFuelCells.get(y - 1, x - 1) ?: 0 val ur = summedAreaFuelCells.get(y - 1, x) ?: 0 val ll = summedAreaFuelCells.get(y, x - 1) ?: 0 val lr = calculatePowerLevel(x, y, serialNumber) summedAreaFuelCells[y][x] = lr + ll + ur - ul } } var maxFuelCellArea = Triple((-1 to -1), MIN_VALUE, 0) (1..300).forEach { gridSize -> (0 until 300 - gridSize).forEach { y -> (0 until 300 - gridSize).forEach { x -> val ul = summedAreaFuelCells[y][x] val ur = summedAreaFuelCells[y][x + gridSize] val ll = summedAreaFuelCells[y + gridSize][x] val lr = summedAreaFuelCells[y + gridSize][x + gridSize] val sum = lr + ul - ur - ll if (sum > maxFuelCellArea.second) maxFuelCellArea = Triple(x + 1 to y + 1, sum, gridSize) } } } Triple(maxFuelCellArea.first.first, maxFuelCellArea.first.second, maxFuelCellArea.third) } private fun calculatePowerLevel(x: Int, y: Int, serialNumber: Int): Int { val rackID = (x + 10) var powerLevel = rackID * y powerLevel += serialNumber powerLevel *= rackID val hundredsDigit = (powerLevel % 1000) / 100 return hundredsDigit - 5 } private fun <T> Array<Array<T>>.get(y: Int, x: Int): T? { return if (y in (indices) && x in (this[y].indices)) { this[y][x] } else { null } } }
0
Kotlin
1
4
5507219c37a97500eed6e455520038549237b504
2,639
advent-of-code
MIT License
kminiorm/src/jvmMain/kotlin/com/soywiz/kminiorm/typer/Typer.kt
korlibs
211,091,810
false
{"Kotlin": 204714}
package com.soywiz.kminiorm.typer import com.soywiz.kminiorm.* import com.soywiz.kminiorm.convert.* import com.soywiz.kminiorm.internal.* import java.math.* import java.time.* import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.LinkedHashMap import kotlin.reflect.* import kotlin.reflect.full.* import kotlin.reflect.jvm.* open class Typer private constructor( internal val keepTypes: Set<KClass<*>> = setOf(), internal val untypersByClass: Map<KClass<*>, Typer.(Any) -> Any> = mapOf(), internal val typersByClass: Map<KClass<*>, Typer.(Any, KType) -> Any> = mapOf(), //val USE_JIT: Boolean = true val USE_JIT: Boolean = false ) { companion object { private val EMPTY_BYTE_ARRAY = byteArrayOf() } val generateFactory: GenerateFactory by lazy { GenerateFactory() } constructor() : this(keepTypes = setOf()) private fun copy( keepTypes: Set<KClass<*>> = this.keepTypes, untypersByClass: Map<KClass<*>, Typer.(Any) -> Any> = this.untypersByClass, typersByClass: Map<KClass<*>, Typer.(Any, KType) -> Any> = this.typersByClass ) = Typer(keepTypes, untypersByClass, typersByClass) fun withKeepType(type: KClass<*>) = copy(keepTypes = keepTypes + type) inline fun <reified T> withKeepType() = withKeepType(T::class) fun <T : Any> withUntyper(clazz: KClass<T>, handler: Typer.(T) -> Any?) = copy(untypersByClass = untypersByClass + mapOf(clazz to (handler as Typer.(Any) -> Any))) fun <T : Any> withTyper(clazz: KClass<T>, handler: Typer.(Any, KType) -> T) = copy(typersByClass = typersByClass + mapOf(clazz to (handler as Typer.(Any, KType) -> Any))) inline fun <reified T : Any> withUntyper(noinline handler: Typer.(T) -> Any) = withUntyper(T::class, handler) inline fun <reified T : Any> withTyper(noinline handler: Typer.(Any, KType) -> T) = withTyper(T::class, handler) inline fun <reified T : Any> withTyperUntyper(noinline typer: Typer.(Any, KType) -> T, noinline untyper: Typer.(T) -> Any = { it }) = withTyper(T::class, typer).withUntyper(T::class, untyper) fun untype(instance: Any): Any { val clazz = instance::class if (clazz in keepTypes) return instance val untyper = untypersByClass[clazz] if (untyper != null) return untyper(instance) return when (instance) { is Number -> instance is Boolean -> instance is String -> instance is ByteArray -> instance.toBase64() is Map<*, *> -> instance.entries.associate { (key, value) -> key?.let { untype(it) } to value?.let { untype(it) } } is Iterable<*> -> instance.map { it?.let { untype(it) } } else -> { when { clazz.java.isEnum -> (instance as Enum<*>).name else -> LinkedHashMap<String, Any?>().also { out -> for (prop in clazz.memberPropertiesCached) { prop.isAccessible = true if (prop.findAnnotation<DbIgnore>() == null && !prop.isLateinit) { out[prop.name] = (prop as KProperty1<Any?, Any?>).get(instance)?.let { untype(it) } } } } } } } } fun untypeNull(instance: Any?): Any? = when (instance) { null -> null else -> untype(instance) } private fun _toIterable(instance: Any?): Iterable<Any?> { if (instance == null) return listOf() if (instance is Iterable<*>) return instance as Iterable<Any?> TODO() } private fun _toMap(instance: Any?): Map<Any?, Any?> { if (instance == null) return LinkedHashMap() if (instance is Map<*, *>) return instance as Map<Any?, Any?> if (instance is Iterable<*>) return (instance as Iterable<Map.Entry<Any?, Any?>>).toList().associate { it.key to it.value } val props = instance::class.memberPropertiesAccessibleCached val out = LinkedHashMap<Any?, Any?>(props.size) for (prop in props) out[prop.name] = (prop as KProperty1<Any?, Any?>).get(instance) return out } @OptIn(ExperimentalStdlibApi::class) inline fun <reified T> type(instance: Any?): T = type(instance, typeOf<T>()) fun <T : Any> type(instance: Any?, type: KClass<T>): T = type(instance, type.starProjectedType) fun <T> type(instance: Any?, targetType: KType): T = _type(instance, targetType) as T private fun _type(instance: Any?, targetType: KType): Any? = if (USE_JIT) _typeJit(instance, targetType) else _typeReflection(instance, targetType) private fun _typeJit(instance: Any?, targetType: KType): Any? = generateFactory.get(targetType).convert(instance) private val subClassCacheNumber = HashMap<KClass<*>, Boolean>() private val subClassCacheMap = HashMap<KClass<*>, Boolean>() private val subClassCacheIterable = HashMap<KClass<*>, Boolean>() private val subClassCacheList = HashMap<KClass<*>, Boolean>() private val subClassCacheSet = HashMap<KClass<*>, Boolean>() private val primaryConstructorCache = HashMap<KClass<*>, KFunction<*>>() private val <T : Any> KClass<T>.primaryConstructorCached: KFunction<*> get() = primaryConstructorCache.getOrPut(this) { this.primaryConstructor ?: constructors.firstOrNull { it.isAccessible && it.parameters.isNotEmpty() } ?: constructors.firstOrNull { it.isAccessible } ?: constructors.firstOrNull() ?: error("Class $this doesn't have public constructors") } private val propertiesCache = HashMap<KClass<*>, List<KProperty1<*, *>>>() private val <T : Any> KClass<T>.memberPropertiesCached: List<KProperty1<T, *>> get() = propertiesCache.getOrPut(this) { this.memberProperties.toList() } as List<KProperty1<T, *>> private val propertiesAccessibleCache = HashMap<KClass<*>, List<KProperty1<*, *>>>() private val <T : Any> KClass<T>.memberPropertiesAccessibleCached: List<KProperty1<T, *>> get() = propertiesAccessibleCache.getOrPut(this) { this.memberPropertiesCached.filter { it.isAccessible } } as List<KProperty1<T, *>> private val mutablePropertiesCache = HashMap<KClass<*>, List<KMutableProperty1<*, *>>>() private val <T : Any> KClass<T>.memberMutablePropertiesCached: List<KMutableProperty1<T, *>> get() = mutablePropertiesCache.getOrPut(this) { this.memberPropertiesCached.filterIsInstance<KMutableProperty1<*, *>>().toList() } as List<KMutableProperty1<T, *>> private fun _typeReflection(instance: Any?, targetType: KType): Any? { if (targetType.isMarkedNullable && instance == null) return null val targetClass = targetType.jvmErasure val targetClassJava = targetClass.java val typer = typersByClass[targetClass] if (typer != null && instance != null) return typer(instance, targetType) val instanceClass = if (instance != null) instance::class else null return when (targetClass) { instanceClass -> instance Boolean::class -> when (instance) { is Boolean -> instance is Number -> instance.toDouble() != 0.0 is String -> instance != "" else -> true } String::class -> instance.toString() ByteArray::class -> { when (instance) { is ByteArray -> instance is String -> instance.fromBase64() else -> _toIterable(instance).map { (it as Number).toByte() }.toTypedArray() } } IntArray::class -> (instance as? IntArray) ?: _toIterable(instance).map { (it as Number).toInt() }.toTypedArray() LongArray::class -> (instance as? LongArray) ?: _toIterable(instance).map { (it as Number).toLong() }.toTypedArray() FloatArray::class -> (instance as? FloatArray) ?: _toIterable(instance).map { (it as Number).toFloat() }.toTypedArray() DoubleArray::class -> (instance as? DoubleArray) ?: _toIterable(instance).map { (it as Number).toDouble() }.toTypedArray() Any::class -> instance else -> when { subClassCacheNumber.getOrPut(targetClass) { targetClass.isSubclassOf(Number::class) } -> when (targetClass) { Byte::class -> (instance as? Number)?.toByte() ?: instance.toString().toIntOrNull()?.toByte() ?: 0.toByte() Short::class -> (instance as? Number)?.toShort() ?: instance.toString().toIntOrNull()?.toShort() ?: 0.toShort() Char::class -> (instance as? Number)?.toChar() ?: instance.toString().toIntOrNull()?.toChar() ?: 0.toChar() Int::class -> (instance as? Number)?.toInt() ?: instance.toString().toIntOrNull() ?: 0 Long::class -> (instance as? Number)?.toLong() ?: instance.toString().toLongOrNull() ?: 0L Float::class -> (instance as? Number)?.toFloat() ?: instance.toString().toFloatOrNull() ?: 0f Double::class -> (instance as? Number)?.toDouble() ?: instance.toString().toDoubleOrNull() ?: 0.0 BigInteger::class -> (instance as? BigInteger) ?: instance.toString().toBigInteger() BigDecimal::class -> (instance as? BigDecimal) ?: instance.toString().toBigDecimal() else -> TODO() } subClassCacheMap.getOrPut(targetClass) { targetClass.isSubclassOf(Map::class) } -> { val paramKey = targetType.arguments.first().type ?: Any::class.starProjectedType val paramValue = targetType.arguments.last().type ?: Any::class.starProjectedType _toMap(instance).entries.associate { (key, value) -> key?.let { _type(it, paramKey) } to value?.let { _type(it, paramValue) } } } subClassCacheIterable.getOrPut(targetClass) { targetClass.isSubclassOf(Iterable::class) } -> { val param = targetType.arguments.first().type ?: Any::class.starProjectedType val info = _toIterable(instance).map { it?.let { type<Any>(it, param) } } when { subClassCacheList.getOrPut(targetClass) { targetClass.isSubclassOf(List::class) } -> info.toMutableList() subClassCacheSet.getOrPut(targetClass) { targetClass.isSubclassOf(Set::class) } -> info.toMutableSet() else -> error("Don't know how to convert iterable into $targetClass") } } targetClassJava.isEnum -> { val constants = targetClassJava.enumConstants constants.firstOrNull { (it as Enum<*>).name == instance } ?: (if (targetType.isMarkedNullable) null else (constants.firstOrNull() ?: error("No constants"))) } else -> { val data = _toMap(instance) val constructor = targetClass.primaryConstructorCached val processedKeys = linkedSetOf<String?>() val params = constructor.parameters.map { val value = data[it.name] val type = it.type processedKeys += it.name value?.let { _type(value, type) } ?: DbTyper.createDefault(type) } val instance = kotlin.runCatching { constructor.call(*params.toTypedArray()) }.getOrNull() ?: error("Can't instantiate object $targetClass") for (prop in targetClass.memberMutablePropertiesCached) { processedKeys += prop.name kotlin.runCatching { (prop as KMutableProperty1<Any?, Any?>).set(instance, data[prop.name]) } } if (instance is ExtrinsicData) { for (key in data.keys) { if (key in processedKeys) continue instance[key.toString()] = data[key] } } instance } } } } @OptIn(ExperimentalStdlibApi::class) inline fun <reified T> createDefault(): Any? = createDefault(typeOf<T>()) fun createDefault(type: KType): Any? = if (USE_JIT) createDefaultJit(type) else createDefaultReflection(type) fun createDefaultJit(type: KType): Any? { if (type.isMarkedNullable) return null return generateFactory.get(type.jvmErasure.java).convertDefault() } fun createDefaultReflection(type: KType): Any? { if (type.isMarkedNullable) return null val clazz = type.jvmErasure val jclazz = clazz.java return when (clazz) { Unit::class -> Unit Boolean::class -> false Float::class -> 0f Double::class -> 0.0 Byte::class -> 0.toByte() Short::class -> 0.toShort() Char::class -> 0.toChar() ByteArray::class -> EMPTY_BYTE_ARRAY Int::class -> 0 Long::class -> 0L String::class -> "" List::class, ArrayList::class -> arrayListOf<Any?>() Map::class, HashMap::class, MutableMap::class -> mutableMapOf<Any?, Any?>() DbRef::class -> DbRef<DbTableElement>(ByteArray(12)) DbKey::class -> DbKey(ByteArray(12)) DbIntRef::class -> DbIntRef<DbTableIntElement>() DbStringRef::class -> DbStringRef<DbTableStringElement>() DbIntKey::class -> DbIntKey(0L) Date::class -> Date(0L) UUID::class -> UUID(0L, 0L) LocalDate::class -> LocalDate.MIN else -> { if (jclazz.isEnum) { jclazz.enumConstants.first() } else { val constructor = clazz.primaryConstructorCached val defaultParameters = constructor.valueParameters.map { createDefault(it.type) }.toTypedArray() constructor.call(*defaultParameters) } } } } private val typerForClassCacheJit = HashMap<KClass<*>, ClassTyper<*>>() private val typerForClassCacheNoJit = HashMap<KClass<*>, ClassTyper<*>>() fun <T : Any> typerForClass(clazz: KClass<T>, jit: Boolean = USE_JIT): ClassTyper<T> = when { jit -> typerForClassCacheJit.getOrPut(clazz) { JitClassTyper(generateFactory, clazz) } else -> typerForClassCacheNoJit.getOrPut(clazz) { val ctyper = typersByClass[clazz] if (ctyper != null) { ReflectTyperClassTyper(this, clazz, ctyper) } else { ReflectClassTyper(this, clazz) } } } as ClassTyper<T> } abstract class ClassTyper<T: Any>(val clazz: KClass<T>) { val propertiesByName = clazz.memberProperties.associateBy { it.name } abstract fun type(value: Any?): T open fun typeOrNull(value: Any?): T? = if (value == null) null else type(value) fun <R> getProperty(first: KProperty<R>): KProperty1<T, R> { @Suppress("UNCHECKED_CAST") return (propertiesByName[first.name] as? KProperty1<T, R>?) ?: error("Can't find property $first") } } class JitClassTyper<T: Any>(val factory: GenerateFactory, clazz: KClass<T>) : ClassTyper<T>(clazz) { private val gen = factory.get(clazz) override fun type(value: Any?): T = gen.convert(value) } class ReflectClassTyper<T: Any>(val typer: Typer, clazz: KClass<T>) : ClassTyper<T>(clazz) { override fun type(value: Any?): T = typer.type<T>(value ?: Unit, clazz) as T } class ReflectTyperClassTyper<T: Any>(val typer: Typer, clazz: KClass<T>, private val ctyper: ((Typer, Any, KType) -> Any)) : ClassTyper<T>(clazz) { private val ktype = clazz.starProjectedType override fun type(value: Any?): T = ctyper(typer, value ?: Unit, ktype) as T }
1
Kotlin
1
9
66a7accee207e8bbacfc9feee421d489e9d4a5e7
16,254
kminiorm
MIT License
TestGeopagos/app/src/main/java/com/rest/testgeopagos/view/adapters/InstallmentsAdapter.kt
restriglio
235,801,044
false
{"Markdown": 16, "Text": 1, "Ignore List": 18, "Java Properties": 21, "Gradle": 49, "Shell": 16, "Batchfile": 16, "YAML": 15, "Proguard": 9, "XML": 321, "Java": 94, "INI": 8, "Kotlin": 121, "JSON": 1}
package com.rest.testgeopagos.view.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.rest.testgeopagos.databinding.PartialInstallmentItemBinding import com.rest.testgeopagos.model.Installment import com.rest.testgeopagos.utils.SharedPreferencesManager import kotlin.reflect.KFunction0 class InstallmentsAdapter( private val context : Context, private val list: List<Installment.PayerCosts>, private val onClickMethod: KFunction0<Unit> ) : RecyclerView.Adapter<InstallmentsAdapter.InstallmentsViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InstallmentsViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = PartialInstallmentItemBinding.inflate(inflater) return InstallmentsViewHolder(binding) } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: InstallmentsViewHolder, position: Int) { val item = list[position] holder.bind(item, View.OnClickListener { SharedPreferencesManager.with(context).saveInstallment(item.recommendedMessage) onClickMethod() }) } class InstallmentsViewHolder(private val binding: PartialInstallmentItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Installment.PayerCosts, listener: View.OnClickListener) { with(binding) { recommendedMessage.text = item.recommendedMessage binding.container.setOnClickListener(listener) } } } }
1
null
1
1
8f5a3bcbb3b191143c598e9627bc2f881dda6a0b
1,725
views-widgets-samples
Apache License 2.0
androidext/src/test/java/com/david/hackro/androidext/ExampleUnitTest.kt
David-Hackro
260,338,201
false
null
package com.david.hackro.androidext
0
Kotlin
4
24
09ca20d311cc9a770013123dc91d5e0802242e45
36
Covid
MIT License
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/SampleEntity.kt
Maccimo
18,582,736
false
null
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage interface SampleEntity : WorkspaceEntity { val booleanProperty: Boolean val stringProperty: String val stringListProperty: List<String> val fileProperty: VirtualFileUrl val children: List<@Child ChildSampleEntity> val nullableData: String? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: SampleEntity, ModifiableWorkspaceEntity<SampleEntity>, ObjBuilder<SampleEntity> { override var booleanProperty: Boolean override var entitySource: EntitySource override var stringProperty: String override var stringListProperty: List<String> override var fileProperty: VirtualFileUrl override var children: List<ChildSampleEntity> override var nullableData: String? } companion object: Type<SampleEntity, Builder>() { operator fun invoke(booleanProperty: Boolean, entitySource: EntitySource, stringProperty: String, stringListProperty: List<String>, fileProperty: VirtualFileUrl, init: (Builder.() -> Unit)? = null): SampleEntity { val builder = builder() builder.booleanProperty = booleanProperty builder.entitySource = entitySource builder.stringProperty = stringProperty builder.stringListProperty = stringListProperty builder.fileProperty = fileProperty init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SampleEntity, modification: SampleEntity.Builder.() -> Unit) = modifyEntity(SampleEntity.Builder::class.java, entity, modification) //endregion interface ChildSampleEntity : WorkspaceEntity { val data: String val parentEntity: SampleEntity? //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: ChildSampleEntity, ModifiableWorkspaceEntity<ChildSampleEntity>, ObjBuilder<ChildSampleEntity> { override var data: String override var entitySource: EntitySource override var parentEntity: SampleEntity? } companion object: Type<ChildSampleEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildSampleEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ChildSampleEntity, modification: ChildSampleEntity.Builder.() -> Unit) = modifyEntity(ChildSampleEntity.Builder::class.java, entity, modification) //endregion abstract class MyData(val myData: MyContainer) class MyConcreteImpl(myData: MyContainer) : MyData(myData) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is MyConcreteImpl) return false return this.myData == other.myData } override fun hashCode(): Int { return this.myData.hashCode() } } data class MyContainer(val info: String) interface SecondSampleEntity : WorkspaceEntity { val intProperty: Int //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: SecondSampleEntity, ModifiableWorkspaceEntity<SecondSampleEntity>, ObjBuilder<SecondSampleEntity> { override var intProperty: Int override var entitySource: EntitySource } companion object: Type<SecondSampleEntity, Builder>() { operator fun invoke(intProperty: Int, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SecondSampleEntity { val builder = builder() builder.intProperty = intProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SecondSampleEntity, modification: SecondSampleEntity.Builder.() -> Unit) = modifyEntity(SecondSampleEntity.Builder::class.java, entity, modification) //endregion interface SourceEntity : WorkspaceEntity { val data: String val children: List<@Child ChildSourceEntity> //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: SourceEntity, ModifiableWorkspaceEntity<SourceEntity>, ObjBuilder<SourceEntity> { override var data: String override var entitySource: EntitySource override var children: List<ChildSourceEntity> } companion object: Type<SourceEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SourceEntity, modification: SourceEntity.Builder.() -> Unit) = modifyEntity(SourceEntity.Builder::class.java, entity, modification) //endregion interface ChildSourceEntity : WorkspaceEntity { val data: String val parentEntity: SourceEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: ChildSourceEntity, ModifiableWorkspaceEntity<ChildSourceEntity>, ObjBuilder<ChildSourceEntity> { override var data: String override var entitySource: EntitySource override var parentEntity: SourceEntity } companion object: Type<ChildSourceEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildSourceEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ChildSourceEntity, modification: ChildSourceEntity.Builder.() -> Unit) = modifyEntity(ChildSourceEntity.Builder::class.java, entity, modification) //endregion interface PersistentIdEntity : WorkspaceEntityWithPersistentId { val data: String override val persistentId: LinkedListEntityId get() { return LinkedListEntityId(data) } //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: PersistentIdEntity, ModifiableWorkspaceEntity<PersistentIdEntity>, ObjBuilder<PersistentIdEntity> { override var data: String override var entitySource: EntitySource } companion object: Type<PersistentIdEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): PersistentIdEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: PersistentIdEntity, modification: PersistentIdEntity.Builder.() -> Unit) = modifyEntity(PersistentIdEntity.Builder::class.java, entity, modification) //endregion
1
null
1
1
aa7852d5f99bd8dcd44f6cb430e4e9b94eb96dd1
7,820
intellij-community
Apache License 2.0
framework/src/main/java/com/addeeandra/akm/framework/util/MessageBag.kt
addeeandra
314,520,818
false
null
package com.addeeandra.akm.framework.util import android.content.Context import android.view.View import android.widget.Toast import androidx.annotation.IntDef /** * WIP */ class MessageBag { private var mSnackbarContainer: View? = null private var mTitle: String? = null private var mMessage: String? = null private var mPositiveTextButton: String? = "OK" private var mNegativeTextButton: String? = "Cancel" private var mCancelable: Boolean? = null private var mType: Int = 0 private var mContext: Context? = null fun show() { when (mType) { TYPE_MSG_TOAST -> { Toast.makeText(mContext, mMessage, Toast.LENGTH_SHORT).show() return } TYPE_MSG_SUCCESS -> { } TYPE_MSG_FAILURE -> { } TYPE_MSG_ALERT -> { } TYPE_MSG_CONFIRMATION -> { } } } companion object { // a simple toast message, which will only shown up at debuggable running apps. const val TYPE_MSG_TOAST = 0 // shows a simple message with SnackBar const val TYPE_MSG_SUCCESS = 1 // shows a simple message with SnackBar const val TYPE_MSG_FAILURE = 2 // shows a dialog with Yes / OK only button const val TYPE_MSG_ALERT = 3 // shows a dialog with Yes / Cancel buttons const val TYPE_MSG_CONFIRMATION = 4 } @IntDef(value = [TYPE_MSG_TOAST, TYPE_MSG_SUCCESS, TYPE_MSG_FAILURE, TYPE_MSG_ALERT, TYPE_MSG_CONFIRMATION]) annotation class MessageType interface ToastMessageAdapter { fun showToast(containerView: View, message: String, duration: Int = Toast.LENGTH_SHORT) } interface SuccessMessageAdapter { fun showSuccessMessage( containerView: View, title: String?, message: String?, confirmText: String? ) } interface FailureMessageAdapter { fun showFailureMessage( containerView: View, title: String?, message: String?, confirmText: String? ) } interface AlertMessageAdapter { fun showAlertMessage( containerView: View, title: String?, message: String?, confirmText: String? ) } interface ConfirmationMessageAdapter { fun showConfirmMessage( containerView: View, title: String?, message: String?, confirmText: String? ) } class Builder { private val messageBag: MessageBag = MessageBag() fun setSnackbarContainer(v: View): Builder { messageBag.mSnackbarContainer = v return this } fun setTitle(text: String): Builder { messageBag.mTitle = text return this } fun setMessage(text: String): Builder { messageBag.mMessage = text return this } fun setCancelable(isCancelable: Boolean): Builder { messageBag.mCancelable = isCancelable return this } fun setPositiveTextButton(text: String): Builder { messageBag.mPositiveTextButton = text return this } fun setNegativeTextButton(text: String): Builder { messageBag.mNegativeTextButton = text return this } fun setMessageType(@MessageType type: Int): Builder { messageBag.mType = type return this } fun build(): MessageBag { return messageBag } } }
0
Kotlin
0
2
2f870c40f7ed43265e6bbe69846f96dae518da5b
3,710
akm-framework
MIT License
library/src/test/java/com/shopapp/shopify/api/adapter/CategoryListAdapterTest.kt
rubygarage
121,784,219
false
null
package com.shopapp.shopify.api.adapter import com.shopapp.shopify.JodaTimeAndroidRule import com.shopapp.shopify.StorefrontMockInstantiator import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner.Silent::class) class CategoryListAdapterTest { @Rule @JvmField var jodaTimeAndroidRule = JodaTimeAndroidRule() @Test fun shouldAdaptFromListCollectionStorefrontToListCategory() { val shop = StorefrontMockInstantiator.newShop() val categoryList = CategoryListAdapter.adapt(shop) assertEquals(StorefrontMockInstantiator.DEFAULT_LIST_SIZE, categoryList.size) } }
4
Kotlin
31
51
33d10ee580d12ad94042566677a4607ab21d236b
737
shopapp-shopify-android
Apache License 2.0
json-schema-validator/src/commonMain/kotlin/io/github/optimumcode/json/schema/extension/ExternalAssertionContext.kt
OptimumCode
665,024,908
false
{"Kotlin": 701490, "Shell": 919}
package io.github.optimumcode.json.schema.extension import io.github.optimumcode.json.pointer.JsonPointer import io.github.optimumcode.json.schema.ExperimentalApi @ExperimentalApi public interface ExternalAssertionContext { /** * A JSON pointer to the currently validating element in the object that is being validated */ public val objectPath: JsonPointer /** * The [ExternalAnnotationCollector] associated with currently validating element */ public val annotationCollector: ExternalAnnotationCollector }
7
Kotlin
3
33
20ad6e2e642ad7c98554c1788392bbbfc423c068
529
json-schema-validator
MIT License
app/src/main/kotlin/com/kondenko/pocketwaka/screens/stats/model/TabsElevationState.kt
Kondenko
95,912,101
false
null
package com.kondenko.pocketwaka.screens.stats.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class TabsElevationState( private val elevationStates: MutableMap<Int, Boolean> = mutableMapOf(), var currentTabIndex: Int = 0 ) : Parcelable { var isElevated: Boolean get() = elevationStates[currentTabIndex] ?: false set(value) { elevationStates[currentTabIndex] = value } }
2
null
7
58
6f1423415e2a23f12626ac67c9afb25f2df9e302
472
pocketwaka
MIT License
app/src/main/kotlin/com/kondenko/pocketwaka/screens/stats/model/TabsElevationState.kt
Kondenko
95,912,101
false
null
package com.kondenko.pocketwaka.screens.stats.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class TabsElevationState( private val elevationStates: MutableMap<Int, Boolean> = mutableMapOf(), var currentTabIndex: Int = 0 ) : Parcelable { var isElevated: Boolean get() = elevationStates[currentTabIndex] ?: false set(value) { elevationStates[currentTabIndex] = value } }
2
null
7
58
6f1423415e2a23f12626ac67c9afb25f2df9e302
472
pocketwaka
MIT License
intellij.tools.ide.starter.junit5/src/com/intellij/ide/starter/junit5/config/LogEnvironmentVariables.kt
JetBrains
499,194,001
false
{"Kotlin": 555547, "C++": 3610, "Makefile": 713}
package com.intellij.ide.starter.junit5.config import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.config.ConfigurationStorage import com.intellij.ide.starter.config.logEnvironmentVariables import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext open class LogEnvironmentVariables : BeforeAllCallback, BeforeEachCallback { private fun configure() { if (CIServer.instance.isBuildRunningOnCI) return ConfigurationStorage.logEnvironmentVariables(true) } override fun beforeEach(context: ExtensionContext) = configure() override fun beforeAll(context: ExtensionContext?) = configure() }
0
Kotlin
6
17
63ca6f3a1d55ea46c3d2e55521a37831f9cb2a56
742
intellij-ide-starter
Apache License 2.0
app/src/main/java/com/breezesalesoriplast/features/location/api/LocationRepo.kt
DebashisINT
630,052,678
false
{"Kotlin": 15891731, "Java": 1030472}
package com.breezesalesoriplast.features.location.api import com.breezesalesoriplast.app.Pref import com.breezesalesoriplast.base.BaseResponse import com.breezesalesoriplast.features.location.model.AppInfoInputModel import com.breezesalesoriplast.features.location.model.AppInfoResponseModel import com.breezesalesoriplast.features.location.model.GpsNetInputModel import com.breezesalesoriplast.features.location.model.ShopDurationRequest import com.breezesalesoriplast.features.location.shopdurationapi.ShopDurationApi import io.reactivex.Observable /** * Created by Saikat on 17-Aug-20. */ class LocationRepo(val apiService: LocationApi) { fun appInfo(appInfo: AppInfoInputModel?): Observable<BaseResponse> { return apiService.submitAppInfo(appInfo) } fun getAppInfo(): Observable<AppInfoResponseModel> { return apiService.getAppInfo(Pref.session_token!!, Pref.user_id!!) } fun gpsNetInfo(appInfo: GpsNetInputModel?): Observable<BaseResponse> { return apiService.submitGpsNetInfo(appInfo) } }
0
Kotlin
0
0
45469c2142f48f7fbf2796e3f63cd80b41b1662c
1,048
Oriplast
Apache License 2.0
src/test/kotlin/dev/fakek/fakes/FakeEmailAddressTest.kt
CodyEngel
226,218,138
false
null
package dev.fakek.fakes import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.endsWith import strikt.assertions.startsWith internal class FakeEmailAddressTest { private val fakeName by lazy { FakeName( firstName = "First", middleName = "", lastName = "Last" ) } @Test fun `given a FakeName when creating a FakeEmailAddress then the correct emailAddress should be set`() { val subject = FakeEmailAddress(fakeName) expectThat(subject.emailAddress) { startsWith("${fakeName.firstName}.${fakeName.lastName}".toLowerCase()) endsWith("@example.com") } } }
6
Kotlin
7
7
e3d1442059b1196a020c71fb9424266bf12fe1a1
708
fakek
Apache License 2.0
Lab_01-02/app/src/main/java/com/example/myapplication/MainActivity.kt
diable201
462,816,171
false
{"Kotlin": 72994}
package com.example.myapplication import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider class MainActivity : AppCompatActivity() { private lateinit var viewModel: Brain override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProvider(this).get(Brain::class.java) } fun buttonClick(view: View) { val button = view as Button val text = button.text; viewModel.processSignal(text.toString()) val equationText = findViewById<TextView>(R.id.workingsTV) equationText.text = viewModel.equationText val resultText = findViewById<TextView>(R.id.resultsTV) resultText.text = viewModel.resultText } }
0
Kotlin
0
0
673cade0f8d35664c697c1b5baa1046df6a85a15
938
AndroidDevelopment
MIT License
app/src/main/java/com/example/studioghiblilist/framework/viewmodel/AnimeViewModel.kt
matheusdelnero
569,841,082
false
null
package com.example.studioghiblilist.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.studioghiblilist.api.AnimeRestApiTask import com.example.studioghiblilist.data.AnimeDataSource import com.example.studioghiblilist.data.AnimeRepository import com.example.studioghiblilist.domain.Anime import com.example.studioghiblilist.implementations.AnimeDataSourceImplementation import com.example.studioghiblilist.usecase.AnimeListUseCase class AnimeViewModel:ViewModel() { companion object{ const val TAG = "AnimeRepository" } private val animeRestApiTask = AnimeRestApiTask() private val animeDataSource = AnimeDataSourceImplementation(animeRestApiTask) private val animeRepository = AnimeRepository(animeDataSource) private val animeListUseCase = AnimeListUseCase(animeRepository) private var _listOfAnime = MutableLiveData<List<Anime>>() val listOfAnime: LiveData<List<Anime>> get() = _listOfAnime fun init(){ getAllAnimes() } fun getAllAnimes(){ Thread{ try { _listOfAnime.postValue(animeListUseCase.invoke()) } catch (exception: Exception){ Log.d(TAG, exception.message.toString()) } }.start() } }
0
Kotlin
0
0
1d1a14b1be36bc4ee548d89064635ae2e0b419bd
1,384
Animes_StudioGhibli
MIT License
src/test/kotlin/org/web3kt/core/protocol/Web3Test.kt
web3kt
828,453,056
false
{"Kotlin": 192188}
package org.web3kt.core.protocol import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals class Web3Test { private val web3 = Web3(Fixture.jsonRpc) @Test fun clientVersion(): Unit = runBlocking { web3.clientVersion() } @Test fun sha3(): Unit = runBlocking { val expected = "0x5e39a0a66544c0668bde22d61c47a8710000ece931f13b84d3b2feb44ec96d3f" val actual = web3.sha3("0x68656c6c6f20776f726c00") assertEquals(expected, actual) } }
0
Kotlin
0
0
b4ddabf6dc6225bf06136ea333532b15bf34047a
541
web3.kt
MIT License
src/test/kotlin/org/web3kt/core/protocol/Web3Test.kt
web3kt
828,453,056
false
{"Kotlin": 192188}
package org.web3kt.core.protocol import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals class Web3Test { private val web3 = Web3(Fixture.jsonRpc) @Test fun clientVersion(): Unit = runBlocking { web3.clientVersion() } @Test fun sha3(): Unit = runBlocking { val expected = "0x5e39a0a66544c0668bde22d61c47a8710000ece931f13b84d3b2feb44ec96d3f" val actual = web3.sha3("0x68656c6c6f20776f726c00") assertEquals(expected, actual) } }
0
Kotlin
0
0
b4ddabf6dc6225bf06136ea333532b15bf34047a
541
web3.kt
MIT License
app/src/androidTest/kotlin/ir/fallahpoor/releasetracker/libraries/view/composables/SearchBarTest.kt
MasoodFallahpoor
298,668,650
false
null
package ir.fallahpoor.releasetracker.libraries.view.composables import android.content.Context import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth import ir.fallahpoor.releasetracker.R import org.junit.Rule import org.junit.Test class SearchBarTest { @get:Rule val composeTestRule = createComposeRule() private val context: Context = ApplicationProvider.getApplicationContext() private val clearSearchBarTag = context.getString(R.string.test_tag_search_bar_clear_button) private val closeSearchBarTag = context.getString(R.string.test_tag_search_bar_close_button) private val queryTextFieldTag = context.getString(R.string.test_tag_search_bar_query_text_field) @Test fun searchBar_is_initialized_correctly() { val hint = "hint" composeTestRule.setContent { SearchBar( hint = hint, query = "", onQueryChange = {}, onQuerySubmit = {}, onClearClick = {}, onCloseClick = {} ) } with(composeTestRule) { onNodeWithText(hint).assertIsDisplayed() onNodeWithTag(closeSearchBarTag) .assertIsDisplayed() onNodeWithTag(clearSearchBarTag) .assertIsDisplayed() } } @Test fun hint_not_displayed_when_query_is_not_empty() { // Given val hint = "hint" var query by mutableStateOf("") val newQuery = "coil" composeTestRule.setContent { SearchBar( hint = hint, query = query, onQueryChange = { query = it }, onQuerySubmit = {}, onClearClick = {}, onCloseClick = {} ) } // When composeTestRule.onNodeWithTag(queryTextFieldTag) .performTextInput(newQuery) // Then with(composeTestRule) { onNodeWithText(hint).assertDoesNotExist() onNodeWithText(newQuery).assertIsDisplayed() } } @Test fun correct_callback_called_when_clear_button_clicked() { var query by mutableStateOf("") composeTestRule.setContent { SearchBar( hint = "", query = query, onQueryChange = { }, onQuerySubmit = { }, onClearClick = { query = "" }, onCloseClick = { } ) } // When composeTestRule.onNodeWithTag(clearSearchBarTag) .performClick() // Then Truth.assertThat(query).isEmpty() } @Test fun clicking_the_close_button_invokes_the_correct_callback() { var query by mutableStateOf("") composeTestRule.setContent { SearchBar( hint = "", query = query, onQueryChange = { }, onQuerySubmit = { }, onClearClick = { }, onCloseClick = { query = "" } ) } // When composeTestRule.onNodeWithTag(closeSearchBarTag) .performClick() // Then Truth.assertThat(query).isEmpty() } @Test fun correct_callback_called_when_query_changes() { // Given var query by mutableStateOf("") val newQuery = "coil" composeTestRule.setContent { SearchBar( hint = "", query = query, onQueryChange = { query = it }, onQuerySubmit = { }, onClearClick = { }, onCloseClick = { } ) } // When composeTestRule.onNodeWithTag(queryTextFieldTag) .performTextInput(newQuery) // Then Truth.assertThat(query).isEqualTo(newQuery) } @Test fun correct_callback_called_when_query_submitted() { // Given var query by mutableStateOf("") val newQuery = "coil" composeTestRule.setContent { SearchBar( hint = "", query = query, onQueryChange = { }, onQuerySubmit = { query = it }, onClearClick = { }, onCloseClick = { } ) } // TODO Find a way to perform the 'search' IME action // When // composeTestRule.onNodeWithTag(queryTextFieldTag) // .performImeAction() // Then // Truth.assertThat(query).isEqualTo(newQuery) } }
4
Kotlin
2
4
64406d7c5688fca2ca600c8f76d6d89e7bd23ed6
4,865
ReleaseTracker
Apache License 2.0
library/src/main/java/ru/yoo/sdk/kassa/payments/impl/paymentOptionInfo/PaymentOptionInfoPresenter.kt
ilnur21748
340,495,560
true
{"Kotlin": 982108, "HTML": 1425}
/* * The MIT License (MIT) * Copyright © 2020 NBCO YooMoney LLC * * 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 ru.yoo.sdk.kassa.payments.impl.paymentOptionInfo import ru.yoo.sdk.kassa.payments.R import ru.yoo.sdk.kassa.payments.model.LinkedCard import ru.yoo.sdk.kassa.payments.model.NewCard import ru.yoo.sdk.kassa.payments.model.Presenter import ru.yoo.sdk.kassa.payments.model.PaymentIdCscConfirmation import ru.yoo.sdk.kassa.payments.model.ViewModel import ru.yoo.sdk.kassa.payments.payment.tokenize.TokenizeOutputModel import ru.yoo.sdk.kassa.payments.payment.tokenize.TokenizePaymentOptionInfoRequired internal class PaymentOptionInfoPresenter( private val otherPresenter: Presenter<TokenizeOutputModel, ViewModel> ) : Presenter<TokenizeOutputModel, ViewModel> { override fun invoke(outputModel: TokenizeOutputModel) = when (outputModel) { is TokenizePaymentOptionInfoRequired -> when (outputModel.option) { is NewCard -> PaymentOptionInfoBankCardViewModel( optionId = outputModel.option.id, savePaymentOption = outputModel.savePaymentMethod ) is LinkedCard -> PaymentOptionInfoLinkedCardViewModel( optionId = outputModel.option.id, savePaymentOption = outputModel.savePaymentMethod, title = R.string.ym_bank_card_title_edit, pan = outputModel.option.pan.chunked(4).joinToString(" ") ) is PaymentIdCscConfirmation -> PaymentOptionInfoLinkedCardViewModel( optionId = outputModel.option.id, savePaymentOption = outputModel.savePaymentMethod, title = R.string.ym_bank_card_title_new, pan = (outputModel.option.first + "*****" + outputModel.option.last).chunked(4).joinToString(" ") ) else -> throw IllegalArgumentException("${outputModel.option} is not allowed here") } else -> otherPresenter.invoke(outputModel) } } internal sealed class PaymentOptionInfoViewModel : ViewModel() { abstract val optionId: Int abstract val savePaymentOption: Boolean } internal data class PaymentOptionInfoBankCardViewModel( override val optionId: Int, override val savePaymentOption: Boolean ) : PaymentOptionInfoViewModel() internal data class PaymentOptionInfoLinkedCardViewModel( override val optionId: Int, override val savePaymentOption: Boolean, val pan: CharSequence, val title: Int ) : PaymentOptionInfoViewModel()
0
null
0
0
665a71ef687bc3c7b779398290da373d67a61bf5
3,563
yookassa-android-sdk
MIT License
klogx/core/src/main/kotlin/com/mohsenoid/klogx/KLogLevel.kt
mohsenoid
861,233,292
false
{"Kotlin": 20133}
package com.mohsenoid.klogx /** * The log priorities that map to [android.util.Log] priority */ enum class KLogLevel(val priority: Int) { VERBOSE(priority = 2), DEBUG(priority = 3), INFO(priority = 4), WARN(priority = 5), ERROR(priority = 6), ASSERT(priority = 7), }
0
Kotlin
1
6
24c90ccd239f8c473c4237446167ff2fce2f37e5
294
KLogX
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/authentication/AuthenticationViewModel.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.http_shortcuts.activities.editor.authentication import android.app.Application import android.net.Uri import android.text.InputType import ch.rmy.android.framework.extensions.attachTo import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.editor.authentication.usecases.CopyCertificateFileUseCase import ch.rmy.android.http_shortcuts.activities.variables.VariablesActivity import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.shortcuts.TemporaryShortcutRepository import ch.rmy.android.http_shortcuts.data.dtos.VariablePlaceholder import ch.rmy.android.http_shortcuts.data.enums.ClientCertParams import ch.rmy.android.http_shortcuts.data.enums.ShortcutAuthenticationType import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.usecases.GetVariablePlaceholderPickerDialogUseCase import ch.rmy.android.http_shortcuts.usecases.KeepVariablePlaceholderProviderUpdatedUseCase import javax.inject.Inject class AuthenticationViewModel(application: Application) : BaseViewModel<Unit, AuthenticationViewState>(application), WithDialog { @Inject lateinit var temporaryShortcutRepository: TemporaryShortcutRepository @Inject lateinit var keepVariablePlaceholderProviderUpdated: KeepVariablePlaceholderProviderUpdatedUseCase @Inject lateinit var copyCertificateFile: CopyCertificateFileUseCase @Inject lateinit var getVariablePlaceholderPickerDialog: GetVariablePlaceholderPickerDialogUseCase init { getApplicationComponent().inject(this) } override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun onInitializationStarted(data: Unit) { finalizeInitialization(silent = true) } override fun initViewState() = AuthenticationViewState() override fun onInitialized() { temporaryShortcutRepository.getTemporaryShortcut() .subscribe( ::initViewStateFromShortcut, ::onInitializationError, ) .attachTo(destroyer) keepVariablePlaceholderProviderUpdated(::emitCurrentViewState) .attachTo(destroyer) } private fun initViewStateFromShortcut(shortcut: ShortcutModel) { updateViewState { copy( authenticationType = shortcut.authenticationType, username = shortcut.username, password = <PASSWORD>, token = shortcut.authToken, clientCertParams = shortcut.clientCertParams, isClientCertButtonEnabled = !shortcut.acceptAllCertificates, ) } } private fun onInitializationError(error: Throwable) { handleUnexpectedError(error) finish() } fun onAuthenticationTypeChanged(authenticationType: ShortcutAuthenticationType) { updateViewState { copy( authenticationType = authenticationType, ) } performOperation( temporaryShortcutRepository.setAuthenticationType(authenticationType) ) } fun onUsernameChanged(username: String) { updateViewState { copy(username = username) } performOperation( temporaryShortcutRepository.setUsername(username) ) } fun onPasswordChanged(password: String) { updateViewState { copy(password = password) } performOperation( temporaryShortcutRepository.setPassword(password) ) } fun onTokenChanged(token: String) { updateViewState { copy(token = token) } performOperation( temporaryShortcutRepository.setToken(token) ) } fun onClientCertParamsChanged(clientCertParams: ClientCertParams?) { updateViewState { copy(clientCertParams = clientCertParams) } performOperation( temporaryShortcutRepository.setClientCertParams(clientCertParams) ) } fun onClientCertButtonClicked() { doWithViewState { viewState -> if (viewState.clientCertParams == null) { showClientCertDialog() } else { onClientCertParamsChanged(null) } } } private fun showClientCertDialog() { dialogState = DialogState.create { title(R.string.title_client_cert) .item(R.string.label_client_cert_from_os, descriptionRes = R.string.label_client_cert_from_os_subtitle) { promptForClientCertAlias() } .item(R.string.label_client_cert_from_file, descriptionRes = R.string.label_client_cert_from_file_subtitle) { openCertificateFilePicker() } .build() } } private fun promptForClientCertAlias() { emitEvent(AuthenticationEvent.PromptForClientCertAlias) } private fun openCertificateFilePicker() { emitEvent(AuthenticationEvent.OpenCertificateFilePicker) } fun onCertificateFileSelected(file: Uri) { copyCertificateFile(file) .compose(progressMonitor.singleTransformer()) .subscribe( ::promptForPassword, ::handleUnexpectedError, ) .attachTo(destroyer) } private fun promptForPassword(fileName: String) { dialogState = DialogState.create { title(R.string.title_client_cert_file_password) .textInput( inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD, ) { password -> onClientCertParamsChanged( ClientCertParams.File(fileName, password) ) } .build() } } fun onBackPressed() { waitForOperationsToFinish { finish() } } fun onUsernameVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForUsername(it) } } fun onPasswordVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForPassword(it) } } fun onTokenVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForToken(it) } } private fun showVariableDialog(onVariablePicked: (VariablePlaceholder) -> AuthenticationEvent) { dialogState = getVariablePlaceholderPickerDialog.invoke( onVariableSelected = { emitEvent(onVariablePicked(it)) }, onEditVariableButtonClicked = { openActivity( VariablesActivity.IntentBuilder() ) }, ) } }
34
Kotlin
87
547
09eaa8438d452f95e73d57183b198c4b52d05789
7,327
HTTP-Shortcuts
MIT License
app/src/main/java/com/google/firebase/ml/md/kotlin/barcodedetection/BarcodeProcessor.kt
Anand0581
406,074,524
false
null
/** * Created by <NAME> on 19,July,2020 */ package com.google.firebase.ml.md.kotlin.barcodedetection import android.animation.ValueAnimator import android.util.Log import androidx.annotation.MainThread import com.google.android.gms.tasks.Task import com.google.firebase.ml.md.kotlin.camera.CameraReticleAnimator import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay import com.google.firebase.ml.md.kotlin.camera.WorkflowModel import com.google.firebase.ml.md.kotlin.camera.WorkflowModel.WorkflowState import com.google.firebase.ml.md.kotlin.camera.FrameProcessorBase import com.google.firebase.ml.md.kotlin.settings.PreferenceUtils import java.io.IOException /** A processor to run the barcode detector. */ class BarcodeProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) : FrameProcessorBase<List<FirebaseVisionBarcode>>() { private val detector = FirebaseVision.getInstance().visionBarcodeDetector private val cameraReticleAnimator: CameraReticleAnimator = CameraReticleAnimator(graphicOverlay) override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionBarcode>> = detector.detectInImage(image) @MainThread override fun onSuccess( image: FirebaseVisionImage, results: List<FirebaseVisionBarcode>, graphicOverlay: GraphicOverlay ) { if (!workflowModel.isCameraLive) return Log.d(TAG, "Barcode result size: ${results.size}") // Picks the barcode, if exists, that covers the center of graphic overlay. val barcodeInCenter = results.firstOrNull { barcode -> val boundingBox = barcode.boundingBox ?: return@firstOrNull false val box = graphicOverlay.translateRect(boundingBox) box.contains(graphicOverlay.width / 2f, graphicOverlay.height / 2f) } graphicOverlay.clear() if (barcodeInCenter == null) { cameraReticleAnimator.start() graphicOverlay.add(BarcodeReticleGraphic(graphicOverlay, cameraReticleAnimator)) workflowModel.setWorkflowState(WorkflowState.DETECTING) } else { cameraReticleAnimator.cancel() val sizeProgress = PreferenceUtils.getProgressToMeetBarcodeSizeRequirement(graphicOverlay, barcodeInCenter) if (sizeProgress < 1) { // Barcode in the camera view is too small, so prompt user to move camera closer. graphicOverlay.add(BarcodeConfirmingGraphic(graphicOverlay, barcodeInCenter)) workflowModel.setWorkflowState(WorkflowState.CONFIRMING) } else { // Barcode size in the camera view is sufficient. if (PreferenceUtils.shouldDelayLoadingBarcodeResult(graphicOverlay.context)) { val loadingAnimator = createLoadingAnimator(graphicOverlay, barcodeInCenter) loadingAnimator.start() graphicOverlay.add(BarcodeLoadingGraphic(graphicOverlay, loadingAnimator)) workflowModel.setWorkflowState(WorkflowState.SEARCHING) } else { workflowModel.setWorkflowState(WorkflowState.DETECTED) workflowModel.detectedBarcode.setValue(barcodeInCenter) } } } graphicOverlay.invalidate() } private fun createLoadingAnimator(graphicOverlay: GraphicOverlay, barcode: FirebaseVisionBarcode): ValueAnimator { val endProgress = 1.1f return ValueAnimator.ofFloat(0f, endProgress).apply { duration = 2000 addUpdateListener { if ((animatedValue as Float).compareTo(endProgress) >= 0) { graphicOverlay.clear() workflowModel.setWorkflowState(WorkflowState.SEARCHED) workflowModel.detectedBarcode.setValue(barcode) } else { graphicOverlay.invalidate() } } } } override fun onFailure(e: Exception) { Log.e(TAG, "Barcode detection failed!", e) } override fun stop() { try { detector.close() } catch (e: IOException) { Log.e(TAG, "Failed to close barcode detector!", e) } } companion object { private const val TAG = "BarcodeProcessor" } }
1
null
1
1
9b7b3dd53423fc8489eaa3afd30bfe19357a06ea
4,572
Barcode-Scanner
Apache License 2.0
app/src/main/java/com/aias/aias/MainActivity.kt
old-pj-aias
290,510,190
false
null
package com.aias.aias import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlin.concurrent.thread class MainActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // val intent = Intent(this, SignActivity::class.java) // intent.putExtra(Intent.EXTRA_TEXT, "hoge") // startActivityForResult(intent, 9) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) var result = ""; if (requestCode != 9) { return } if (resultCode == Activity.RESULT_OK && data != null) { val message = data.getStringExtra(Intent.EXTRA_TEXT) result = message } else if(resultCode == Activity.RESULT_CANCELED) { result = "CANCELED" } Toast.makeText(this, result, Toast.LENGTH_LONG).show(); } override fun onClick(v: View?) { when (v!!.id) { R.id.register_button -> { val intent = Intent(this, SmsActivity::class.java) startActivity(intent) } } } }
0
Kotlin
0
1
f48c87bf6f085a95d1904ffdd9b0ac7982b884fc
1,406
aias-app-android
MIT License
core/src/main/java/com/atech/core/usecase/SyllabusUseCase.kt
aiyu-ayaan
489,575,997
false
{"Kotlin": 824684}
/* * Created by aiyu * Copyright (c) 2021 . All rights reserved. * BIT App * */ package com.atech.core.usecase import androidx.annotation.Keep import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.map import com.atech.core.datasource.retrofit.model.SubjectModel import com.atech.core.datasource.room.syllabus.Subject import com.atech.core.datasource.room.syllabus.SubjectType import com.atech.core.datasource.room.syllabus.SyllabusDao import com.atech.core.datasource.room.syllabus.SyllabusModel import com.atech.core.utils.DEFAULT_PAGE_SIZE import com.atech.core.utils.EntityMapper import com.atech.core.utils.INITIAL_LOAD_SIZE import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject data class SyllabusUseCase @Inject constructor( val getSubjectsByType: GetSubjectsByType, val getSearchSyllabus: GetSearchSyllabus, ) data class GetSubjectsByType @Inject constructor( private val dao: SyllabusDao, private val offlineMapper: OfflineSyllabusUIMapper ) { operator fun invoke( courseSem: String, type: SubjectType = SubjectType.THEORY ): Flow<PagingData<SyllabusUIModel>> = Pager( config = PagingConfig( pageSize = DEFAULT_PAGE_SIZE, enablePlaceholders = false, initialLoadSize = INITIAL_LOAD_SIZE ) ) { dao.getSyllabusType(courseSem, type.name) }.flow.map { it.map { model -> offlineMapper.mapFormEntity(model) } } } data class GetSearchSyllabus @Inject constructor( private val dao: SyllabusDao, private val offlineMapper: OfflineSyllabusUIMapper ) { operator fun invoke(query: String): Flow<PagingData<SyllabusUIModel>> = Pager( config = PagingConfig( pageSize = DEFAULT_PAGE_SIZE, enablePlaceholders = false, initialLoadSize = INITIAL_LOAD_SIZE ) ) { dao.getSyllabusSearch(query) }.flow.map { it.map { model -> offlineMapper.mapFormEntity(model) } } } @Keep data class SyllabusUIModel( val subject: String, val code: String, val credits: Int, val openCode: String, val type: String, val group: String, val shortName: String?, val listOrder: Int, val subjectContent: Subject?, val isChecked: Boolean?, val isAdded: Boolean?, val fromNetwork: Boolean?, val deprecated: Boolean?, val isFromOnline: Boolean = false ) class OfflineSyllabusUIMapper @Inject constructor() : EntityMapper<SyllabusModel, SyllabusUIModel> { override fun mapFormEntity(entity: SyllabusModel): SyllabusUIModel = SyllabusUIModel( subject = entity.subject, code = entity.code, credits = entity.credits, openCode = entity.openCode, type = entity.type, group = entity.group, shortName = entity.shortName, listOrder = entity.listOrder, subjectContent = entity.subjectContent, isChecked = entity.isChecked, isAdded = entity.isAdded, fromNetwork = entity.fromNetwork, deprecated = entity.deprecated ) override fun mapToEntity(domainModel: SyllabusUIModel): SyllabusModel = SyllabusModel( subject = domainModel.subject, code = domainModel.code, credits = domainModel.credits, openCode = domainModel.openCode, type = domainModel.type, group = domainModel.group, shortName = domainModel.shortName ?: "", listOrder = domainModel.listOrder, subjectContent = domainModel.subjectContent, isChecked = domainModel.isChecked, isAdded = domainModel.isAdded, fromNetwork = domainModel.fromNetwork, deprecated = domainModel.deprecated ) fun mapFromEntityList(entities: List<SyllabusModel>): List<SyllabusUIModel> = entities.map { mapFormEntity(it) } } class OnlineSyllabusUIMapper @Inject constructor() : EntityMapper<SubjectModel, SyllabusUIModel> { override fun mapFormEntity(entity: SubjectModel): SyllabusUIModel = SyllabusUIModel( subject = entity.subjectName, code = entity.code, credits = entity.credit.toInt(), openCode = "", type = "", group = "", shortName = entity.shortName, listOrder = 0, subjectContent = null, isChecked = false, isAdded = false, fromNetwork = true, deprecated = false, isFromOnline = true ) override fun mapToEntity(domainModel: SyllabusUIModel): SubjectModel = SubjectModel( subjectName = domainModel.subject, code = domainModel.code, credit = domainModel.credits.toDouble(), shortName = domainModel.shortName ?: "" ) fun mapFromEntityList(entities: List<SubjectModel>): List<SyllabusUIModel> = entities.map { mapFormEntity(it) } }
9
Kotlin
5
17
2dcf9ccf6de5a3b4cb11f8edac88822296251500
5,191
BIT-App
MIT License
app/src/main/java/br/com/andreikeda/example/villageresourcemanagement/ui/village/VillagePresenter.kt
andreikeda
653,666,949
false
null
package br.com.andreikeda.example.villageresourcemanagement.ui.village import br.com.andreikeda.example.villageresourcemanagement.domain.models.Game import br.com.andreikeda.example.villageresourcemanagement.domain.models.Game.Status.* import br.com.andreikeda.example.villageresourcemanagement.ui.home.HomeContract class VillagePresenter(private val view: HomeContract.View): VillageContract.Presenter { override fun onGatherResourcesClicked() { when (Game.endDay()) { VICTORY -> view.victory() GAME_OVER -> view.gameOver() ONGOING -> view.refreshData() } } }
0
Kotlin
0
0
72b82d8e73b06227ecdadb4151e41f4ada4ec15e
622
village-resource-management-example
MIT License
src/jvmMain/kotlin/matt/file/commons/lcommons/lcommons.kt
mgroth0
513,680,528
false
null
package matt.file.commons.lcommons import matt.file.CaseSensitivity.CaseSensitive import matt.file.MFile import matt.file.commons.CACHE_FOLDER import matt.file.commons.DATA_FOLDER import matt.file.commons.REGISTERED_FOLDER import matt.file.construct.mFile import matt.file.context.ComputeContextFiles import matt.model.code.jvm.agentpath.MAC_LIBJPROFILERTI_PATH class LocalComputeContextFiles : ComputeContextFiles { private val fakeRemoteFs = REGISTERED_FOLDER["remote"] private val fakeOmFs = fakeRemoteFs["om"] override val defaultPathPrefix = fakeOmFs override val briarDataFolder: MFile get() = mFile("/Volumes/Untitled/", caseSensitivity = CaseSensitive) override val briarExtractsFolder: MFile get() = DATA_FOLDER["BriarExtracts"] override val libjprofilertiPath: String get() = MAC_LIBJPROFILERTI_PATH override val cacheFolder: MFile get() = CACHE_FOLDER["local_compute_context"] }
0
Kotlin
0
0
60e731e48bdf820ce9b51e82c20f86bbe0360f4c
953
file
MIT License
app/src/main/java/com/danefinlay/ttsutil/ui/ActivityFragmentInterfaces.kt
Danesprite
220,346,944
false
null
/* * TTS Util * * Authors: <NAME> <<EMAIL>> * * Copyright (C) 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.danefinlay.ttsutil.ui /** * Interface between fragments and their activity. */ interface FragmentInterface { /** * This method is called for activity events. */ fun handleActivityEvent(event: ActivityEvent) } /** * Interface for classes that prompt the user to pick a file for some purpose. */ interface ActivityInterface { /** * Show a screen where the user can choose a file. */ fun showFileChooser() /** * Show a screen where the user can choose a directory. */ fun showDirChooser() /** * Function to request sample TTS text from the current TTS engine. */ fun requestSampleTTSText() /** * Use attached fragments to handle an event. */ fun handleActivityEvent(event: ActivityEvent) /** * Get the most recent status update event. * * TASK_ID_IDLE is used if there have been no updates yet. */ fun getLastStatusUpdate(): ActivityEvent.StatusUpdateEvent /** * Get the most recent directory chosen event, if any. */ fun getLastDirChosenEvent(): ActivityEvent.ChosenFileEvent? /** * Get the most recent file chosen event, if any. */ fun getLastFileChosenEvent(): ActivityEvent.ChosenFileEvent? }
9
null
8
27
ee610c96270733a2a6ffd2812537f80b4e960b83
1,914
tts-util-app
Apache License 2.0
src/main/kotlin/com/skillw/asahi/api/member/ast/expr/compound/Ternary.kt
Skillw
583,251,101
false
{"Kotlin": 94989, "Java": 4431}
package com.skillw.asahi.api.member.ast.expr.compound import com.skillw.asahi.api.member.ast.Expression import com.skillw.asahi.api.member.ast.TokenBased import com.skillw.asahi.api.member.tokenizer.Token import com.skillw.asahi.api.member.tokenizer.source.SourceHolder /** * @className Unary * * @author Glom * @date 2023/8/13 11:38 Copyright 2023 user. All rights reserved. */ abstract class Ternary( source: SourceHolder, override val token: Token, val left: Expression, val middle: Expression, val right: Expression, ) : TokenBased, SourceHolder by source { override fun sized() = left.sized() && middle.sized() && right.sized() override fun serialize() = linkedMapOf( "operator" to token.toString(), "left" to left.serialize(), "middle" to middle.serialize(), "right" to right.serialize(), ) }
0
Kotlin
1
7
a78bce9a19c066bd318ec81450fdfdd7dccfc831
869
Asahi
Creative Commons Zero v1.0 Universal
samples/demo-app/app/src/main/java/cash/z/wallet/sdk/demoapp/demos/send/SendFragment.kt
benzcash
257,942,797
true
{"Kotlin": 336630, "Rust": 82586, "Dockerfile": 1729}
package cash.z.ecc.android.sdk.demoapp.demos.send import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.lifecycle.lifecycleScope import cash.z.ecc.android.sdk.Initializer import cash.z.ecc.android.sdk.Synchronizer import cash.z.ecc.android.sdk.block.CompactBlockProcessor import cash.z.ecc.android.sdk.demoapp.App import cash.z.ecc.android.sdk.demoapp.BaseDemoFragment import cash.z.ecc.android.sdk.demoapp.R import cash.z.ecc.android.sdk.demoapp.databinding.FragmentSendBinding import cash.z.ecc.android.sdk.demoapp.util.SampleStorageBridge import cash.z.ecc.android.sdk.db.entity.* import cash.z.ecc.android.sdk.ext.* /** * Demonstrates sending funds to an address. This is the most complex example that puts all of the * pieces of the SDK together, including monitoring transactions for completion. It begins by * downloading, validating and scanning any missing blocks. Once that is complete, the wallet is * in a SYNCED state and available to send funds. Calling `sendToAddress` produces a flow of * PendingTransaction objects which represent the active state of the transaction that was sent. * Any time the state of that transaction changes, a new instance will be emitted. */ class SendFragment : BaseDemoFragment<FragmentSendBinding>() { private val config = App.instance.defaultConfig private val initializer = Initializer(App.instance, host = config.host, port = config.port) private val birthday = config.loadBirthday() private lateinit var synchronizer: Synchronizer private lateinit var keyManager: SampleStorageBridge private lateinit var amountInput: TextView private lateinit var addressInput: TextView // // Observable properties (done without livedata or flows for simplicity) // private var balance = CompactBlockProcessor.WalletBalance() set(value) { field = value onUpdateSendButton() } private var isSending = false set(value) { field = value if (value) Twig.sprout("Sending") else Twig.clip("Sending") onUpdateSendButton() } private var isSyncing = true set(value) { field = value onUpdateSendButton() } // // BaseDemoFragment overrides // override fun inflateBinding(layoutInflater: LayoutInflater): FragmentSendBinding = FragmentSendBinding.inflate(layoutInflater) override fun resetInBackground() { val spendingKeys = initializer.new(config.seed, birthday) keyManager = SampleStorageBridge().securelyStorePrivateKey(spendingKeys[0]) synchronizer = Synchronizer(initializer) } // STARTING POINT override fun onResetComplete() { initSendUi() startSynchronizer() monitorChanges() } override fun onClear() { synchronizer.stop() initializer.clear() } // // Private functions // private fun initSendUi() { amountInput = binding.root.findViewById<TextView>(R.id.input_amount).apply { text = config.sendAmount.toString() } addressInput = binding.root.findViewById<TextView>(R.id.input_address).apply { text = config.toAddress } binding.buttonSend.setOnClickListener(::onSend) } private fun startSynchronizer() { lifecycleScope.apply { synchronizer.start(this) } } private fun monitorChanges() { synchronizer.status.collectWith(lifecycleScope, ::onStatus) synchronizer.progress.collectWith(lifecycleScope, ::onProgress) synchronizer.processorInfo.collectWith(lifecycleScope, ::onProcessorInfoUpdated) synchronizer.balances.collectWith(lifecycleScope, ::onBalance) } private fun onStatus(status: Synchronizer.Status) { binding.textStatus.text = "Status: $status" isSyncing = status != Synchronizer.Status.SYNCED if (status == Synchronizer.Status.SCANNING) { binding.textBalance.text = "Calculating balance..." } else { if (!isSyncing) onBalance(balance) } } private fun onProgress(i: Int) { if (i < 100) { binding.textStatus.text = "Downloading blocks...$i%" binding.textBalance.visibility = View.INVISIBLE } else { binding.textBalance.visibility = View.VISIBLE } } private fun onProcessorInfoUpdated(info: CompactBlockProcessor.ProcessorInfo) { if (info.isScanning) binding.textStatus.text = "Scanning blocks...${info.scanProgress}%" } private fun onBalance(balance: CompactBlockProcessor.WalletBalance) { this.balance = balance if (!isSyncing) { binding.textBalance.text = """ Available balance: ${balance.availableZatoshi.convertZatoshiToZecString(12)} Total balance: ${balance.totalZatoshi.convertZatoshiToZecString(12)} """.trimIndent() } } private fun onSend(unused: View) { isSending = true val amount = amountInput.text.toString().toDouble().convertZecToZatoshi() val toAddress = addressInput.text.toString().trim() synchronizer.sendToAddress( keyManager.key, amount, toAddress, "Demo App Funds" ).collectWith(lifecycleScope, ::onPendingTxUpdated) } private fun onPendingTxUpdated(pendingTransaction: PendingTransaction?) { val id = pendingTransaction?.id ?: -1 val message = when { pendingTransaction == null -> "Transaction not found" pendingTransaction.isMined() -> "Transaction Mined (id: $id)!\n\nSEND COMPLETE".also { isSending = false } pendingTransaction.isSubmitSuccess() -> "Successfully submitted transaction!\nAwaiting confirmation..." pendingTransaction.isFailedEncoding() -> "ERROR: failed to encode transaction! (id: $id)".also { isSending = false } pendingTransaction.isFailedSubmit() -> "ERROR: failed to submit transaction! (id: $id)".also { isSending = false } pendingTransaction.isCreated() -> "Transaction creation complete! (id: $id)" pendingTransaction.isCreating() -> "Creating transaction!".also { onResetInfo() } else -> "Transaction updated!".also { twig("Unhandled TX state: $pendingTransaction") } } twig("Pending TX Updated: $message") binding.textInfo.apply { text = "$text\n$message" } } private fun onUpdateSendButton() { with(binding.buttonSend) { when { isSending -> { text = "➡ sending" isEnabled = false } isSyncing -> { text = "⌛ syncing" isEnabled = false } balance.availableZatoshi <= 0 -> isEnabled = false else -> { text = "send" isEnabled = true } } } } private fun onResetInfo() { binding.textInfo.text = "Active Transaction:" } }
0
Kotlin
0
0
fb7cf0e8eb7092d693472c8742dfeceb0dbe6b67
7,247
zcash-android-wallet-sdk
Apache License 2.0
app/src/main/java/com/fabiel/casas/amazon_products/MainActivity.kt
fabiel-casas
284,458,709
false
{"Kotlin": 11920}
package com.fabiel.casas.amazon_products import android.app.SearchManager import android.content.Context import android.os.Bundle import android.view.* import android.widget.ImageView import android.widget.TextView import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.fabiel.casas.amazon_products.data.models.Product import com.fabiel.casas.amazon_products.view.adapter.ProductAdapter import com.fabiel.casas.amazon_products.view.viewmodel.MainViewModel import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_amazon_product_list.* import kotlinx.android.synthetic.main.product_item_list.view.* import kotlinx.android.synthetic.main.products_list.* class MainActivity : AppCompatActivity() { private val model: MainViewModel by viewModels() private lateinit var searchView: SearchView private lateinit var searchItem: MenuItem override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_amazon_product_list) setSupportActionBar(toolbar) toolbar.title = title setupProducts() } private fun setupProducts() { val adapter = ProductAdapter() model.productList.observe(this, Observer { productsRecyclerView.isVisible = true progressBar.isVisible = false adapter.setItems(it) }) model.productListError.observe(this, Observer { progressBar.isVisible = false productsRecyclerView.isVisible = false Snackbar.make(productsRecyclerView, it, Snackbar.LENGTH_LONG).show() }) productsRecyclerView.adapter = adapter productsRecyclerView.layoutManager = GridLayoutManager(this, 2) } override fun onResume() { super.onResume() model.getProducts() progressBar.isVisible = true } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.search, menu) searchItem = menu.findItem(R.id.action_search) val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager searchView = searchItem.actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) searchView.setOnQueryTextListener(searchListener) return super.onCreateOptionsMenu(menu) } private val searchListener = object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { searchItem.collapseActionView() model.getProducts(query) progressBar.isVisible = true return true } override fun onQueryTextChange(newText: String): Boolean = true } }
0
Kotlin
0
0
87638476645fe7aad65b4606213c643bb829f76e
3,075
Amazon-Products
Apache License 2.0
core/src/main/kotlin/org/bastanchu/churiservices/core/api/model/orders/OrderLinePricingCondition.kt
vellebue
723,669,515
false
{"Kotlin": 222568}
package org.bastanchu.churiservices.core.api.model.orders import org.bastanchu.churiservices.core.api.model.article.ArticlePricingCondition import java.math.BigDecimal data class OrderLinePricingCondition(var type : ArticlePricingCondition.PricingConditionType = ArticlePricingCondition.PricingConditionType.FARE, var subtype : String = "", var order : Int = 0, var valueType : ArticlePricingCondition.PricingConditionKind = ArticlePricingCondition.PricingConditionKind.VALUE, var value : BigDecimal = BigDecimal.ZERO, var baseValue : BigDecimal = BigDecimal.ZERO, var conditionValue : BigDecimal = BigDecimal.ZERO, var totalValue : BigDecimal = BigDecimal.ZERO) { }
0
Kotlin
0
0
0c5f47ae51faa216d0b19e9cf1827865fb5af059
927
churiservices
Apache License 2.0
libs/ui-modal/src/main/kotlin/mono/html/modal/compose/DropDownMenu.kt
tuanchauict
325,686,408
false
{"Kotlin": 614290, "SCSS": 33498, "Python": 1834, "Shell": 935, "HTML": 885, "CSS": 728}
/* * Copyright (c) 2023, tuanchauict */ @file:Suppress("FunctionName") package mono.html.modal.compose import androidx.compose.runtime.Composable import kotlinx.browser.document import mono.html.px import mono.html.style import org.jetbrains.compose.web.dom.Li import org.jetbrains.compose.web.dom.Text import org.jetbrains.compose.web.dom.Ul import org.w3c.dom.Element /** * Show drop down menu at the bottom of the anchor, horizontal center aligned with the anchor. */ fun DropDownMenu( anchor: Element, items: List<DropDownItem>, onClick: (DropDownItem) -> Unit ) { NoBackgroundModal( attrs = { classes("drop-down-menu") ref { it.adjustPosition(anchor) onDispose { } } } ) { Ul { for (item in items) { if (!item.isVisible()) { continue } when (item) { is DropDownItem.Divider -> Divider() is DropDownItem.Text -> Item(item) { onClick(it) dismiss() } is DropDownItem.Custom -> { item.content.invoke(this@NoBackgroundModal) } } } } } } @Composable private fun Divider() { Li(attrs = { classes("drop-down-divider") }) } @Composable private fun Item(item: DropDownItem.Text, onClick: (DropDownItem) -> Unit) { Li( attrs = { classes("drop-down-item") onClick { onClick(item) } } ) { Text(item.title) } } private fun Element.adjustPosition(anchor: Element) { val maxWidth = document.body?.clientWidth ?: return val menuWidthPx = clientWidth val anchorRect = anchor.getBoundingClientRect() val leftPx = (anchorRect.left + anchorRect.width / 2 - menuWidthPx / 2).toInt() .coerceIn(4, maxWidth - menuWidthPx - 4) style( "left" to leftPx.px, "top" to anchorRect.bottom.px ) } sealed class DropDownItem(internal val isVisible: () -> Boolean) { class Divider(isVisible: () -> Boolean = { true }) : DropDownItem(isVisible) class Text(val title: String, val key: Any, isVisible: () -> Boolean = { true }) : DropDownItem(isVisible) class Custom( isVisible: () -> Boolean, internal val content: @Composable ModalElementScope.() -> Unit ) : DropDownItem(isVisible) }
15
Kotlin
9
376
fb4c99a23173768bf935992f09692715c908cdae
2,537
MonoSketch
Apache License 2.0
payments-ui-core/src/main/java/com/stripe/android/ui/core/BillingDetailsCollectionConfiguration.kt
stripe
6,926,049
false
null
package com.stripe.android.ui.core import android.os.Parcelable import androidx.annotation.RestrictTo import kotlinx.parcelize.Parcelize /** * Configuration for how billing details are collected during checkout. */ @Parcelize @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class BillingDetailsCollectionConfiguration( /** * How to collect the name field. */ val name: CollectionMode = CollectionMode.Automatic, /** * How to collect the phone field. */ val phone: CollectionMode = CollectionMode.Automatic, /** * How to collect the email field. */ val email: CollectionMode = CollectionMode.Automatic, /** * How to collect the billing address. */ val address: AddressCollectionMode = AddressCollectionMode.Automatic, /** * Whether the values included in `PaymentSheet.Configuration.defaultBillingDetails` * should be attached to the payment method, this includes fields that aren't displayed in the form. * * If `false` (the default), those values will only be used to prefill the corresponding fields in the form. */ val attachDefaultsToPaymentMethod: Boolean = false, ) : Parcelable { /** * Billing details fields collection options. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) enum class CollectionMode { /** * The field will be collected depending on the Payment Method's requirements. */ Automatic, /** * The field will never be collected. * If this field is required by the Payment Method, you must provide it as part of `defaultBillingDetails`. */ Never, /** * The field will always be collected, even if it isn't required for the Payment Method. */ Always, } /** * Billing address collection options. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) enum class AddressCollectionMode { /** * Only the fields required by the Payment Method will be collected, this may be none. */ Automatic, /** * Address will never be collected. * If the Payment Method requires a billing address, you must provide it as part of `defaultBillingDetails`. */ Never, /** * Collect the full billing address, regardless of the Payment Method requirements. */ Full, } }
86
Kotlin
584
1,078
74bf7263f56d53aff2d0035127d84dd40609403d
2,449
stripe-android
MIT License
presentation/src/main/kotlin/ir/cafebazzar/nearby/di/app/AppComponent.kt
mohsenuix
170,470,285
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Kotlin": 54, "Java": 6, "Proguard": 1, "XML": 24}
package ir.cafebazzar.nearby.di.app import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import ir.cafebazzar.nearby.App import ir.cafebazzar.nearby.data.DataLayerModule import ir.cafebazzar.nearby.di.viewmodel.ViewModelModule import javax.inject.Singleton @Singleton @Component(modules = [AppModule::class, AndroidSupportInjectionModule::class, BuilderModule::class, ViewModelModule::class, DataLayerModule::class]) interface AppComponent : AndroidInjector<App> { @Component.Builder interface Builder { @BindsInstance fun application(application: App): Builder fun build(): AppComponent } override fun inject(app: App) }
1
null
1
1
808ae3db5aed4a44daec8178fed8a55eefb65428
775
nearby
MIT License
app/src/main/java/com/dubedivine/samples/injection/module/ApplicationModule.kt
dubeboy
102,972,979
false
null
package com.dubedivine.samples.injection.module import android.app.Application import android.content.Context import com.dubedivine.samples.data.local.PreferencesHelper import com.dubedivine.samples.data.remote.MvpStarterService import com.dubedivine.samples.data.remote.MvpStarterServiceFactory import com.dubedivine.samples.injection.ApplicationContext import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ApplicationModule(private val mApplication: Application) { @Provides internal fun provideApplication(): Application { return mApplication } @Provides @ApplicationContext internal fun provideContext(): Context { return mApplication } @Provides @Singleton internal fun provideMvpStarterService(): MvpStarterService { return MvpStarterServiceFactory.makeStarterService() } @Provides @Singleton internal fun provideMvpPreferences(): PreferencesHelper { return PreferencesHelper(mApplication) } }
0
Kotlin
1
1
0dccd66d69fc3f1ae7cbecbab397d8de6f29cc5c
1,033
Peerlink-mobile
The Unlicense
app/src/main/java/com/github/lion4ik/ui/ForecastsFragment.kt
lion4ik
154,719,120
false
null
package com.github.lion4ik.ui import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.View import com.github.lion4ik.App import com.github.lion4ik.R import com.github.lion4ik.ui.base.BaseFragment import com.github.lion4ik.util.lazyNotThreadSafe import com.github.lion4ik.util.showSnackBar import com.github.lion4ik.viewmodel.ForecastsViewModel import com.github.lion4ik.viewmodel.MainViewModelFactory import javax.inject.Inject class ForecastsFragment : BaseFragment() { companion object { fun newInstance(): ForecastsFragment = ForecastsFragment() } @Inject lateinit var viewModelFactory: MainViewModelFactory private val forecastsViewModel by lazyNotThreadSafe { ViewModelProviders.of(this, viewModelFactory).get(ForecastsViewModel::class.java) } private val adapter by lazyNotThreadSafe { ForecastAdapter() } override fun getOptionalToolbar(): Toolbar? = toolbar override fun getLayoutRes(): Int = R.layout.fragment_forecast override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App.appComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) addLocationFab.setOnClickListener { forecastsViewModel.onAddLocationClicked() } initForecastList() // TODO move observing to onCreate observeData() } private fun initForecastList() { forecastList.layoutManager = LinearLayoutManager(context) forecastList.setHasFixedSize(true) forecastList.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) forecastList.adapter = adapter forecastList.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy != 0 && addLocationFab.isShown) addLocationFab.hide() } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { addLocationFab.show() } super.onScrollStateChanged(recyclerView, newState) } }) } private fun observeData() { forecastsViewModel.getAllForecasts().nonNullObserve(this) { adapter.submitList(it) } forecastsViewModel.error.nonNullObserve(this) { showSnackBar(it) } forecastsViewModel.isEmpty.nonNullObserve(this) { isEmpty -> setEmptyVisible(isEmpty) } } private fun setEmptyVisible(isVisible: Boolean) { emptyList.visibility = if (isVisible) View.VISIBLE else View.GONE } }
0
Kotlin
0
2
b837a78240a1be17504f52847faf4573cf8cdd9c
3,045
WeatherApp
MIT License
app/src/main/java/com/example/camera2basicjetpackcompose/MainActivity.kt
videlanicolas
832,437,632
false
{"Kotlin": 19388}
package com.example.camera2basicjetpackcompose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import com.example.camera2basicjetpackcompose.ui.theme.Camera2BasicJetpackComposeTheme // Main entrypoint for the app. class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { Camera2BasicJetpackComposeTheme { // Just for display we show the camera composable. In a real implementation you should have a // NavHost controller to route the user to the camera. CameraScreen() } } } }
0
Kotlin
0
0
e712adbe713d8e3acb8a3eb8b3fd2b422784dab6
803
camera2_jetpack_compose_example
The Unlicense
src/main/kotlin/com.franzmandl.fileadmin/security/ShutdownService.kt
franzmandl
570,884,978
false
null
package com.franzmandl.fileadmin.security import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.context.ConfigurableApplicationContext import org.springframework.stereotype.Service @Service class ShutdownService : ApplicationContextAware { private val logger: Logger = LoggerFactory.getLogger(ShutdownService::class.java) private lateinit var context: ConfigurableApplicationContext override fun setApplicationContext(applicationContext: ApplicationContext) { this.context = applicationContext as ConfigurableApplicationContext } fun shutdown(reasons: String) { logger.info("Shutting down for $reasons reasons") context.close() } }
0
Kotlin
0
0
9e7a3f2876688627b24a98a2fe58027b4d733ce2
824
fileadmin-server
MIT License
app/src/main/java/com/quickbirdstudios/mvvmtalk/MyModule.kt
quickbirdstudios
129,719,136
false
null
package com.quickbirdstudios.mvvmtalk import android.arch.lifecycle.ViewModel import com.quickbirdstudios.quickboot.di.ViewModelKey import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import javax.inject.Singleton /** * Created by <NAME> on 10/04/2018. */ @Singleton @Module abstract class MyModule { @Binds @IntoMap @ViewModelKey(TranslatorViewModel::class) abstract fun bindsTranslatorViewModel(translatorViewModelImpl: TranslatorViewModelImpl): ViewModel }
1
Kotlin
1
15
9e15947f5098b46e0231ec11d30eb2f5c71947b2
507
platform-independent-mvvm-android
Apache License 2.0
app/src/test/java/com/desarrollodroide/simplecleancode/ui/MainViewModelTest.kt
DesarrolloAntonio
281,364,477
false
null
package com.desarrollodroide.simplecleancode.ui import android.util.Log import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.desarrollodroide.simplecleancode.domain.DummyObjectRepository import com.desarrollodroide.simplecleancode.model.DummyObject import com.desarrollodroide.simplecleancode.model.Resource import com.nhaarman.mockitokotlin2.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.TestCoroutineScope import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.setMain import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(Log::class) @ExperimentalCoroutinesApi class MainViewModelTest { private val testDispatcher = TestCoroutineDispatcher() private val testCoroutineScope = TestCoroutineScope(testDispatcher) private val repository = mock<DummyObjectRepository>() private val viewModel by lazy { MainFragmentViewModel(repository) } private val observerDummyObjects: Observer<Resource<List<DummyObject>?>> = mock() @Rule var rule: TestRule = InstantTaskExecutorRule() @Before fun setUp() { PowerMockito.mockStatic(Log::class.java) Dispatchers.setMain(testDispatcher) viewModel.dummyObjects.observeForever(observerDummyObjects) } @Test fun `should success when fetchFromServer returns proper data`() = testCoroutineScope.runBlockingTest { whenever(repository.getDummyObjects()).thenReturn(Resource.Success(listOf(DummyObject(1, 1, "Title", "Body")))) viewModel.getData() advanceTimeBy(500) verify(repository).getDummyObjects() // Changes two times , loading and success verify(observerDummyObjects, times(2)).onChanged(any()) verify(observerDummyObjects, times(1)) .onChanged(ArgumentMatchers.any(Resource.Loading::class.java) as Resource<List<DummyObject>?>?) verify(observerDummyObjects, times(1)) .onChanged(ArgumentMatchers.any(Resource.Success::class.java) as Resource<List<DummyObject>?>?) verify(observerDummyObjects, never()) .onChanged(ArgumentMatchers.any(Resource.Error::class.java) as Resource<List<DummyObject>?>?) } @Test fun `should fail when fetchFromServer throws exception`() = testCoroutineScope.runBlockingTest { val error = Error() whenever(repository.getDummyObjects()).thenThrow(error) // act viewModel.getData() advanceTimeBy(500) // assert - Verify if this method is called verify(repository).getDummyObjects() // Changes two times , loading and error verify(observerDummyObjects, times(2)).onChanged(any()) verify(observerDummyObjects, times(1)) .onChanged(ArgumentMatchers.any(Resource.Loading::class.java) as Resource<List<DummyObject>?>?) verify(observerDummyObjects, times(1)) .onChanged(ArgumentMatchers.any(Resource.Error::class.java) as Resource<List<DummyObject>?>?) verify(observerDummyObjects, never()) .onChanged(ArgumentMatchers.any(Resource.Success::class.java) as Resource<List<DummyObject>?>?) } }
0
Kotlin
1
0
cad3904d77c5a73f5d8dafeaeba9be51cd71e430
3,624
SimpleCleanCode
Apache License 2.0
core/src/test/java/de/maibornwolff/domainchoreograph/scenarios/supermarket/DomainDefinitionsWithInterfacesTests.kt
MaibornWolff
139,985,029
false
{"Kotlin": 168533, "TypeScript": 132987, "JavaScript": 5400, "HTML": 1174, "Dockerfile": 390}
package de.maibornwolff.domainchoreograph.scenarios.supermarket import de.maibornwolff.domainchoreograph.core.api.DomainEnvironment import de.maibornwolff.domainchoreograph.scenarios.supermarket.choreographies.Cashier import de.maibornwolff.domainchoreograph.scenarios.supermarket.domaindefinitions.Article import de.maibornwolff.domainchoreograph.scenarios.supermarket.domaindefinitions.Basket import de.maibornwolff.domainchoreograph.scenarios.supermarket.domaindefinitions.BasketPrice import de.maibornwolff.domainchoreograph.scenarios.supermarket.serviceimplementations.PriceServiceImplementation import org.assertj.core.api.Assertions.assertThat import org.junit.Test class DomainDefinitionsWithInterfacesTests { @Test fun `it should work with interfaces`() { // given val basket = Basket(listOf( Article("apple"), Article("banana") )) val priceService = PriceServiceImplementation() val cashier = DomainEnvironment().get(Cashier::class.java) // when val price = cashier.checkout( basket, priceService ) // then assertThat(price).isEqualTo(BasketPrice(1.5)) } }
16
Kotlin
0
1
863441f0df267dcbf9874c92771e104a8f60fe37
1,215
domainchoreograph
Apache License 2.0
arrangement/src/main/java/com/fang/arrangement/ui/screen/btmnav/money/loan/MLoan.kt
7ANG2C
794,384,998
false
{"Kotlin": 425333}
package com.fang.arrangement.ui.screen.btmnav.money.loan import com.fang.arrangement.definition.Employee import com.fang.arrangement.definition.Record internal data class MLoan( val id: Long, val employee: Employee, val loan: Int, val millis: Long, val records: List<Record>, val remark: String?, ) { val remain get() = loan - records.sumOf { it.loan } val isClear get() = remain <= 0 }
0
Kotlin
0
0
d820ad78b7eea6142da8f94c68af7b16cc0e583c
421
FANG
Apache License 2.0
src/main/kotlin/gay/pizza/pkg/apk/file/ApkFsTreeEntry.kt
azenla
590,581,912
false
null
package gay.pizza.pkg.apk.file class ApkFsTreeEntry( var parent: ApkFsTreeEntry? = null, val entity: ApkFsEntity, val children: MutableMap<String, ApkFsTreeEntry> = mutableMapOf() ) { fun addChild(entity: ApkFsEntity): ApkFsTreeEntry { val entry = ApkFsTreeEntry( parent = this, entity = entity ) children[entity.name] = entry return entry } fun getOrCreateStub(name: String, path: String): ApkFsTreeEntry { return children[name] ?: addChild(ApkFsEntity(name, path, ApkFsEntityType.Directory)) } fun crawl(block: (ApkFsTreeEntry) -> Unit) { block(this) for (child in children.values) { child.crawl(block) } } }
0
Kotlin
0
4
74d43db44188fe825f723571533303da62a81b16
682
apk-tools
MIT License
feature_view_recyclerview_adapter_sample/src/main/java/com/mercandalli/android/apps/view_recyclerview_adapter_sample/cat_row_view/CatRowView.kt
Mercandj
788,910,223
false
{"Kotlin": 44015}
package com.mercandalli.android.apps.view_recyclerview_adapter_sample.cat_row_view import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.TextView import androidx.annotation.IdRes import com.mercandalli.android.apps.view_recyclerview_adapter_sample.R class CatRowView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val view = View.inflate(context, R.layout.cat_row_view, this) private val name: TextView = bind(R.id.cat_row_view_name) private val userAction = createUserAction() fun setViewModel(viewModel: CatRowViewModel?) { userAction.onViewModelSet(viewModel = viewModel) } private fun <T : View> bind(@Suppress("SameParameterValue") @IdRes id: Int): T { return view.findViewById(id) } private fun createScreen() = object : CatRowViewContract.Screen { override fun setName(text: String) { name.text = text } } private fun createUserAction(): CatRowViewContract.UserAction { if (isInEditMode) { return object : CatRowViewContract.UserAction { override fun onViewModelSet(viewModel: CatRowViewModel?) {} } } return CatRowViewPresenter( createScreen() ) } }
0
Kotlin
0
0
f573a1804ca13b730234c6a41971292185d9eca8
1,445
recyclerview-adapter
MIT License
src/main/kotlin/de/gianttree/discord/w2g/logging/W2GFormatter.kt
GiantTreeLP
326,642,252
false
{"Kotlin": 32952}
package de.gianttree.discord.w2g.logging import java.io.PrintWriter import java.io.StringWriter import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.logging.LogRecord import java.util.logging.SimpleFormatter class W2GFormatter : SimpleFormatter() { private val sw = StringWriter() private val pw = PrintWriter(sw) private val dateFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME override fun format(record: LogRecord): String { return buildString { append(record.level.localizedName) append(' ') append(dateFormatter.format(Instant.ofEpochMilli(record.millis).atZone(ZoneId.systemDefault()))) append(": ") append(formatMessage(record)) if (record.thrown != null) { record.thrown.printStackTrace(pw) append(System.lineSeparator()) append(sw) sw.flush() } append(System.lineSeparator()) } } }
1
Kotlin
0
4
13e3a680d0bc07cba01dba49ad512fda83db88da
1,046
w2g-bot
MIT License
demo/src/main/java/co/zsmb/rainbowcake/demo/ui/viewbinding/ViewBindingSampleFragment.kt
rainbowcake
185,018,634
false
null
package co.zsmb.rainbowcake.demo.ui.viewbinding import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import co.zsmb.rainbowcake.base.RainbowCakeFragment import co.zsmb.rainbowcake.dagger.getViewModelFromFactory import co.zsmb.rainbowcake.demo.databinding.FragmentViewBindingBinding class ViewBindingSampleFragment : RainbowCakeFragment<ViewBindingSampleState, ViewBindingSampleViewModel>() { private var _binding: FragmentViewBindingBinding? = null private val binding get() = _binding!! override fun provideViewModel(): ViewBindingSampleViewModel = getViewModelFromFactory() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentViewBindingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.load() } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun render(viewState: ViewBindingSampleState) { binding.messageText.text = viewState.message } }
3
Kotlin
24
258
57e91273a319a5e5b92e853b4e6ad9b3564ce60a
1,267
rainbowcake
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day14/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day14 fun launchDay14(testCase: String) { launchPart1(testCase) launchPart2(testCase) } private fun launchPart1(testCase: String) { val input = readInput(testCase) tiltNorth(input) println("Day 14, part 1: ${calcSum(input)}") } private fun launchPart2(testCase: String) { val grid = readInput(testCase) var tilts = 0 val history = mutableListOf<Input>() while (search(grid, history) == -1) { tilts++ history.add(clone(grid)) tiltNorth(grid) tiltWest(grid) tiltSouth(grid) tiltEast(grid) } val goal = 1_000_000_000 val pos = search(grid, history) val diff = tilts - pos var todo = (goal - pos) % diff do { tiltNorth(grid) tiltWest(grid) tiltSouth(grid) tiltEast(grid) todo-- } while (todo > 0) println("Day 14, part 2: ${calcSum(grid)}") } private fun clone(input: Input): Input = input.map { it.toMutableList() }.toMutableList() private fun search(a: Input, bs: List<Input>): Int { bs.forEachIndexed { idx, b -> var res = true loop@ for (row in a.indices) for (col in a[row].indices) { if (a[row][col] != b[row][col]) { res = false break@loop } } if (res) return idx } return -1 } private fun printInput(grid: Input) { println("-----") grid.forEach { println(it.joinToString("")) } } private fun tiltNorth(grid: Input) { for (row in grid.indices) { for (col in grid[row].indices) { if (grid[row][col] == 'O') for (row2 in row - 1 downTo -1) { if (row2 == -1 || grid[row2][col] != '.') { val x = grid[row][col] grid[row][col] = grid[row2 + 1][col] grid[row2 + 1][col] = x break } } } } } private fun tiltWest(grid: Input) { for (col in grid[0].indices) { for (row in grid.indices) { if (grid[row][col] == 'O') for (col2 in col - 1 downTo -1) { if (col2 == -1 || grid[row][col2] != '.') { val x = grid[row][col] grid[row][col] = grid[row][col2 + 1] grid[row][col2 + 1] = x break } } } } } private fun tiltSouth(grid: Input) { for (row in grid.size - 1 downTo 0) { for (col in grid[row].indices) { if (grid[row][col] == 'O') for (row2 in row + 1..grid.size) { if (row2 == grid.size || grid[row2][col] != '.') { val x = grid[row][col] grid[row][col] = grid[row2 - 1][col] grid[row2 - 1][col] = x break } } } } } private fun tiltEast(grid: Input) { for (col in grid[0].size - 1 downTo 0) { for (row in grid.indices) { if (grid[row][col] == 'O') for (col2 in col + 1..grid[0].size) { if (col2 == grid[0].size || grid[row][col2] != '.') { val x = grid[row][col] grid[row][col] = grid[row][col2 - 1] grid[row][col2 - 1] = x break } } } } } private fun calcSum(grid: Input): Int { var result = 0 var counter = grid.size grid.forEach { it.forEach { x -> if (x == 'O') result += counter } counter-- } return result } private fun readInput(testCase: String): Input { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") val rows = mutableListOf<MutableList<Char>>() while (true) { val rawLine = (reader.readLine() ?: break).trim() rows.add(rawLine.toMutableList()) } return rows } private typealias Input = MutableList<MutableList<Char>>
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
4,056
advent-of-code-2023
MIT License
CoordinatorSample/app/src/main/kotlin/open/aqrlei/com/coordinatorsample/MainActivity.kt
AqrLei
156,317,408
false
null
package open.aqrlei.com.coordinatorsample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) toCoordinatorTv.setOnClickListener { CoordinatorActivity.open(this) } } }
0
Kotlin
0
0
f69ed362beb1158880a94b769ba03227d5af439a
468
AndroidDemo
Apache License 2.0
bm_hw_android/app/src/main/java/steffen/de/bm_hw_android/View/MainActivity.kt
colinsteffen
135,430,328
false
null
package steffen.de.bm_hw_android.View import android.support.v7.app.AppCompatActivity import android.os.Bundle import steffen.de.bm_hw_android.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { println("Time: Start") val startTime = System.nanoTime() super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val endTime = System.nanoTime() println("Time: End -> " + ((endTime - startTime) / 1000000)) } }
1
null
1
1
90e57cb9e758a12056c09ca72f1916963a78ca5b
530
ba-xamarin-android
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/request/reminders/RemindersListRequest.kt
uakihir0
794,979,552
false
{"Kotlin": 1210021, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package com.github.seratch.jslack.api.methods.request.reminders import com.github.seratch.jslack.api.methods.SlackApiRequest class RemindersListRequest internal constructor( /** * Authentication token. Requires scope: `reminders:read` */ override var token: String? ) : SlackApiRequest { class RemindersListRequestBuilder internal constructor() { private var token: String? = null fun token(token: String?): RemindersListRequestBuilder { this.token = token return this } fun build(): RemindersListRequest { return RemindersListRequest(token) } override fun toString(): String { return "RemindersListRequest.RemindersListRequestBuilder(token=" + this.token + ")" } } companion object { fun builder(): RemindersListRequestBuilder { return RemindersListRequestBuilder() } } }
5
Kotlin
0
0
4d1299164adc8b8e638b02e0ca7e46afb10709f8
944
kslack
MIT License
Storage/src/main/java/com/vini/storage/StorageModule.kt
vinioliveirasilva
776,456,665
false
{"Kotlin": 54838}
package com.vini.storage import org.koin.core.module.dsl.factoryOf import org.koin.dsl.module val StorageModule = module { factoryOf(::SecureStorage) factoryOf(::LocalStorage) }
0
Kotlin
0
0
3209698be4cb6c2f5c56fdc812e7a7a9ab6a06f8
187
ViniBank
MIT License
storage/src/main/java/app/glucostats/storage/domain/model/Token.kt
vapoyan
875,236,683
false
{"Kotlin": 43557}
package app.glucostats.storage.domain.model /** * Data class representing an access and refresh token pair. * * @property accessToken The access token used for API authentication. * @property refreshToken The refresh token used to obtain a new access * token when the current one expires. */ data class Token( val accessToken: String, val refreshToken: String )
0
Kotlin
0
0
178b72fd5e6d9cba8059b912f9c11469c14737d3
376
Glucostats
FSF All Permissive License
gamedetail/src/main/java/com/oscarg798/amiibowiki/gamedetail/mvi/GameDetailReducer.kt
aliceresponde
296,732,120
true
{"Kotlin": 870948, "Shell": 3484}
/* * Copyright 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * */ package com.oscarg798.amiibowiki.gamedetail.mvi import com.oscarg798.amiibowiki.core.mvi.Reducer import javax.inject.Inject class GameDetailReducer @Inject constructor() : Reducer<GameDetailResult, GameDetailViewState> { override suspend fun reduce( state: GameDetailViewState, from: GameDetailResult ): GameDetailViewState = when (from) { is GameDetailResult.Loading -> state.copy( isLoading = true, isIdling = false, expandedImages = null, gameTrailer = null, error = null ) is GameDetailResult.GameTrailerFound -> state.copy( isLoading = false, isIdling = false, expandedImages = null, gameTrailer = from.trailerId, error = null ) is GameDetailResult.GameFetched -> state.copy( isLoading = false, isIdling = false, gameDetails = from.game, expandedImages = null, gameTrailer = null, error = null ) is GameDetailResult.Error -> state.copy( isLoading = false, isIdling = false, expandedImages = null, error = from.exception ) is GameDetailResult.ImagesExpanded -> state.copy( isIdling = false, isLoading = false, gameTrailer = null, expandedImages = from.images, error = null ) } }
0
null
0
0
d2d0a1c4edaa4031b3fa89af93c3d93a79ffb016
2,572
AmiiboWiki
MIT License
app/src/main/java/com/cesarwillymc/mbcgroup/presentation/home/viewmodel/DetailSurveyViewModel.kt
cesarwillymc
719,282,528
false
{"Kotlin": 161270}
package com.cesarwillymc.mbcgroup.presentation.home.viewmodel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import com.cesarwillymc.mbcgroup.presentation.home.state.DetailSurveyUiState import com.cesarwillymc.mbcgroup.ui.navigation.route.MainRoute import com.cesarwillymc.mbcgroup.util.extension.fromJson import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import javax.inject.Inject /** * Created by <NAME> on 10/10/23. * <EMAIL> * * IOWA, United States. */ @HiltViewModel class DetailSurveyViewModel @Inject constructor( private val savedStateHandle: SavedStateHandle ) : ViewModel() { val detailUiState get() = _detailUiState private val _detailUiState = MutableStateFlow(DetailSurveyUiState()) init { onLoadArgument() } private fun onLoadArgument() { savedStateHandle.get<String>(MainRoute.ARGUMENT)?.let { _detailUiState.update { update -> update.copy(data = fromJson(it)) } } } }
0
Kotlin
0
1
603cc1d2c24c22dd833121b8430e8dd4841e91a1
1,077
MBCGroup
Apache License 2.0
libraries/kitsu/library/src/main/java/com/chesire/nekome/kitsu/library/KitsuLibrary.kt
Chesire
223,272,337
false
{"Kotlin": 740322, "Ruby": 1682}
package com.chesire.nekome.kitsu.library import com.chesire.nekome.core.flags.UserSeriesStatus import com.chesire.nekome.core.models.ErrorDomain import com.chesire.nekome.datasource.series.SeriesDomain import com.chesire.nekome.datasource.series.remote.SeriesApi import com.chesire.nekome.kitsu.asError import com.chesire.nekome.kitsu.library.adapter.UserSeriesStatusAdapter import com.chesire.nekome.kitsu.library.dto.AddResponseDto import com.chesire.nekome.kitsu.library.dto.DtoFactory import com.chesire.nekome.kitsu.library.dto.RetrieveResponseDto import com.chesire.nekome.kitsu.parse import com.github.michaelbull.result.Err import com.github.michaelbull.result.Ok import com.github.michaelbull.result.Result import javax.inject.Inject import okhttp3.MediaType import okhttp3.RequestBody import retrofit2.Response private const val LIMIT = 500 private const val MAX_RETRIES = 3 private const val ANIME_TYPE = "anime" private const val MANGA_TYPE = "manga" private const val MEDIA_TYPE = "application/vnd.api+json" /** * Implementation of the [SeriesApi] for usage with the Kitsu API. */ @Suppress("TooGenericExceptionCaught") class KitsuLibrary @Inject constructor( private val libraryService: KitsuLibraryService, private val map: ResponseDtoMapper, private val entityFactory: DtoFactory ) : SeriesApi { private val userSeriesStatusAdapter = UserSeriesStatusAdapter() override suspend fun retrieveAnime(userId: Int): Result<List<SeriesDomain>, ErrorDomain> = performRetrieveCall(userId, libraryService::retrieveAnimeAsync) override suspend fun retrieveManga(userId: Int): Result<List<SeriesDomain>, ErrorDomain> = performRetrieveCall(userId, libraryService::retrieveMangaAsync) override suspend fun addAnime( userId: Int, seriesId: Int, startingStatus: UserSeriesStatus ): Result<SeriesDomain, ErrorDomain> { val addJson = entityFactory.createAddDto( userId, seriesId, userSeriesStatusAdapter.userSeriesStatusToString(startingStatus), ANIME_TYPE ) val body = RequestBody.create(MediaType.parse(MEDIA_TYPE), addJson) return try { return parseResponse(libraryService.addAnimeAsync(body)) } catch (ex: Exception) { Err(ex.parse()) } } override suspend fun addManga( userId: Int, seriesId: Int, startingStatus: UserSeriesStatus ): Result<SeriesDomain, ErrorDomain> { val addJson = entityFactory.createAddDto( userId, seriesId, userSeriesStatusAdapter.userSeriesStatusToString(startingStatus), MANGA_TYPE ) val body = RequestBody.create(MediaType.parse(MEDIA_TYPE), addJson) return try { return parseResponse(libraryService.addMangaAsync(body)) } catch (ex: Exception) { Err(ex.parse()) } } override suspend fun update( userSeriesId: Int, progress: Int, newStatus: UserSeriesStatus, rating: Int ): Result<SeriesDomain, ErrorDomain> { val updateJson = entityFactory.createUpdateDto( userSeriesId, progress, userSeriesStatusAdapter.userSeriesStatusToString(newStatus), rating ) val body = RequestBody.create(MediaType.parse(MEDIA_TYPE), updateJson) return try { parseResponse(libraryService.updateItemAsync(userSeriesId, body)) } catch (ex: Exception) { Err(ex.parse()) } } override suspend fun delete(userSeriesId: Int): Result<Unit, ErrorDomain> { return try { val response = libraryService.deleteItemAsync(userSeriesId) return if (response.isSuccessful) { Ok(Unit) } else { Err(response.asError()) } } catch (ex: Exception) { Err(ex.parse()) } } @Suppress("ComplexMethod", "LongMethod") private suspend fun performRetrieveCall( userId: Int, execute: suspend (userId: Int, offset: Int, limit: Int) -> Response<RetrieveResponseDto> ): Result<List<SeriesDomain>, ErrorDomain> { val models = mutableListOf<SeriesDomain>() var offset = 0 var page = 0 var retries = 0 var executeAgain: Boolean var errorResponse = ErrorDomain("", 200) do { executeAgain = false val response: Response<RetrieveResponseDto> try { response = execute(userId, offset, LIMIT) } catch (ex: Exception) { return Err(ex.parse()) } val body = response.body() if (response.isSuccessful && body != null) { models.addAll(buildSeries(body)) retries = 0 if (body.links.next.isNotEmpty()) { page++ offset = LIMIT * page executeAgain = true } } else { if (retries < MAX_RETRIES) { retries++ executeAgain = true } else { errorResponse = response.asError() } } } while (executeAgain) return if (retries == MAX_RETRIES && models.isEmpty()) { Err( ErrorDomain(errorResponse.message, errorResponse.code) ) } else { Ok(models) } } private fun buildSeries(body: RetrieveResponseDto): List<SeriesDomain> { return body.data.mapNotNull { if (body.included == null) { null } else { map.toSeriesDomain(AddResponseDto(it, body.included)) } } } private fun parseResponse(response: Response<AddResponseDto>): Result<SeriesDomain, ErrorDomain> { return if (response.isSuccessful) { response.body()?.let { entity -> Ok(requireNotNull(map.toSeriesDomain(entity))) } ?: Err(ErrorDomain.emptyResponse) } else { Err(response.asError()) } } }
24
Kotlin
42
471
191def4011f659972951d3766bfb4e5af4076ab1
6,268
Nekome
Apache License 2.0
src/main/kotlin/dev/mbo/linkshortener2/domain/url/UrlCreateDto.kt
mbogner
679,798,073
false
null
/* * Copyright (c) 2023. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.mbo.linkshortener2.domain.url import jakarta.validation.constraints.NotBlank import java.net.URL internal data class UrlCreateDto( @NotBlank val url: URL, )
0
Kotlin
0
0
7b5b07821698196c1dd0c0b16ece08c7e43a6d86
767
link-shortener2
Apache License 2.0
fields/src/commonMain/kotlin/geo/AddressManager.kt
aSoft-Ltd
695,480,107
false
{"Kotlin": 18492}
package geo import symphony.BaseField import kollections.List interface AddressManager { fun entries(country: Country?): List<BaseField<String>> fun labels(country: Country) : List<String> }
0
Kotlin
0
0
b7c5704b364663fdafefdfe6a055f273eb0bd204
202
geo-client
MIT License
app/src/main/java/id/yanuar/weather/mvp/CompositeDisposablePresenter.kt
januaripin
146,331,939
false
null
package id.yanuar.weather.mvp import io.reactivex.disposables.CompositeDisposable /** * Created by Yanuar Arifin * halo@yanuar.id */ open class CompositeDisposablePresenter<V : MvpView> : MvpPresenter<V>() { var compositeDisposable = CompositeDisposable() override fun detachView() { super.detachView() if (compositeDisposable.isDisposed.not()) compositeDisposable.dispose() } }
0
Kotlin
0
0
bebf7539c84a5ce9c063d7a4faa5a78e8f9c8c73
412
weather
MIT License
app/src/main/java/com/huhx0015/androidbooster/architecture/mvi/BaseViewModel.kt
huhx0015
95,202,520
false
null
package com.huhx0015.androidbooster.architecture.mvi interface BaseViewModel<T>
0
Kotlin
3
4
19c5b41eab5efedf4f404f660cc15e612bb5edb1
80
AndroidBooster
Apache License 2.0
app/src/main/java/com/ningsk/zrdc/ui/main/query/adapter/QueryShowFieldSelectAdapter.kt
kicker315
334,635,124
false
null
package com.ningsk.zrdc.ui.main.query.adapter import android.widget.CheckBox import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.ningsk.zrdc.R import com.ningsk.zrdc.entity.bean.IField /** * ======================================= * 属性值多选适配器 * Create by ningsikai 2020/7/3:9:03 AM * ======================================== */ class QueryShowFieldSelectAdapter : BaseQuickAdapter<IField, BaseViewHolder>(R.layout.item_layer_select_list, null) { override fun convert(holder: BaseViewHolder, item: IField) { holder.setText(R.id.tv_filename, if (item.dltb != null) {item.dltb!!.zdmc + "(${item.dltb!!.zddm})" } else item.field.name) val checkbox = holder.getView<CheckBox>(R.id.checkbox) checkbox.isChecked = item.checked != 0 } }
0
null
0
0
b82990a7edac9ccef42ff0ad69520a8a3d14819b
846
gis
Apache License 2.0
fabric/src/main/kotlin/com/your_name/mod/your_mod_id/fabric/FabricCommon.kt
A11v1r15
815,434,363
false
{"Kotlin": 866}
package com.your_name.mod.your_mod_id.fabric import com.your_name.mod.your_mod_id.YourMod import net.fabricmc.api.ModInitializer class FabricCommon : ModInitializer { override fun onInitialize() { YourMod.initialize() } }
0
Kotlin
0
0
7688fc2f2a5d82a0971c982b931f7b7d18fc2868
239
Vanilla-Apricorn
MIT License
canvas_lp/src/main/java/com/angcyo/canvas/laser/pecker/dslitem/TypefaceItem.kt
angcyo
229,037,684
false
null
package com.angcyo.canvas.laser.pecker.dslitem import android.graphics.Typeface import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.canvas.laser.pecker.R import com.angcyo.widget.DslViewHolder /** * 字体展示的item * @author <a href="mailto:angcyo@126.com">angcyo</a> * @since 2022/04/18 */ class TypefaceItem : DslAdapterItem() { /**显示的名字*/ var displayName: String? = null /**预览的文本*/ var previewText: String? = null /**字体*/ var typeface: Typeface? = null init { itemLayoutId = R.layout.item_canvas_typeface_layout } override fun onItemBind( itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem, payloads: List<Any> ) { super.onItemBind(itemHolder, itemPosition, adapterItem, payloads) itemHolder.visible(R.id.lib_check_view, itemIsSelected) itemHolder.tv(R.id.text_view)?.apply { text = previewText this.typeface = this@TypefaceItem.typeface } itemHolder.tv(R.id.name_view)?.apply { text = displayName } } }
0
Kotlin
4
3
13dc66c06abd72995fb8393655bb69544c259248
1,114
UICoreEx
MIT License