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
playground/sandbox-compose/src/test/kotlin/com/sdds/playground/sandbox/ComposeCheckBoxScreenshotTest.kt
salute-developers
765,665,583
false
{"Kotlin": 1736676}
package com.sdds.playground.sandbox import com.github.takahirom.roborazzi.RobolectricDeviceQualifiers import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewCheckedSizeSmall import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewOffSizeSmall import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewOnSizeMediumNoDesc import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewOnSizeMediumNoLabel import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewSizeMediumNoLabelAndDesc import com.sdds.playground.sandbox.checkbox.SandboxCheckBoxPreviewUncheckedSizeMedium import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode @GraphicsMode(GraphicsMode.Mode.NATIVE) @Config(sdk = [SDK_NUMBER], qualifiers = RobolectricDeviceQualifiers.Pixel6) @RunWith(RobolectricTestRunner::class) class ComposeCheckBoxScreenshotTest : RoborazziConfig() { /** * Запуск скриншот тестов с использованием Preview */ @Test fun testCheckBoxUncheckedSizeMedium() { composeTestRule.setContent { SandboxCheckBoxPreviewUncheckedSizeMedium() } } @Test fun testCheckBoxCheckedSizeSmallDark() { composeTestRule.setContent { SandboxTheme(darkTheme = true) { SandboxCheckBoxPreviewCheckedSizeSmall() } } } @Test fun testCheckBoxOffSizeSmall() { composeTestRule.setContent { SandboxCheckBoxPreviewOffSizeSmall() } } @Test fun testCheckBoxOnSizeMediumNoDesc() { composeTestRule.setContent { SandboxCheckBoxPreviewOnSizeMediumNoDesc() } } @Test fun testCheckBoxOnSizeMediumNoLabel() { composeTestRule.setContent { SandboxCheckBoxPreviewOnSizeMediumNoLabel() } } @Test fun testCheckBoxSizeMediumNoLabelAndDesc() { composeTestRule.setContent { SandboxCheckBoxPreviewSizeMediumNoLabelAndDesc() } } }
3
Kotlin
0
1
a5209f66c4fdd76d1f2373502a2705697aaf70e4
2,127
plasma-android
MIT License
anissia-app-external-api/src/main/kotlin/anissia/dto/AccountUserDto.kt
qqq-tech
366,089,141
true
{"Kotlin": 177106, "HTML": 2740}
package anissia.dto import anissia.rdb.domain.Account import anissia.rdb.domain.AccountRole import java.time.LocalDateTime data class AccountUserDto ( var email: String = "", var name: String = "", var regDt: LocalDateTime = LocalDateTime.now(), var roles: Set<AccountRole> = setOf(), ) { companion object { fun cast(account: Account) = AccountUserDto( email = account.email, name = account.name, regDt = account.regDt, roles = account.roles ) } }
0
null
0
0
d0d1e9858bf2807b9df12c6c40b598eb64350112
537
anissia-core
Creative Commons Attribution 4.0 International
feature/login/imp/src/main/java/com/vpopov/movienow/feature/login/imp/data/LoginRepository.kt
Va1erii
461,271,627
false
null
package com.vpopov.movienow.feature.login.imp.data import javax.inject.Inject interface LoginRepository { fun login() } class LoginRepositoryImp @Inject constructor( private val loginService: LoginService ) : LoginRepository { override fun login() { loginService.requestToken() } }
4
Kotlin
0
0
ab03f4cc5484548b0d40486fac7b90c1c8e75470
308
movie-now
MIT License
feature/login/imp/src/main/java/com/vpopov/movienow/feature/login/imp/data/LoginRepository.kt
Va1erii
461,271,627
false
null
package com.vpopov.movienow.feature.login.imp.data import javax.inject.Inject interface LoginRepository { fun login() } class LoginRepositoryImp @Inject constructor( private val loginService: LoginService ) : LoginRepository { override fun login() { loginService.requestToken() } }
4
Kotlin
0
0
ab03f4cc5484548b0d40486fac7b90c1c8e75470
308
movie-now
MIT License
app/storybook/src/main/java/com/yourssu/storybook/component/SearchTopBarViewModel.kt
yourssu
364,290,281
false
null
package com.yourssu.storybook.component import android.app.Application import android.view.KeyEvent import android.widget.TextView import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.yourssu.design.system.atom.Toggle import com.yourssu.storybook.BaseViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.launch class SearchTopBarViewModel(application: Application): BaseViewModel(application) { private val _eventFlow = MutableSharedFlow<Event>() val eventFlow: SharedFlow<Event> = _eventFlow private val _textInSearchTopBar = MutableLiveData("") val textInSearchTopBar: LiveData<String> = _textInSearchTopBar private val _placeholderText = MutableLiveData("") val placeholderText: LiveData<String> = _placeholderText val initText = "initText" private val _isDisable = MutableLiveData(false) val isDisable: LiveData<Boolean> = _isDisable val enableSelectListener = object : Toggle.SelectedListener { override fun onSelected(boolean: Boolean) { _isDisable.value = boolean } } fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { _textInSearchTopBar.value = s.toString() } fun onPlaceholderTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { _placeholderText.value = s.toString() } fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean { event(Event.KeyboardAction(actionId)) return true } fun onLeftArrowButtonClicked() { event(Event.LeftArrowButtonClicked) } private fun event(event: Event) { viewModelScope.launch { _eventFlow.emit(event) } } sealed class Event { object LeftArrowButtonClicked: Event() class KeyboardAction(val actionId: Int): Event() } }
9
null
2
9
58364077175f882def5108e654f51667b9d3af36
1,976
YDS-Android
MIT License
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/discovery/dotnetSdk/DotnetSdksProvider.kt
JetBrains
49,584,664
false
{"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
package jetbrains.buildServer.dotnet.discovery.dotnetSdk import java.io.File interface DotnetSdksProvider { fun getSdks(dotnetExecutable: File): Sequence<DotnetSdk> }
3
Kotlin
25
94
cdecbf2c7721a40265a031453262614809d5378d
175
teamcity-dotnet-plugin
Apache License 2.0
libraries/image/src/main/java/de/schnettler/scrobbler/image/di/SpotifyApiModule.kt
nschnettler
260,203,355
false
{"Kotlin": 440825}
package de.schnettler.scrobbler.image.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import de.schnettler.scrobbler.image.api.SpotifyApi import de.schnettler.scrobbler.network.spotify.annotation.retrofit.AuthorizedSpotifyRetrofitClient import retrofit2.Retrofit @Module @InstallIn(SingletonComponent::class) class SpotifyApiModule { @Provides fun providesSearchService( @AuthorizedSpotifyRetrofitClient retrofit: Retrofit ): SpotifyApi = retrofit.create(SpotifyApi::class.java) }
10
Kotlin
5
57
523d0b739901b971fd41e09258dcab6dcb1c8e58
580
Compose-Scrobbler
Apache License 2.0
app/src/main/java/com/ono/streamer/di/AppMainModule.kt
MuhammadAounAnwar
544,583,769
false
null
package com.ono.streamer.di import android.app.Application import android.content.Context import com.ono.streamer.StreamerClass import dagger.Binds import dagger.Module @Module(includes = [AppActivitiesModule::class, AppNetworkModule::class]) abstract class AppMainModule { @Binds abstract fun bindsApp(streamerClass: StreamerClass): Application @Binds abstract fun bindsContext(application: Application): Context }
0
Kotlin
0
0
4e6f44b2d6c8052c864d517276cf1c31683eec7b
437
Streamer
MIT License
app/src/main/java/com/ono/streamer/di/AppMainModule.kt
MuhammadAounAnwar
544,583,769
false
null
package com.ono.streamer.di import android.app.Application import android.content.Context import com.ono.streamer.StreamerClass import dagger.Binds import dagger.Module @Module(includes = [AppActivitiesModule::class, AppNetworkModule::class]) abstract class AppMainModule { @Binds abstract fun bindsApp(streamerClass: StreamerClass): Application @Binds abstract fun bindsContext(application: Application): Context }
0
Kotlin
0
0
4e6f44b2d6c8052c864d517276cf1c31683eec7b
437
Streamer
MIT License
app/src/main/java/academy/bangkit/lanting/utils/ViewExt.kt
fhrii
368,801,393
false
null
package academy.bangkit.lanting.utils import academy.bangkit.lanting.R import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.EditText import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.request.target.Target fun EditText.setOnChangeListener(callback: (text: String?) -> Unit) { this.addTextChangedListener(object : TextWatcher { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { callback(s?.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun afterTextChanged(s: Editable?) {} }) } fun ImageView.setImageFromUrl(url: String) { Glide.with(this.context) .load(url) .placeholder(R.drawable.ic_image_loading) .override(Target.SIZE_ORIGINAL) .into(this) } fun View.setVisible(state: Boolean) { this.visibility = if (state) View.VISIBLE else View.GONE }
1
Kotlin
1
1
224efe4e6cda949249e0b543aac56e9d5d57cd35
1,034
lanting
MIT License
src/test/kotlin/org/ktlib/BootstrapTests.kt
ktlib-org
713,606,396
false
{"Kotlin": 102290}
package org.ktlib import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class BootstrapTests : StringSpec({ "boostrap called" { BootstrapRunner.init() System.getProperty("boostrap-called") shouldBe "true" } })
0
Kotlin
0
0
9e60ae44885ac075d4df37b24ed7a5485c597166
260
core
Apache License 2.0
app/src/test/kotlin/com/github/starter/core/filters/RequestTimingFilters.kt
skhatri
250,538,313
false
null
package com.github.starter.core.filters; class RequestTimingFilters { private constructor() { } companion object { fun newInstance(log: Boolean): RequestTimingFilter { return RequestTimingFilter(log); } } }
1
null
3
7
3e2728a126b136c24cbb2277df9cbf928b341aff
254
microservices-starter-kotlin
Apache License 2.0
app/src/test/kotlin/com/github/starter/core/filters/RequestTimingFilters.kt
skhatri
250,538,313
false
null
package com.github.starter.core.filters; class RequestTimingFilters { private constructor() { } companion object { fun newInstance(log: Boolean): RequestTimingFilter { return RequestTimingFilter(log); } } }
1
null
3
7
3e2728a126b136c24cbb2277df9cbf928b341aff
254
microservices-starter-kotlin
Apache License 2.0
idea/testData/formatter/EmptyLineBetweenEnumEntries.kt
JakeWharton
99,388,807
true
null
enum class E1 { F, S, T } enum class E2 { F, S, T } enum class E3 { F, S, T } enum class E4 { F { }, S, T } enum class E5 { F, S {}, T } enum class E6 { F, S, T {} } enum class E7 { F { }, S, T } enum class E8 { A, // A B // B } // SET_TRUE: KEEP_LINE_BREAKS
0
Kotlin
4
83
4383335168338df9bbbe2a63cb213a68d0858104
312
kotlin
Apache License 2.0
client/src/test/kotlin/no/nav/su/se/bakover/client/oppdrag/simulering/SimuleringRequestBuilderTest.kt
navikt
227,366,088
false
{"Kotlin": 9509213, "Shell": 4372, "TSQL": 1233, "Dockerfile": 1211}
package no.nav.su.se.bakover.client.oppdrag.simulering import arrow.core.nonEmptyListOf import io.kotest.matchers.shouldBe import no.nav.su.se.bakover.client.oppdrag.utbetaling.UtbetalingRequest import no.nav.su.se.bakover.client.oppdrag.utbetaling.UtbetalingRequestTest import no.nav.su.se.bakover.client.oppdrag.utbetaling.toUtbetalingRequest import no.nav.su.se.bakover.common.Rekkefølge import no.nav.su.se.bakover.common.extensions.desember import no.nav.su.se.bakover.common.extensions.februar import no.nav.su.se.bakover.common.extensions.mai import no.nav.su.se.bakover.common.extensions.oktober import no.nav.su.se.bakover.common.extensions.september import no.nav.su.se.bakover.common.extensions.startOfDay import no.nav.su.se.bakover.common.tid.periode.Periode import no.nav.su.se.bakover.common.tid.periode.år import no.nav.su.se.bakover.test.fixedClock import no.nav.su.se.bakover.test.xml.shouldBeSimilarXmlTo import no.nav.system.os.tjenester.simulerfpservice.simulerfpserviceservicetypes.Oppdrag import no.nav.system.os.tjenester.simulerfpservice.simulerfpserviceservicetypes.Oppdragslinje import no.nav.system.os.tjenester.simulerfpservice.simulerfpserviceservicetypes.SimulerBeregningRequest import org.junit.jupiter.api.Test import økonomi.domain.avstemming.Avstemmingsnøkkel import økonomi.domain.utbetaling.Utbetalingslinje import java.math.BigDecimal import java.time.Clock internal class SimuleringRequestBuilderTest { @Test fun `bygger simulering request til bruker uten eksisterende oppdragslinjer`() { val utbetalingsRequest = UtbetalingRequestTest.utbetalingRequestFørstegangsutbetaling.oppdragRequest val actual = buildXmlRequestBody( simuleringsperiode = år(2020), request = utbetalingsRequest, ) val expected = """ <ns2:simulerBeregningRequest xmlns:ns2="http://nav.no/system/os/tjenester/simulerFpService/simulerFpServiceGrensesnitt" xmlns:ns3="http://nav.no/system/os/entiteter/oppdragSkjema"> <request> <oppdrag> <kodeEndring>NY</kodeEndring> <kodeFagomraade>SUUFORE</kodeFagomraade> <fagsystemId>2021</fagsystemId> <utbetFrekvens>MND</utbetFrekvens> <oppdragGjelderId>12345678911</oppdragGjelderId> <datoOppdragGjelderFom>1970-01-01</datoOppdragGjelderFom> <saksbehId>SU</saksbehId> <ns3:enhet> <typeEnhet>BOS</typeEnhet> <enhet>8020</enhet> <datoEnhetFom>1970-01-01</datoEnhetFom> </ns3:enhet> <oppdragslinje> <kodeEndringLinje>NY</kodeEndringLinje> <delytelseId>${utbetalingsRequest.oppdragslinjer[0].delytelseId}</delytelseId> <kodeKlassifik>SUUFORE</kodeKlassifik> <datoVedtakFom>2020-01-01</datoVedtakFom> <datoVedtakTom>2020-04-30</datoVedtakTom> <sats>1000</sats> <fradragTillegg>T</fradragTillegg> <typeSats>MND</typeSats> <brukKjoreplan>N</brukKjoreplan> <saksbehId>SU</saksbehId> <utbetalesTilId>12345678911</utbetalesTilId> <henvisning>${utbetalingsRequest.utbetalingsId()}</henvisning> <ns3:grad> <typeGrad>UFOR</typeGrad> <grad>50</grad> </ns3:grad> <ns3:attestant> <attestantId>SU</attestantId> </ns3:attestant> </oppdragslinje> <oppdragslinje> <kodeEndringLinje>NY</kodeEndringLinje> <delytelseId>${utbetalingsRequest.oppdragslinjer[1].delytelseId}</delytelseId> <kodeKlassifik>SUUFORE</kodeKlassifik> <datoVedtakFom>2020-05-01</datoVedtakFom> <datoVedtakTom>2020-12-31</datoVedtakTom> <sats>1000</sats> <fradragTillegg>T</fradragTillegg> <typeSats>MND</typeSats> <brukKjoreplan>N</brukKjoreplan> <saksbehId>SU</saksbehId> <utbetalesTilId>12345678911</utbetalesTilId> <henvisning>${utbetalingsRequest.utbetalingsId()}</henvisning> <refFagsystemId>2021</refFagsystemId> <refDelytelseId>${utbetalingsRequest.oppdragslinjer[0].delytelseId}</refDelytelseId> <ns3:grad> <typeGrad>UFOR</typeGrad> <grad>70</grad> </ns3:grad> <ns3:attestant> <attestantId>SU</attestantId> </ns3:attestant> </oppdragslinje> </oppdrag> <simuleringsPeriode> <datoSimulerFom>2020-01-01</datoSimulerFom> <datoSimulerTom>2020-12-31</datoSimulerTom> </simuleringsPeriode> </request> </ns2:simulerBeregningRequest> """.trimIndent() actual.shouldBeSimilarXmlTo(expected, true) } @Test fun `bygger simulering request ved endring av eksisterende oppdragslinjer`() { val linjeSomSkalEndres = UtbetalingRequestTest.nyUtbetaling.sisteUtbetalingslinje() val linjeMedEndring = Utbetalingslinje.Endring.Opphør( utbetalingslinjeSomSkalEndres = linjeSomSkalEndres, virkningsperiode = Periode.create(1.februar(2020), linjeSomSkalEndres.periode.tilOgMed), clock = fixedClock, rekkefølge = Rekkefølge.start(), ) val utbetalingMedEndring = UtbetalingRequestTest.nyUtbetaling.copy( avstemmingsnøkkel = Avstemmingsnøkkel(18.september(2020).startOfDay()), utbetalingslinjer = nonEmptyListOf(linjeMedEndring), ) val utbetalingsRequest = toUtbetalingRequest(utbetalingMedEndring).oppdragRequest val acutal = buildXmlRequestBody( simuleringsperiode = Periode.create( fraOgMed = 1.februar(2020), tilOgMed = 31.desember(2020), ), request = utbetalingsRequest, ) val expected = """ <ns2:simulerBeregningRequest xmlns:ns2="http://nav.no/system/os/tjenester/simulerFpService/simulerFpServiceGrensesnitt" xmlns:ns3="http://nav.no/system/os/entiteter/oppdragSkjema"> <request> <oppdrag> <kodeEndring>ENDR</kodeEndring> <kodeFagomraade>SUUFORE</kodeFagomraade> <fagsystemId>2021</fagsystemId> <utbetFrekvens>MND</utbetFrekvens> <oppdragGjelderId>12345678911</oppdragGjelderId> <datoOppdragGjelderFom>1970-01-01</datoOppdragGjelderFom> <saksbehId>SU</saksbehId> <ns3:enhet> <typeEnhet>BOS</typeEnhet> <enhet>8020</enhet> <datoEnhetFom>1970-01-01</datoEnhetFom> </ns3:enhet> <oppdragslinje> <kodeEndringLinje>ENDR</kodeEndringLinje> <kodeStatusLinje>OPPH</kodeStatusLinje> <datoStatusFom>2020-02-01</datoStatusFom> <delytelseId>${utbetalingsRequest.oppdragslinjer[0].delytelseId}</delytelseId> <kodeKlassifik>SUUFORE</kodeKlassifik> <datoVedtakFom>2020-05-01</datoVedtakFom> <datoVedtakTom>2020-12-31</datoVedtakTom> <sats>1000</sats> <fradragTillegg>T</fradragTillegg> <typeSats>MND</typeSats> <brukKjoreplan>N</brukKjoreplan> <saksbehId>SU</saksbehId> <utbetalesTilId>12345678911</utbetalesTilId> <henvisning>${utbetalingsRequest.utbetalingsId()}</henvisning> <ns3:grad> <typeGrad>UFOR</typeGrad> <grad>70</grad> </ns3:grad> <ns3:attestant> <attestantId>SU</attestantId> </ns3:attestant> </oppdragslinje> </oppdrag> <simuleringsPeriode> <datoSimulerFom>2020-02-01</datoSimulerFom> <datoSimulerTom>2020-12-31</datoSimulerTom> </simuleringsPeriode> </request> </ns2:simulerBeregningRequest> """ acutal.shouldBeSimilarXmlTo(expected, true) } @Test fun `opphører fra oktober og ut men simulerer hele siste utbetalingslinje`() { val linjeSomSkalEndres = UtbetalingRequestTest.nyUtbetaling.sisteUtbetalingslinje() val linjeMedEndring = Utbetalingslinje.Endring.Opphør( utbetalingslinjeSomSkalEndres = linjeSomSkalEndres, virkningsperiode = Periode.create(1.oktober(2020), linjeSomSkalEndres.periode.tilOgMed), clock = Clock.systemUTC(), rekkefølge = Rekkefølge.start(), ) val utbetalingMedEndring = UtbetalingRequestTest.nyUtbetaling.copy( avstemmingsnøkkel = Avstemmingsnøkkel(18.september(2020).startOfDay()), utbetalingslinjer = nonEmptyListOf(linjeMedEndring), ) val utbetalingsRequest = toUtbetalingRequest(utbetalingMedEndring).oppdragRequest val actual = buildXmlRequestBody( simuleringsperiode = Periode.create( fraOgMed = 1.mai(2020), tilOgMed = 31.desember(2020), ), request = utbetalingsRequest, ) val expected = """ <ns2:simulerBeregningRequest xmlns:ns2="http://nav.no/system/os/tjenester/simulerFpService/simulerFpServiceGrensesnitt" xmlns:ns3="http://nav.no/system/os/entiteter/oppdragSkjema"> <request> <oppdrag> <kodeEndring>ENDR</kodeEndring> <kodeFagomraade>SUUFORE</kodeFagomraade> <fagsystemId>2021</fagsystemId> <utbetFrekvens>MND</utbetFrekvens> <oppdragGjelderId>12345678911</oppdragGjelderId> <datoOppdragGjelderFom>1970-01-01</datoOppdragGjelderFom> <saksbehId>SU</saksbehId> <ns3:enhet> <typeEnhet>BOS</typeEnhet> <enhet>8020</enhet> <datoEnhetFom>1970-01-01</datoEnhetFom> </ns3:enhet> <oppdragslinje> <kodeEndringLinje>ENDR</kodeEndringLinje> <kodeStatusLinje>OPPH</kodeStatusLinje> <datoStatusFom>2020-10-01</datoStatusFom> <delytelseId>${utbetalingsRequest.oppdragslinjer[0].delytelseId}</delytelseId> <kodeKlassifik>SUUFORE</kodeKlassifik> <datoVedtakFom>2020-05-01</datoVedtakFom> <datoVedtakTom>2020-12-31</datoVedtakTom> <sats>1000</sats> <fradragTillegg>T</fradragTillegg> <typeSats>MND</typeSats> <brukKjoreplan>N</brukKjoreplan> <saksbehId>SU</saksbehId> <utbetalesTilId>12345678911</utbetalesTilId> <henvisning>${utbetalingsRequest.utbetalingsId()}</henvisning> <ns3:grad> <typeGrad>UFOR</typeGrad> <grad>70</grad> </ns3:grad> <ns3:attestant> <attestantId>SU</attestantId> </ns3:attestant> </oppdragslinje> </oppdrag> <simuleringsPeriode> <datoSimulerFom>2020-05-01</datoSimulerFom> <datoSimulerTom>2020-12-31</datoSimulerTom> </simuleringsPeriode> </request> </ns2:simulerBeregningRequest> """ actual.shouldBeSimilarXmlTo(expected, true) } @Suppress("unused") private fun SimulerBeregningRequest.SimuleringsPeriode.assert(fraOgMed: String, tilOgMed: String) { this.datoSimulerFom shouldBe fraOgMed this.datoSimulerTom shouldBe tilOgMed } @Suppress("unused") private fun Oppdragslinje.assert(oppdragslinje: UtbetalingRequest.Oppdragslinje) { delytelseId shouldBe oppdragslinje.delytelseId kodeEndringLinje shouldBe oppdragslinje.kodeEndringLinje.value sats shouldBe BigDecimal(oppdragslinje.sats) typeSats shouldBe oppdragslinje.typeSats.value datoVedtakFom shouldBe oppdragslinje.datoVedtakFom datoVedtakTom shouldBe oppdragslinje.datoVedtakTom utbetalesTilId shouldBe oppdragslinje.utbetalesTilId refDelytelseId shouldBe oppdragslinje.refDelytelseId refFagsystemId shouldBe oppdragslinje.refFagsystemId kodeKlassifik shouldBe oppdragslinje.kodeKlassifik fradragTillegg.value() shouldBe oppdragslinje.fradragTillegg.value saksbehId shouldBe oppdragslinje.saksbehId brukKjoreplan shouldBe oppdragslinje.brukKjoreplan.value attestant[0].attestantId shouldBe oppdragslinje.saksbehId kodeStatusLinje?.value() shouldBe oppdragslinje.kodeStatusLinje?.value datoStatusFom shouldBe oppdragslinje.datoStatusFom } @Suppress("unused") private fun Oppdrag.assert(utbetalingsRequest: UtbetalingRequest.OppdragRequest) { oppdragGjelderId shouldBe utbetalingsRequest.oppdragGjelderId saksbehId shouldBe utbetalingsRequest.saksbehId fagsystemId shouldBe utbetalingsRequest.fagsystemId kodeEndring shouldBe utbetalingsRequest.kodeEndring.value kodeFagomraade shouldBe utbetalingsRequest.kodeFagomraade utbetFrekvens shouldBe utbetalingsRequest.utbetFrekvens.value datoOppdragGjelderFom shouldBe utbetalingsRequest.datoOppdragGjelderFom enhet[0].datoEnhetFom shouldBe utbetalingsRequest.oppdragsEnheter[0].datoEnhetFom enhet[0].enhet shouldBe utbetalingsRequest.oppdragsEnheter[0].enhet enhet[0].typeEnhet shouldBe utbetalingsRequest.oppdragsEnheter[0].typeEnhet } }
1
Kotlin
1
1
e0193ea73a8771537b04819641348093f011c1f8
13,075
su-se-bakover
MIT License
domain/src/main/kotlin/com/seanshubin/condorcet/backend/domain/VoterElectionCandidateRank.kt
SeanShubin
238,518,165
false
{"XML": 1, "Maven POM": 22, "Ignore List": 1, "Markdown": 9, "Shell": 4, "Text": 25, "Kotlin": 204, "HTML": 21, "Java": 21, "Python": 1, "SVG": 2, "SQL": 65, "JSON": 2}
package com.seanshubin.condorcet.backend.domain data class VoterElectionCandidateRank(val voter: String, val election: String, val candidate: String, val rank: Int)
1
null
1
1
c6dd3e86d9f722829c57d215fcfa7cb18b7955cd
166
condorcet-backend
The Unlicense
identity/src/main/java/com/stripe/android/identity/navigation/IdentityNavGraph.kt
stripe
6,926,049
false
null
package com.stripe.android.identity.navigation import android.util.Log import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalBottomSheetLayout import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Scaffold import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.stripe.android.camera.AppSettingsOpenable import com.stripe.android.camera.CameraPermissionEnsureable import com.stripe.android.identity.FallbackUrlLauncher import com.stripe.android.identity.IdentityVerificationSheet import com.stripe.android.identity.R import com.stripe.android.identity.VerificationFlowFinishable import com.stripe.android.identity.analytics.IdentityAnalyticsRequestFactory import com.stripe.android.identity.ui.BottomSheet import com.stripe.android.identity.ui.ConfirmationScreen import com.stripe.android.identity.ui.ConsentScreen import com.stripe.android.identity.ui.CountryNotListedScreen import com.stripe.android.identity.ui.DebugScreen import com.stripe.android.identity.ui.DocWarmupScreen import com.stripe.android.identity.ui.DocumentScanScreen import com.stripe.android.identity.ui.ErrorScreen import com.stripe.android.identity.ui.ErrorScreenButton import com.stripe.android.identity.ui.IdentityTopAppBar import com.stripe.android.identity.ui.IdentityTopBarState import com.stripe.android.identity.ui.IndividualScreen import com.stripe.android.identity.ui.IndividualWelcomeScreen import com.stripe.android.identity.ui.InitialLoadingScreen import com.stripe.android.identity.ui.OTPScreen import com.stripe.android.identity.ui.SelfieScanScreen import com.stripe.android.identity.ui.SelfieWarmupScreen import com.stripe.android.identity.ui.UploadScreen import com.stripe.android.identity.viewmodel.BottomSheetViewModel import com.stripe.android.identity.viewmodel.DocumentScanViewModel import com.stripe.android.identity.viewmodel.IdentityViewModel import com.stripe.android.identity.viewmodel.SelfieScanViewModel import com.stripe.android.uicore.stripeShapes import com.stripe.android.uicore.utils.collectAsState import kotlinx.coroutines.launch @Composable @ExperimentalMaterialApi internal fun IdentityNavGraph( navController: NavHostController = rememberNavController(), identityViewModel: IdentityViewModel, fallbackUrlLauncher: FallbackUrlLauncher, appSettingsOpenable: AppSettingsOpenable, cameraPermissionEnsureable: CameraPermissionEnsureable, verificationFlowFinishable: VerificationFlowFinishable, documentScanViewModelFactory: DocumentScanViewModel.DocumentScanViewModelFactory, selfieScanViewModelFactory: SelfieScanViewModel.SelfieScanViewModelFactory, onTopBarNavigationClick: () -> Unit, topBarState: IdentityTopBarState, onNavControllerCreated: (NavController) -> Unit ) { val coroutineScope = rememberCoroutineScope() LaunchedEffect(Unit) { onNavControllerCreated(navController) } Scaffold( topBar = { IdentityTopAppBar(topBarState, onTopBarNavigationClick) } ) { contentPadding -> NavHost( navController = navController, modifier = Modifier.padding(contentPadding), startDestination = InitialLoadingDestination.destinationRoute.route ) { screen(DebugDestination.ROUTE) { DebugScreen( navController = navController, identityViewModel = identityViewModel, verificationFlowFinishable = verificationFlowFinishable ) } screen(InitialLoadingDestination.ROUTE) { InitialLoadingScreen( navController = navController, identityViewModel = identityViewModel, fallbackUrlLauncher = fallbackUrlLauncher ) } screen(IndividualWelcomeDestination.ROUTE) { IndividualWelcomeScreen( navController = navController, identityViewModel = identityViewModel ) } screen(ConsentDestination.ROUTE) { ConsentScreen( navController = navController, identityViewModel = identityViewModel ) } screen(DocWarmupDestination.ROUTE) { DocWarmupScreen( navController = navController, identityViewModel = identityViewModel, cameraPermissionEnsureable = cameraPermissionEnsureable ) } screen(DocumentScanDestination.ROUTE) { val documentScanViewModel: DocumentScanViewModel = viewModel(factory = documentScanViewModelFactory) ScanDestinationEffect( lifecycleOwner = it, identityScanViewModel = documentScanViewModel ) DocumentScanScreen( navController = navController, identityViewModel = identityViewModel, documentScanViewModel = documentScanViewModel ) } screen(SelfieWarmupDestination.ROUTE) { SelfieWarmupScreen( navController = navController, identityViewModel = identityViewModel ) } screen(SelfieDestination.ROUTE) { val selfieScanViewModel: SelfieScanViewModel = viewModel(factory = selfieScanViewModelFactory) ScanDestinationEffect( lifecycleOwner = it, identityScanViewModel = selfieScanViewModel ) SelfieScanScreen( navController = navController, identityViewModel = identityViewModel, selfieScanViewModel = selfieScanViewModel ) } screen(DocumentUploadDestination.ROUTE) { UploadScreen( navController = navController, identityViewModel = identityViewModel, ) } screen(IndividualDestination.ROUTE) { IndividualScreen( navController = navController, identityViewModel = identityViewModel ) } screen(ConfirmationDestination.ROUTE) { ConfirmationScreen( navController = navController, identityViewModel = identityViewModel, verificationFlowFinishable = verificationFlowFinishable ) } screen(CountryNotListedDestination.ROUTE) { CountryNotListedScreen( isMissingID = CountryNotListedDestination.isMissingId(it), navController = navController, identityViewModel = identityViewModel, verificationFlowFinishable = verificationFlowFinishable ) } screen(OTPDestination.ROUTE) { OTPScreen(navController = navController, identityViewModel = identityViewModel) } screen(CameraPermissionDeniedDestination.ROUTE) { val requireLiveCapture = identityViewModel.verificationPage.value?.data?.documentCapture?.requireLiveCapture ?: false ErrorScreen( identityViewModel = identityViewModel, title = stringResource(id = R.string.stripe_camera_permission), message1 = stringResource(id = R.string.stripe_grant_camera_permission_text), message2 = if (!requireLiveCapture) { stringResource( R.string.stripe_upload_file_generic_text ) } else { null }, topButton = if (!requireLiveCapture) { ErrorScreenButton( buttonText = stringResource(id = R.string.stripe_file_upload) ) { identityViewModel.screenTracker.screenTransitionStart( IdentityAnalyticsRequestFactory.SCREEN_NAME_ERROR ) navController.navigateTo( DocumentUploadDestination ) } } else { null }, bottomButton = ErrorScreenButton( buttonText = stringResource(id = R.string.stripe_app_settings) ) { appSettingsOpenable.openAppSettings() // navigate back to DocWarmup, so that when user is back to the app // from settings // the camera permission check can be triggered again from there. navController.navigateTo(DocWarmupDestination) } ) } screen(CouldNotCaptureDestination.ROUTE) { val fromSelfie = CouldNotCaptureDestination.fromSelfie(it) ErrorScreen( identityViewModel = identityViewModel, title = stringResource(id = R.string.stripe_could_not_capture_title), message1 = stringResource(id = R.string.stripe_could_not_capture_body1), message2 = if (fromSelfie) { null } else { stringResource( R.string.stripe_could_not_capture_body2 ) }, topButton = if (fromSelfie) { null } else { ErrorScreenButton( buttonText = stringResource(id = R.string.stripe_upload_a_photo), ) { identityViewModel.screenTracker.screenTransitionStart( IdentityAnalyticsRequestFactory.SCREEN_NAME_ERROR ) navController.navigateTo( DocumentUploadDestination ) } }, bottomButton = ErrorScreenButton( buttonText = stringResource(id = R.string.stripe_try_again) ) { identityViewModel.screenTracker.screenTransitionStart( IdentityAnalyticsRequestFactory.SCREEN_NAME_ERROR ) navController.navigateTo( if (fromSelfie) { SelfieDestination } else { DocumentScanDestination } ) } ) } screen(ErrorDestination.ROUTE) { Log.d( ErrorDestination.TAG, "About to show error screen with error caused by ${identityViewModel.errorCause.value?.cause}" ) ErrorScreen( identityViewModel = identityViewModel, title = ErrorDestination.errorTitle(it), message1 = ErrorDestination.errorContent(it), topButton = ErrorDestination.continueButtonContext(it) ?.let { (topButtonText, topButtonRequirement) -> ErrorScreenButton(buttonText = topButtonText) { coroutineScope.launch { identityViewModel.postVerificationPageDataForForceConfirm( requirementToForceConfirm = topButtonRequirement, navController = navController ) } } }, bottomButton = ErrorScreenButton( buttonText = ErrorDestination.backButtonText(it) ) { identityViewModel.screenTracker.screenTransitionStart( IdentityAnalyticsRequestFactory.SCREEN_NAME_ERROR ) if (ErrorDestination.shouldFail(it)) { verificationFlowFinishable.finishWithResult( IdentityVerificationSheet.VerificationFlowResult.Failed( requireNotNull(identityViewModel.errorCause.value) { "cause of error is null" } ) ) } else { val destination = ErrorDestination.backButtonDestination(it) if (destination == ErrorDestination.UNEXPECTED_ROUTE) { navController.navigateTo(ConsentDestination) } else { var shouldContinueNavigateUp = true while ( shouldContinueNavigateUp && navController.currentDestination?.route?.toRouteBase() != destination ) { shouldContinueNavigateUp = navController.clearDataAndNavigateUp(identityViewModel) } } } } ) } } } } @ExperimentalMaterialApi /** * Built a composable screen with ModalBottomSheetLayout */ private fun NavGraphBuilder.screen( route: IdentityTopLevelDestination.DestinationRoute, content: @Composable (NavBackStackEntry) -> Unit ) { composable( route = route.route, arguments = route.arguments ) { navBackStackEntry -> val bottomSheetViewModel = viewModel<BottomSheetViewModel>() val bottomSheetState by bottomSheetViewModel.bottomSheetState.collectAsState() val modalSheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Hidden ) // Required when bottomsheet is dismissed by swiping down or clicking outside, need to // update the state inside viewmodel LaunchedEffect(modalSheetState.isVisible) { if (modalSheetState.isVisible.not()) { bottomSheetViewModel.dismissBottomSheet() } } LaunchedEffect(bottomSheetState.shouldShow) { if (bottomSheetState.shouldShow) { modalSheetState.show() } else { modalSheetState.hide() } } ModalBottomSheetLayout( sheetContent = { BottomSheet() }, sheetState = modalSheetState, sheetGesturesEnabled = true, sheetShape = RoundedCornerShape( topStart = MaterialTheme.stripeShapes.cornerRadius.dp, topEnd = MaterialTheme.stripeShapes.cornerRadius.dp, ) ) { content(navBackStackEntry) } } }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
16,832
stripe-android
MIT License
compose-multiplatform-navigation/src/androidxCommonMain/kotlin/com/huanshankeji/androidx/navigation/compose/NavHostController.androidxCommon.kt
huanshankeji
570,509,992
false
{"Kotlin": 330635}
package com.huanshankeji.androidx.navigation.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.navigation.* import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController @Composable actual fun NavController.currentBackStackEntryAsState(): State<NavBackStackEntry?> = currentBackStackEntryAsState() @Composable actual fun rememberNavController(vararg navigators: Navigator<out NavDestination>): NavHostController = rememberNavController(*navigators)
20
Kotlin
0
16
44e6bb560653463549d3a09e011b15f8f4b88743
574
compose-multiplatform-material
Apache License 2.0
src/main/kotlin/de/thbingen/epro/osbimpl/model/catalog/Schemas.kt
Bonebreaker9
239,772,148
false
null
package de.thbingen.epro.osbimpl.model.catalog import com.fasterxml.jackson.annotation.JsonProperty data class Schemas( @JsonProperty("service_instance") val serviceInstance: ServiceInstanceSchema?, @JsonProperty("service_binding") val serviceBinding: ServiceBindingSchema? )
1
Kotlin
0
0
50df50bad48b6635f7324d7007da7cc8cdc1fe86
293
EPRO
Apache License 2.0
charty/src/main/java/com/himanshoe/charty/bar/model/GroupedBarData.kt
hi-manshu
523,070,772
false
null
package com.niyaj.popos.features.components.chart.bar.model import androidx.compose.ui.graphics.Color data class GroupedBarData(val barData: List<BarData>, val colors: List<Color> = List(barData.count()) { Color.Transparent }) internal fun List<GroupedBarData>.totalItems(): Int = this.sumOf { it.barData.count() } internal fun List<GroupedBarData>.maxYValue() = maxOf { it.barData.maxYValue() }
4
null
36
645
050fa400cb41716195fe01f16f3b5325e674972b
408
Charty
Apache License 2.0
bottom-sheet-alert-dialog/src/main/kotlin/com/sixtyninefourtwenty/bottomsheetalertdialog/BaseDialogBuilder.kt
unbiaseduser
687,410,356
false
null
package com.sixtyninefourtwenty.bottomsheetalertdialog import android.content.Context import android.content.res.Configuration import android.view.View import androidx.annotation.StringRes import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import java.util.function.Consumer abstract class BaseDialogBuilder<T : BaseDialogBuilder<T>>( view: View, context: Context, isFullscreen: Boolean = false ) { private val shouldBeFullScreen: Boolean protected val ui: BottomSheetAlertDialogCommonUi protected val actions: BottomSheetAlertDialogActions protected abstract val dialog: BottomSheetDialog protected abstract fun self(): T fun setTitle(@StringRes titleRes: Int) = self().apply { ui.setTitle(titleRes) } fun setTitle(titleText: CharSequence) = self().apply { ui.setTitle(titleText) } private fun applyBtnProps(whichButton: DialogButton, props: DialogButtonProperties) { ui.setButtonAppearance(whichButton, props) ui.setButtonOnClickListener(whichButton) { props.listenerWithDialog?.accept(dialog) props.listener?.run() if (props.dismissAfterClick) { dialog.dismiss() } } } fun setPositiveButton(properties: DialogButtonProperties) = self().apply { applyBtnProps(DialogButton.POSITIVE, properties) } fun setNeutralButton(properties: DialogButtonProperties) = self().apply { applyBtnProps(DialogButton.NEUTRAL, properties) } fun setNegativeButton(properties: DialogButtonProperties) = self().apply { applyBtnProps(DialogButton.NEGATIVE, properties) } fun doActions(block: Consumer<in BottomSheetAlertDialogActions>) = self().apply { block.accept(actions) } /** * Must be called by subclasses in their `init` block. */ protected fun initDialogBehavior() { with(dialog.behavior) { state = BottomSheetBehavior.STATE_EXPANDED if (shouldBeFullScreen) { isDraggable = false } } } init { val isLandscape = context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE shouldBeFullScreen = isFullscreen || isLandscape ui = BottomSheetAlertDialogCommonUi.create(context, shouldBeFullScreen).apply { setContentView(view) } actions = BottomSheetAlertDialogActions(ui) } }
0
Kotlin
0
0
fe2f5cb484b1db60380faa8e0e3df3c5a951e92d
2,472
misc-stuff
MIT License
main/src/main/java/com/quxianggif/util/glide/GifFunModule.kt
guolindev
167,902,491
false
null
/* * Copyright (C) guolin, <NAME> Inc. Open source codes for study only. * Do not use for commercial purpose. * * 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.quxianggif.util.glide import android.content.Context import com.bumptech.glide.Glide import com.bumptech.glide.GlideBuilder import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.module.GlideModule import java.io.InputStream import okhttp3.OkHttpClient import java.util.concurrent.TimeUnit /** * 自定义Glide模块,用于修改Glide默认的配置。 * * @author guolin * @since 2017/10/23 */ class GifFunModule : GlideModule { override fun applyOptions(context: Context, builder: GlideBuilder) {} override fun registerComponents(context: Context, glide: Glide) { val builder = OkHttpClient.Builder() builder.addInterceptor(ProgressInterceptor()) builder.connectTimeout(3000, TimeUnit.MILLISECONDS) builder.readTimeout(6000, TimeUnit.MILLISECONDS) glide.register(GlideUrl::class.java, InputStream::class.java, OkHttpGlideUrlLoader.Factory(builder.build())) } }
30
null
692
3,448
26227595483a8f2508f23d947b3fe99721346e0f
1,602
giffun
Apache License 2.0
src/main/kotlin/leetcode/facebook/Problem560.kt
Magdi
390,731,717
false
null
package leetcode.facebook import java.util.* import kotlin.collections.HashMap class Problem560 { fun subarraySum(nums: IntArray, k: Int): Int { var sum = 0 val sumCnt = HashMap<Int, Int>() sumCnt[0] = 1 var ans = 0 nums.forEach { sum += it ans += sumCnt.getOrDefault(sum - k, 0) val cnt = sumCnt.getOrDefault(sum, 0) sumCnt[sum] = cnt + 1 } return ans } }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
471
ProblemSolving
Apache License 2.0
src/jvmTest/kotlin/mu/ClassWithLoggingForLocationTesting.kt
MicroUtils
62,350,009
false
null
package mu class ClassWithLoggingForLocationTesting { companion object : KLogging() fun log() { logger.info("test") } fun logLazy() { logger.info { "test" } } fun logNull() { logger.info(null) } fun logEntry(): Pair<Int, Int> { logger.entry(1, 2) logger.info("log entry body") return logger.exit(2 to 1) } fun logExitOpt(): Pair<Int, Int>? { logger.entry(1, 2) logger.info("log entry body") return logger.exit(null) } }
18
null
87
1,806
4188b9c27091eae82d7917e4fe2de69af31f5932
542
kotlin-logging
Apache License 2.0
src/test/kotlin/dev/akif/cats/CatServiceTest.kt
makiftutuncu
605,721,123
false
null
package dev.akif.cats import dev.akif.crud.CRUDServiceTest import org.junit.jupiter.api.DisplayName import java.util.UUID @DisplayName("CatService") class CatServiceTest : CRUDServiceTest<UUID, CatEntity, Cat, CreateCat, UpdateCat, CatMapper, CatRepository, CatService, CatTestData>( typeName = "Cat", mapper = CatMapper(), testData = CatTestData() ) { override fun buildService(mapper: CatMapper, testData: CatTestData): CatService = CatService(testData.instantProvider, testData.repository, mapper) }
2
Kotlin
0
2
a391ac45d5ad8c96c42a7e04f33505613abbb6c5
529
kotlin-spring-boot-template
MIT License
app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryPresenter.kt
bujakpvp
167,613,504
true
{"Kotlin": 413721, "IDL": 131}
package io.github.wulkanowy.ui.modules.grade.summary import io.github.wulkanowy.data.db.entities.GradeSummary import io.github.wulkanowy.data.repositories.GradeRepository import io.github.wulkanowy.data.repositories.GradeSummaryRepository import io.github.wulkanowy.data.repositories.PreferencesRepository import io.github.wulkanowy.data.repositories.SemesterRepository import io.github.wulkanowy.data.repositories.StudentRepository import io.github.wulkanowy.ui.base.session.BaseSessionPresenter import io.github.wulkanowy.ui.base.session.SessionErrorHandler import io.github.wulkanowy.utils.FirebaseAnalyticsHelper import io.github.wulkanowy.utils.SchedulersProvider import io.github.wulkanowy.utils.calcAverage import io.github.wulkanowy.utils.changeModifier import timber.log.Timber import java.lang.String.format import java.util.Locale.FRANCE import javax.inject.Inject class GradeSummaryPresenter @Inject constructor( private val errorHandler: SessionErrorHandler, private val gradeSummaryRepository: GradeSummaryRepository, private val gradeRepository: GradeRepository, private val studentRepository: StudentRepository, private val semesterRepository: SemesterRepository, private val preferencesRepository: PreferencesRepository, private val schedulers: SchedulersProvider, private val analytics: FirebaseAnalyticsHelper ) : BaseSessionPresenter<GradeSummaryView>(errorHandler) { override fun onAttachView(view: GradeSummaryView) { super.onAttachView(view) view.initView() } fun onParentViewLoadData(semesterId: Int, forceRefresh: Boolean) { Timber.i("Loading grade summary data started") disposable.add(studentRepository.getCurrentStudent() .flatMap { semesterRepository.getSemesters(it) } .map { semester -> semester.first { it.semesterId == semesterId } } .flatMap { gradeSummaryRepository.getGradesSummary(it, forceRefresh) .flatMap { gradesSummary -> gradeRepository.getGrades(it, forceRefresh) .map { grades -> grades.map { item -> item.changeModifier(preferencesRepository.gradePlusModifier, preferencesRepository.gradeMinusModifier) } .groupBy { grade -> grade.subject } .mapValues { entry -> entry.value.calcAverage() } .filterValues { value -> value != 0.0 } .let { averages -> createGradeSummaryItems(gradesSummary, averages) to GradeSummaryScrollableHeader( formatAverage(gradesSummary.calcAverage()), formatAverage(averages.values.average()) ) } } } } .subscribeOn(schedulers.backgroundThread) .observeOn(schedulers.mainThread) .doFinally { view?.run { showRefresh(false) showProgress(false) notifyParentDataLoaded(semesterId) } }.subscribe({ Timber.i("Loading grade summary result: Success") view?.run { showEmpty(it.first.isEmpty()) showContent(it.first.isNotEmpty()) updateData(it.first, it.second) } analytics.logEvent("load_grade_summary", mapOf("items" to it.first.size, "force_refresh" to forceRefresh)) }) { Timber.i("Loading grade summary result: An exception occurred") view?.run { showEmpty(isViewEmpty) } errorHandler.dispatch(it) }) } fun onSwipeRefresh() { Timber.i("Force refreshing the grade summary") view?.notifyParentRefresh() } fun onParentViewReselected() { view?.run { if (!isViewEmpty) resetView() } } fun onParentViewChangeSemester() { view?.run { showProgress(true) showRefresh(false) showContent(false) showEmpty(false) clearView() } disposable.clear() } private fun createGradeSummaryItems(gradesSummary: List<GradeSummary>, averages: Map<String, Double>) : List<GradeSummaryItem> { return gradesSummary.filter { !checkEmpty(it, averages) }.map { it -> GradeSummaryItem( title = it.subject, average = formatAverage(averages.getOrElse(it.subject) { 0.0 }, ""), predictedGrade = it.predictedGrade, finalGrade = it.finalGrade ) } } private fun checkEmpty(gradeSummary: GradeSummary, averages: Map<String, Double>): Boolean { return gradeSummary.run { finalGrade.isBlank() && predictedGrade.isBlank() && averages[subject] == null } } private fun formatAverage(average: Double, defaultValue: String = "-- --"): String { return if (average == 0.0) defaultValue else format(FRANCE, "%.2f", average) } }
0
Kotlin
0
0
4da812af392ffbdf55960f8bb8d0d0f46721531b
5,422
wulkanowy
Apache License 2.0
src/main/kotlin/com/github/strindberg/emacssearchandcase/actions/search/PreviousSearchAction.kt
strindberg
497,232,016
false
null
package com.github.strindberg.emacssearchandcase.actions.search import com.github.strindberg.emacssearchandcase.search.PreviousSearchHandler import com.intellij.openapi.editor.actionSystem.EditorAction class PreviousSearchAction : ISearchAction, EditorAction(PreviousSearchHandler(false))
0
Kotlin
0
0
7344cb8a80aa0ee0092fae088e9819b561dfc8f6
291
emacs-search-and-case
Apache License 2.0
src/main/kotlin/no/nav/syfo/sykmelding/SykmeldingService.kt
navikt
322,575,632
false
null
package no.nav.syfo.sykmelding import no.nav.syfo.application.database.DatabaseInterface import no.nav.syfo.dinesykmeldte.model.Sykmeldt import no.nav.syfo.dinesykmeldte.util.isActive import no.nav.syfo.sykmelding.db.getArbeidsgiverSykmeldinger import no.nav.syfo.sykmelding.model.SykmeldingArbeidsgiver class SykmeldingService(val database: DatabaseInterface) { fun getSykmeldinger(lederFnr: String): List<SykmeldingArbeidsgiver> { return database.getArbeidsgiverSykmeldinger(lederFnr) } /** Get a sykmeldt for for a given narmesteleder + lederFnr */ fun getSykmeldt(narmestelederId: String, lederFnr: String): Sykmeldt? { val arbeidsgiverSykmeldinger = database.getArbeidsgiverSykmeldinger( lederFnr = lederFnr, narmestelederId = narmestelederId ) val sykmeldingArbeidsgiverV2 = arbeidsgiverSykmeldinger.firstOrNull() return if (sykmeldingArbeidsgiverV2 != null) { Sykmeldt( narmestelederId = sykmeldingArbeidsgiverV2.narmestelederId, orgnummer = sykmeldingArbeidsgiverV2.orgnummer, fnr = sykmeldingArbeidsgiverV2.pasientFnr, navn = sykmeldingArbeidsgiverV2.navn, sykmeldinger = null, aktivSykmelding = arbeidsgiverSykmeldinger.any { it.sykmelding.sykmeldingsperioder.isActive() }, ) } else { null } } }
0
Kotlin
0
0
d8565bd31a0923fbfecc99c648ab785634366a31
1,486
sykmeldinger-arbeidsgiver
MIT License
src/main/kotlin/dev/arbjerg/ukulele/command/HelpCommand.kt
rosbo018
437,280,917
true
{"Kotlin": 45984, "Dockerfile": 282, "Batchfile": 197, "Shell": 99}
package dev.arbjerg.ukulele.command import dev.arbjerg.ukulele.features.HelpContext import dev.arbjerg.ukulele.jda.Command import dev.arbjerg.ukulele.jda.CommandContext import dev.arbjerg.ukulele.jda.CommandManager import org.springframework.stereotype.Component @Component class HelpCommand : Command("help") { override suspend fun CommandContext.invoke() { when (argumentText.trim()){ "" -> replyHelp() "list" -> reply(printAllCommands(beans.commandManager)) else -> { val command = beans.commandManager[argumentText.trim()] if (command != null) { reply("all commands:") replyHelp(command) } } } } fun printAllCommands(commandManager: CommandManager): String { val commands = commandManager.getAllCommands() val sb = StringBuilder("") for (i in commands){ sb.append(i) sb.append("\n") } return sb.toString() } override fun HelpContext.provideHelp() { addUsage("") addDescription("Displays general help. (unfinished) build v1.05") // TODO // add text to show that player is pause/paying/not in channel addUsage("<command>") addDescription("Displays help about a specific command.") } }
0
Kotlin
0
0
79382d0f4178bd8c36a928a409a4fd0d40892595
1,369
ukulele
MIT License
plugins/kotlin/idea/tests/testData/intentions/convertForEachToForLoop/forEachIndexed/list.kt
ingokegel
72,937,917
true
null
// WITH_STDLIB fun test() { listOf(1, 2, 3).forEachIndexed<caret> { index, element -> println("$index: $element") } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
133
intellij-community
Apache License 2.0
src/ast/BooleanLiteral.kt
weareskyrabbit
257,030,778
false
{"Kotlin": 26646}
package ast import ir.IRPrinter class BooleanLiteral(private val value: Boolean): Expression { override fun toS(n: Int): String { return "$value" } override fun toIR(): ir.Operand { val tmp = IRPrinter.tmp() IRPrinter.add(ir.Three(tmp, 0x20, ir.Register.ZERO, ir.Immediate(if (value) 1 else 0))) return tmp } }
0
Kotlin
0
0
76ca16d8939ac60b243ccf341ca469a7159b24ef
360
incremetal3.0
MIT License
pact-jvm-matchers/src/main/kotlin/au/com/dius/pact/matchers/MatchingConfig.kt
thombergs
140,947,341
false
{"Gradle": 23, "YAML": 4, "Markdown": 24, "INI": 4, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Groovy": 207, "Clojure": 5, "Kotlin": 71, "Scala": 75, "Java": 171, "JSON": 628, "XML": 2, "Java Properties": 1, "Dockerfile": 1}
package au.com.dius.pact.matchers object MatchingConfig { val bodyMatchers = mapOf( "application/.*xml" to "au.com.dius.pact.matchers.XmlBodyMatcher", "text/xml" to "au.com.dius.pact.matchers.XmlBodyMatcher", "application/.*json" to "au.com.dius.pact.matchers.JsonBodyMatcher", "application/json-rpc" to "au.com.dius.pact.matchers.JsonBodyMatcher", "application/jsonrequest" to "au.com.dius.pact.matchers.JsonBodyMatcher", "text/plain" to "au.com.dius.pact.matchers.PlainTextBodyMatcher", "multipart/form-data" to "au.com.dius.pact.matchers.MultipartMessageBodyMatcher", "multipart/mixed" to "au.com.dius.pact.matchers.MultipartMessageBodyMatcher", "application/x-www-form-urlencoded" to "au.com.dius.pact.matchers.FormPostBodyMatcher" ) @JvmStatic fun lookupBodyMatcher(mimeType: String): BodyMatcher? { val matcher = bodyMatchers.entries.find { mimeType.matches(Regex(it.key)) }?.value return if (matcher != null) { Class.forName(matcher)?.newInstance() as BodyMatcher? } else { null } } }
1
null
1
1
9dc0901fdbda5de1ed6aada223f82551ab1da245
1,068
pact-jvm
Apache License 2.0
datasource/implementation/src/main/java/com/mitteloupe/whoami/datasource/ipaddressinformation/datasource/IpAddressInformationDataSourceImpl.kt
EranBoudjnah
662,551,018
false
null
package com.mitteloupe.whoami.datasource.ipaddressinformation.datasource import com.mitteloupe.whoami.datasource.ipaddressinformation.exception.NoIpAddressInformationDataException import com.mitteloupe.whoami.datasource.ipaddressinformation.mapper.IpAddressInformationToDataMapper import com.mitteloupe.whoami.datasource.ipaddressinformation.model.IpAddressInformationDataModel import com.mitteloupe.whoami.datasource.ipaddressinformation.service.IpAddressInformationService import com.mitteloupe.whoami.datasource.remote.provider.retrofit.fetchBodyOrThrow class IpAddressInformationDataSourceImpl( private val lazyIpAddressInformationService: Lazy<IpAddressInformationService>, private val ipAddressInformationToDataMapper: IpAddressInformationToDataMapper ) : IpAddressInformationDataSource { private val ipAddressInformationService by lazy { lazyIpAddressInformationService.value } override fun ipAddressInformation(ipAddress: String): IpAddressInformationDataModel = ipAddressInformationToDataMapper.toData( ipAddressInformationService.ipAddressInformation(ipAddress).fetchBodyOrThrow { NoIpAddressInformationDataException() } ) }
0
Kotlin
10
73
360ab5b232427ecc4fdf20e272732eb0d3c65e39
1,222
CleanArchitectureForAndroid
MIT License
web-service/src/main/java/io/acari/event/source/flux/DownloadStreamToFluxFactory.kt
Unthrottled
152,663,510
false
{"CSS": 183129, "TypeScript": 39977, "Java": 24405, "Kotlin": 15328, "JavaScript": 9183, "HTML": 8189, "Dockerfile": 870}
package io.acari.event.source.flux import com.mongodb.reactivestreams.client.Success import com.mongodb.reactivestreams.client.gridfs.GridFSDownloadStream import org.slf4j.Logger import org.slf4j.LoggerFactory import reactor.core.publisher.Flux import reactor.core.publisher.FluxSink import reactor.core.publisher.Mono import java.nio.ByteBuffer /** * Forged in the flames of battle by alex. */ class DownloadStreamToFluxFactory { fun convert(gridFSDownloadStream: GridFSDownloadStream): Flux<ByteArray> { return Flux.create { synchronousSink -> readStream(gridFSDownloadStream, synchronousSink) } } private fun readStream(gridFSDownloadStream: GridFSDownloadStream, synchronousSink: FluxSink<ByteArray>) { val allocate = ByteBuffer.allocate(512000) Mono.from(gridFSDownloadStream.read(allocate)) .subscribe({ bytesRead -> if (finishedReading(bytesRead)) { Mono.from<Success>(gridFSDownloadStream.close()) .subscribe({}, {}, { synchronousSink.complete() }) } else { synchronousSink.next(allocate.array()) readStream(gridFSDownloadStream, synchronousSink) } }, { throwable -> LOGGER.warn("Ohhh snap!", throwable) synchronousSink.complete() }) } private fun finishedReading(read: Int?): Boolean = read ?: -1 < 0 companion object { private val LOGGER = loggerFor(DownloadStreamToFluxFactory::class.java) } } fun <T> loggerFor(clazz: Class<T>): Logger = LoggerFactory.getLogger(clazz)
1
CSS
1
1
f7741fca5eb9e17b449d5c87544600d73e436e33
1,702
event-sourcing-workshop
MIT License
ui/licenses/src/commonMain/kotlin/app/tivi/settings/licenses/LicensesUiState.kt
chrisbanes
100,624,553
false
{"Kotlin": 1003653, "Swift": 24790, "HTML": 23782, "Ruby": 4088, "Shell": 3317, "Python": 1228}
// Copyright 2019, Google LLC, <NAME> and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.settings.licenses import androidx.compose.runtime.Immutable import app.tivi.data.licenses.LicenseItem import com.slack.circuit.runtime.CircuitUiEvent import com.slack.circuit.runtime.CircuitUiState @Immutable data class LicensesUiState( val licenses: List<LicenseGroup> = emptyList(), val eventSink: (LicensesUiEvent) -> Unit, ) : CircuitUiState sealed interface LicensesUiEvent : CircuitUiEvent { data object NavigateUp : LicensesUiEvent data class NavigateRepository(val artifact: LicenseItem) : LicensesUiEvent } data class LicenseGroup( val id: String, val artifacts: List<LicenseItem>, )
23
Kotlin
876
6,626
e261ffbded01c1439b93c550cd6e714c13bb9192
750
tivi
Apache License 2.0
ui/ui-desktop/src/jvmMain/kotlin/androidx/ui/desktop/DesktopParagraph.kt
Sathawale27
282,379,594
true
{"Java Properties": 20, "Shell": 44, "Markdown": 43, "Java": 4516, "HTML": 17, "Kotlin": 3557, "Python": 28, "Proguard": 37, "Batchfile": 6, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 1, "C++": 2}
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.ui.desktop import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.DesktopPath import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.toAndroidX import androidx.compose.ui.text.Paragraph import androidx.compose.ui.text.ParagraphConstraints import androidx.compose.ui.text.ParagraphIntrinsics import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.style.ResolvedTextDirection import org.jetbrains.skija.paragraph.LineMetrics import org.jetbrains.skija.paragraph.RectHeightMode import org.jetbrains.skija.paragraph.RectWidthMode import kotlin.math.floor internal class DesktopParagraph( intrinsics: ParagraphIntrinsics, val maxLines: Int, val ellipsis: Boolean, val constraints: ParagraphConstraints ) : Paragraph { val paragraphIntrinsics = intrinsics as DesktopParagraphIntrinsics val para = paragraphIntrinsics.para init { para.layout(constraints.width) } override val width: Float get() = para.getMaxWidth() override val height: Float get() = para.getHeight() override val minIntrinsicWidth: Float get() = paragraphIntrinsics.minIntrinsicWidth override val maxIntrinsicWidth: Float get() = paragraphIntrinsics.maxIntrinsicWidth override val firstBaseline: Float get() = para.getLineMetrics().firstOrNull()?.run { baseline.toFloat() } ?: 0f override val lastBaseline: Float get() = para.getLineMetrics().lastOrNull()?.run { baseline.toFloat() } ?: 0f override val didExceedMaxLines: Boolean // TODO: support text ellipsize. get() = para.lineNumber < maxLines override val lineCount: Int get() = para.lineNumber.toInt() override val placeholderRects: List<Rect?> get() { println("Paragraph.placeholderRects") return listOf() } override fun getPathForRange(start: Int, end: Int): Path { val boxes = para.getRectsForRange( start, end, RectHeightMode.MAX, RectWidthMode.MAX ) val path = DesktopPath() for (b in boxes) { path.internalPath.addRect(b.rect) } return path } override fun getCursorRect(offset: Int): Rect { val cursorWidth = 4.0f val horizontal = getHorizontalPosition(offset, true) val line = getLineForOffset(offset) return Rect( horizontal - 0.5f * cursorWidth, getLineTop(line), horizontal + 0.5f * cursorWidth, getLineBottom(line) ) } override fun getLineLeft(lineIndex: Int): Float { println("Paragraph.getLineLeft $lineIndex") return 0.0f } override fun getLineRight(lineIndex: Int): Float { println("Paragraph.getLineRight $lineIndex") return 0.0f } override fun getLineTop(lineIndex: Int) = para.lineMetrics.getOrNull(lineIndex)?.let { line -> floor((line.baseline - line.ascent).toFloat()) } ?: 0f override fun getLineBottom(lineIndex: Int) = para.lineMetrics.getOrNull(lineIndex)?.let { line -> floor((line.baseline + line.descent).toFloat()) } ?: 0f private fun lineMetricsForOffset(offset: Int): LineMetrics? { val metrics = para.lineMetrics for (line in metrics) { if (offset <= line.endIndex) { return line } } return null } override fun getLineHeight(lineIndex: Int) = para.lineMetrics[lineIndex].height.toFloat() override fun getLineWidth(lineIndex: Int) = para.lineMetrics[lineIndex].width.toFloat() override fun getLineStart(lineIndex: Int) = para.lineMetrics[lineIndex].startIndex.toInt() override fun getLineEnd(lineIndex: Int) = para.lineMetrics[lineIndex].endIndex.toInt() override fun getLineEllipsisOffset(lineIndex: Int): Int { println("Paragraph.getLineEllipsisOffset $lineIndex") return 0 } override fun getLineEllipsisCount(lineIndex: Int): Int { println("Paragraph.getLineEllipsisCount $lineIndex") return 0 } override fun getLineForOffset(offset: Int) = lineMetricsForOffset(offset)?.run { lineNumber.toInt() } ?: 0 override fun getLineForVerticalPosition(vertical: Float): Int { println("Paragraph.getLineForVerticalPosition $vertical") return 0 } override fun getHorizontalPosition(offset: Int, usePrimaryDirection: Boolean): Float { val metrics = lineMetricsForOffset(offset) return when { metrics == null -> 0f metrics.startIndex.toInt() == offset || metrics.startIndex == metrics.endIndex -> 0f metrics.endIndex.toInt() == offset -> { para.getRectsForRange(offset - 1, offset, RectHeightMode.MAX, RectWidthMode.MAX) .first() .rect.right } else -> { para.getRectsForRange( offset, offset + 1, RectHeightMode.MAX, RectWidthMode.MAX ).first().rect.left } } } override fun getParagraphDirection(offset: Int): ResolvedTextDirection = ResolvedTextDirection.Ltr override fun getBidiRunDirection(offset: Int): ResolvedTextDirection = ResolvedTextDirection.Ltr override fun getOffsetForPosition(position: Offset): Int { return para.getGlyphPositionAtCoordinate(position.x, position.y).position } override fun getBoundingBox(offset: Int) = para.getRectsForRange( offset, offset + 1, RectHeightMode.MAX, RectWidthMode .MAX ).first().rect.toAndroidX() override fun getWordBoundary(offset: Int): TextRange { println("Paragraph.getWordBoundary $offset") return TextRange(0, 0) } override fun paint(canvas: Canvas) { para.paint(canvas.nativeCanvas.skijaCanvas, 0.0f, 0.0f) } }
1
null
0
1
549e3e3003cd308939ff31799cf1250e86d3e63e
6,768
androidx
Apache License 2.0
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/InlineQueries/InlineQueryResult/InlineQueryResultPhotoImpl.kt
Djaler
311,091,197
true
{"Kotlin": 816932, "Shell": 373}
package dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult import dev.inmo.tgbotapi.CommonAbstracts.* import dev.inmo.tgbotapi.types.* import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.abstracts.results.photo.InlineQueryResultPhoto import dev.inmo.tgbotapi.types.InlineQueries.InlineQueryResult.abstracts.results.photo.inlineQueryResultPhotoType import dev.inmo.tgbotapi.types.InlineQueries.abstracts.InputMessageContent import dev.inmo.tgbotapi.types.MessageEntity.* import dev.inmo.tgbotapi.types.ParseMode.ParseMode import dev.inmo.tgbotapi.types.ParseMode.parseModeField import dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable fun InlineQueryResultPhotoImpl( id: InlineQueryIdentifier, url: String, thumbUrl: String, width: Int? = null, height: Int? = null, title: String? = null, description: String? = null, text: String? = null, parseMode: ParseMode? = null, replyMarkup: InlineKeyboardMarkup? = null, inputMessageContent: InputMessageContent? = null ) = InlineQueryResultPhotoImpl(id, url, thumbUrl, width, height, title, description, text, parseMode, null, replyMarkup, inputMessageContent) fun InlineQueryResultPhotoImpl( id: InlineQueryIdentifier, url: String, thumbUrl: String, width: Int? = null, height: Int? = null, title: String? = null, description: String? = null, entities: List<TextSource>, replyMarkup: InlineKeyboardMarkup? = null, inputMessageContent: InputMessageContent? = null ) = InlineQueryResultPhotoImpl(id, url, thumbUrl, width, height, title, description, entities.makeString(), null, entities.toRawMessageEntities(), replyMarkup, inputMessageContent) @Serializable data class InlineQueryResultPhotoImpl internal constructor( @SerialName(idField) override val id: InlineQueryIdentifier, @SerialName(photoUrlField) override val url: String, @SerialName(thumbUrlField) override val thumbUrl: String, @SerialName(photoWidthField) override val width: Int? = null, @SerialName(photoHeightField) override val height: Int? = null, @SerialName(titleField) override val title: String? = null, @SerialName(descriptionField) override val description: String? = null, @SerialName(captionField) override val text: String? = null, @SerialName(parseModeField) override val parseMode: ParseMode? = null, @SerialName(captionEntitiesField) private val rawEntities: List<RawMessageEntity>? = null, @SerialName(replyMarkupField) override val replyMarkup: InlineKeyboardMarkup? = null, @SerialName(inputMessageContentField) override val inputMessageContent: InputMessageContent? = null ) : InlineQueryResultPhoto { override val type: String = inlineQueryResultPhotoType override val entities: List<TextSource>? by lazy { rawEntities ?.asTextParts(text ?: return@lazy null) ?.justTextSources() } }
0
null
0
0
83edda2dfe370fbc35f2e73283cd71e79f101e3c
3,016
TelegramBotAPI
Apache License 2.0
KotlinExample/src/main/kotlin/programmers/basic/Day19/잘라서배열로저장하기/Solution.kt
sangki930
467,437,850
false
{"Kotlin": 69458}
package programmers.basic.Day19.잘라서배열로저장하기 class Solution { fun solution(my_str: String, n: Int): Array<String> { var cnt = (Math.ceil(1.0*my_str.length/n)).toInt() var answer=Array(cnt,{""}) for(i in 0 until cnt) answer[i] = my_str.substring(i*n until Math.min(i*n+n,my_str.length)) return answer } }
0
Kotlin
0
0
a448bbf4b1ea7e9d972b8e3fce7723ce06fc6410
354
Kotlin
Apache License 2.0
KotlinExample/src/main/kotlin/programmers/basic/Day19/잘라서배열로저장하기/Solution.kt
sangki930
467,437,850
false
{"Kotlin": 69458}
package programmers.basic.Day19.잘라서배열로저장하기 class Solution { fun solution(my_str: String, n: Int): Array<String> { var cnt = (Math.ceil(1.0*my_str.length/n)).toInt() var answer=Array(cnt,{""}) for(i in 0 until cnt) answer[i] = my_str.substring(i*n until Math.min(i*n+n,my_str.length)) return answer } }
0
Kotlin
0
0
a448bbf4b1ea7e9d972b8e3fce7723ce06fc6410
354
Kotlin
Apache License 2.0
app/src/main/java/com/vaibhavmojidra/androidkotlindemohilt/Game.kt
VaibhavMojidra
659,176,213
false
null
package com.vaibhavmojidra.androidkotlindemo2dagger2singleton import android.util.Log import javax.inject.Inject class Game @Inject constructor(){ init { Log.i("MyTag","Game class initialized.") } fun isGameDownloaded(){ Log.i("MyTag","Game is already downloaded.") } }
0
Kotlin
0
0
a4f1ee14b40dca359c1a6aa440dc1478aa845d41
305
Android-Kotlin---Demo-Hilt
MIT License
app/src/main/java/com/language/moviecompose/presentation/screen/favorite/views/FavoriteScreen.kt
ahmetufan
650,070,075
false
null
package com.language.moviecompose.presentation.screen.favorite.views import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.language.moviecompose.presentation.navigation.BottomNavigationBar import com.language.moviecompose.presentation.navigation.Destination import com.language.moviecompose.presentation.screen.favorite.FavoriteViewModel import com.language.moviecompose.presentation.screen.moviscreen.movies.MoviesEvent @Composable fun FavoriteScreen(navController: NavController, viewModel: FavoriteViewModel = hiltViewModel()) { // Composable yüklendiğinde filmleri çekme işlemi LaunchedEffect kullanarak yapıyoruz. LaunchedEffect, coroutine scope sağlar ve composable'in lifecycle'ına bağlıdır LaunchedEffect(key1 = true) { viewModel.getAllFavoriteMovie() } // Burada favoriMovies LiveData'nın son değerini observe ediyoruz ve her değişiklikte UI'ı güncelliyoruz. val favoriteMovies by viewModel.favoriteMovies.observeAsState(initial = listOf()) val isRefreshing by viewModel.isRefreshing.observeAsState(initial = false) Scaffold( bottomBar = { BottomNavigationBar(navController = navController) } ){ paddingValues -> Box( modifier = Modifier .padding(paddingValues) .fillMaxSize() .background(Color.Black) ) { Column() { Text( text = "Favorite Movie", textAlign = TextAlign.Center, modifier = Modifier.padding(14.dp), color = Color.White, fontSize = 25.sp, fontWeight = FontWeight.Bold ) SwipeRefresh( state = rememberSwipeRefreshState(isRefreshing = isRefreshing), onRefresh = viewModel::getAllFavoriteMovie ) { LazyColumn { items(favoriteMovies) { movie -> FavoriteListRow(movie = movie, onItemClick = { //Detail ekranına imdbId yollama navController.navigate(Destination.MovieDetailScreen.route + "/${movie.imdbID}") }) } } } } } } }
0
Kotlin
0
1
9171e985df47aa4076067a06a6f503d2a89f9571
3,161
JetpackComposeMovie
MIT License
app/src/main/java/com/egoriku/radiotok/presentation/ui/radio/miniplayer/RadioMiniPlayer.kt
egorikftp
345,375,226
false
null
package com.egoriku.radiotok.presentation.ui.radio.miniplayer import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.egoriku.radiotok.common.model.RadioItemModel import com.egoriku.radiotok.extension.noRippleClickable import com.egoriku.radiotok.presentation.ControlsActions import com.egoriku.radiotok.presentation.state.RadioPlaybackState import com.egoriku.radiotok.presentation.ui.radio.actions.LikeAction import com.egoriku.radiotok.presentation.ui.radio.miniplayer.component.RadioLogoSmall import com.google.accompanist.placeholder.material.placeholder @Composable fun RadioMiniPlayer( modifier: Modifier = Modifier, radioItem: RadioItemModel, playbackState: RadioPlaybackState, controlsActions: ControlsActions, fraction: Float, clickable: Boolean, onClick: () -> Unit ) { Row( modifier = modifier .fillMaxWidth() .height(72.dp) .graphicsLayer { alpha = 1f - fraction } .noRippleClickable(onClick = onClick, enabled = clickable), verticalAlignment = Alignment.CenterVertically ) { RadioLogoSmall( modifier = Modifier.padding(start = 16.dp), placeholder = Modifier.placeholder( visible = radioItem.id.isEmpty() ), url = radioItem.icon ) Text( modifier = Modifier .weight(1f) .padding(start = 16.dp) .placeholder(visible = radioItem.id.isEmpty()), maxLines = 1, overflow = TextOverflow.Ellipsis, text = radioItem.name, color = MaterialTheme.colors.onPrimary, style = MaterialTheme.typography.caption ) LikeAction( modifier = Modifier.padding(end = 16.dp), tint = MaterialTheme.colors.onPrimary, onClick = controlsActions.toggleFavoriteEvent, isLiked = playbackState.isLiked ) } }
1
Kotlin
3
19
aa650480efb655a31f1b325fc3475d83f28fad99
2,492
RadioTok
Apache License 2.0
sunflowerlibrary/src/main/java/com/thanhtv/sunflowerlibrary/extensions/core/Bundle.kt
vanthanhtran245
143,992,863
false
null
package com.thanhtv.sunflowerlibrary.extensions.core import android.os.Bundle inline fun Bundle(body: Bundle.() -> Unit): Bundle { val bundle = Bundle() bundle.body() return bundle } inline fun Bundle(loader: ClassLoader, body: Bundle.() -> Unit): Bundle { val bundle = Bundle(loader) bundle.body() return bundle } inline fun Bundle(capacity: Int, body: Bundle.() -> Unit): Bundle { val bundle = Bundle(capacity) bundle.body() return bundle } inline fun Bundle(b: Bundle?, body: Bundle.() -> Unit): Bundle { val bundle = Bundle(b) bundle.body() return bundle }
1
null
1
1
3b8e5e9398ba0d333551491f574c531b3cb39dc1
615
sunflowerlibrary
MIT License
app/src/main/java/com/kieronquinn/app/classicpowermenu/ui/screens/settings/faq/SettingsFaqFragment.kt
KieronQuinn
410,362,831
false
null
package com.kieronquinn.app.classicpowermenu.ui.screens.settings.faq import android.os.Bundle import android.text.style.ForegroundColorSpan import android.view.View import androidx.core.content.res.ResourcesCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import com.kieronquinn.app.classicpowermenu.R import com.kieronquinn.app.classicpowermenu.databinding.FragmentSettingsFaqBinding import com.kieronquinn.app.classicpowermenu.ui.base.AutoExpandOnRotate import com.kieronquinn.app.classicpowermenu.ui.base.BackAvailable import com.kieronquinn.app.classicpowermenu.ui.base.BoundFragment import com.kieronquinn.app.classicpowermenu.utils.extensions.getColorResCompat import com.kieronquinn.monetcompat.extensions.views.enableStretchOverscroll import io.noties.markwon.AbstractMarkwonPlugin import io.noties.markwon.Markwon import io.noties.markwon.MarkwonSpansFactory import io.noties.markwon.core.MarkwonTheme import org.commonmark.node.Heading class SettingsFaqFragment: BoundFragment<FragmentSettingsFaqBinding>(FragmentSettingsFaqBinding::inflate), AutoExpandOnRotate, BackAvailable { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.root.isNestedScrollingEnabled = false val typeface = ResourcesCompat.getFont(requireContext(), R.font.google_sans_text_medium) val markwon = Markwon.builder(requireContext()).usePlugin(object: AbstractMarkwonPlugin() { override fun configureTheme(builder: MarkwonTheme.Builder) { typeface?.let { builder.headingTypeface(it) builder.headingBreakHeight(0) } } override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) { val origin = builder.requireFactory(Heading::class.java) builder.setFactory(Heading::class.java) { configuration, props -> arrayOf(origin.getSpans(configuration, props), ForegroundColorSpan(requireContext().getColorResCompat(android.R.attr.textColorPrimary))) } } }).build() val markdown = requireContext().assets.open(getString(R.string.settings_about_faq_file)).bufferedReader().use { it.readText() } binding.markdown.text = markwon.toMarkdown(markdown) ViewCompat.setOnApplyWindowInsetsListener(binding.markdown){ view, insets -> val bottomInset = insets.getInsets(WindowInsetsCompat.Type.navigationBars() or WindowInsetsCompat.Type.ime()).bottom view.updatePadding(bottom = bottomInset) insets } binding.root.enableStretchOverscroll() } }
8
null
7
693
e17f14a85f85d4eefabaf847abfadd1af32291c1
2,785
ClassicPowerMenu
Apache License 2.0
app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/testbutton/TestButtonActivity.kt
rodrigomartind
265,013,640
false
null
package com.rodrigodominguez.mixanimationsmotionlayout.testbutton import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.rodrigodominguez.mixanimationsmotionlayout.R class TestButtonActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_key_position_delta) } }
1
Kotlin
63
610
17e3d8ad36a3b9806c828bd03cc71eb37af789dc
414
MixAnimationsMotionLayout
Apache License 2.0
examples/src/main/kotlin/errorPlots/RandomDataErrorsX.kt
SciProgCentre
186,020,000
false
null
package errorPlots import space.kscience.dataforge.meta.invoke import space.kscience.plotly.Plotly import space.kscience.plotly.makeFile import space.kscience.plotly.palettes.Xkcd import space.kscience.plotly.trace import java.util.* /** * - simple scatter with random length of horizontal error bars * - change error bars color * - use XKCD as color palette */ fun main() { val rnd = Random() val xValues = (0..100 step 4).toList().map { it / 20.0 } val err = List(26) { rnd.nextDouble() / 2 } val plot = Plotly.plot { trace { x.numbers = xValues marker { color(Xkcd.PURPLE) } error_x { array = err color(Xkcd.PALE_PURPLE) } } layout { title = "Random Data Error" } } plot.makeFile() }
10
null
21
142
a7d2611513c5f50c2f4a9c99b9ccb33cb486f07d
871
plotly.kt
Apache License 2.0
game/src/main/kotlin/gg/rsmod/game/model/collision/CollisionUpdate.kt
2011Scape
578,880,245
false
null
package gg.rsmod.game.model.collision import gg.rsmod.game.fs.DefinitionSet import gg.rsmod.game.fs.def.ObjectDef import gg.rsmod.game.model.Direction import gg.rsmod.game.model.Tile import gg.rsmod.game.model.entity.GameObject import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectArrayList import it.unimi.dsi.fastutil.objects.ObjectList class CollisionUpdate private constructor(val type: Type, val flags: Object2ObjectOpenHashMap<Tile, ObjectList<DirectionFlag>>) { enum class Type { ADD, REMOVE } class Builder { private val flags = Object2ObjectOpenHashMap<Tile, ObjectList<DirectionFlag>>() private var type: Type? = null fun build(): CollisionUpdate { check(type != null) { "Type has not been set." } return CollisionUpdate(type!!, flags) } fun setType(type: Type) { check(this.type == null) { "Type has already been set." } this.type = type } fun putTile(tile: Tile, impenetrable: Boolean, vararg directions: Direction) { check(directions.isNotEmpty()) { "Directions must not be empty." } val flags = flags[tile] ?: ObjectArrayList<DirectionFlag>() directions.forEach { dir -> flags.add(DirectionFlag(dir, impenetrable)) } this.flags[tile] = flags } private fun putWall(tile: Tile, impenetrable: Boolean, orientation: Direction) { putTile(tile, impenetrable, orientation) putTile(tile.step(orientation), impenetrable, orientation.getOpposite()) } private fun putLargeCornerWall(tile: Tile, impenetrable: Boolean, orientation: Direction) { val directions = orientation.getDiagonalComponents() putTile(tile, impenetrable, *directions) directions.forEach { dir -> putTile(tile.step(dir), impenetrable, dir.getOpposite()) } } fun putObject(definitions: DefinitionSet, obj: GameObject) { val def = definitions.get(ObjectDef::class.java, obj.id) val type = obj.type val tile = obj.tile if (!unwalkable(def, type)) { return } val x = tile.x val z = tile.z val height = tile.height var width = def.width var length = def.length val impenetrable = def.impenetrable val orientation = obj.rot if (orientation == 1 || orientation == 3) { width = def.length length = def.width } if (type == ObjectType.FLOOR_DECORATION.value) { if (def.interactive && def.solid) { putTile(Tile(x, z, height), impenetrable, *Direction.NESW) } } else if (type >= ObjectType.DIAGONAL_WALL.value && type < ObjectType.FLOOR_DECORATION.value) { for (dx in 0 until width) { for (dz in 0 until length) { putTile(Tile(x + dx, z + dz, height), impenetrable, *Direction.NESW) } } } else if (type == ObjectType.LENGTHWISE_WALL.value) { putWall(tile, impenetrable, Direction.WNES[orientation]) } else if (type == ObjectType.TRIANGULAR_CORNER.value || type == ObjectType.RECTANGULAR_CORNER.value) { putWall(tile, impenetrable, Direction.WNES_DIAGONAL[orientation]) } else if (type == ObjectType.WALL_CORNER.value) { putLargeCornerWall(tile, impenetrable, Direction.WNES_DIAGONAL[orientation]) } } private fun unwalkable(def: ObjectDef, type: Int): Boolean { val isSolidFloorDecoration = type == ObjectType.FLOOR_DECORATION.value && def.interactive val isRoof = type > ObjectType.DIAGONAL_INTERACTABLE.value && type < ObjectType.FLOOR_DECORATION.value && def.solid val isWall = (type >= ObjectType.LENGTHWISE_WALL.value && type <= ObjectType.RECTANGULAR_CORNER.value || type == ObjectType.DIAGONAL_WALL.value) && def.solid val isSolidInteractable = (type == ObjectType.DIAGONAL_INTERACTABLE.value || type == ObjectType.INTERACTABLE.value) && def.solid return isWall || isRoof || isSolidInteractable || isSolidFloorDecoration } } }
8
null
33
34
e5400cc71bfa087164153d468979c5a3abc24841
4,452
game
Apache License 2.0
lib/testSrc/util.kt
develar
294,778,365
false
{"Java": 849117, "Kotlin": 24519}
package org.jetbrains.integratedBinaryPacking import org.assertj.core.presentation.Representation import org.assertj.core.presentation.StandardRepresentation import java.lang.StringBuilder import kotlin.random.Random val random = Random(42) const val arraySeparator = "\n " val arrayPresentation = object : Representation { override fun toStringOf(o: Any?): String { return when (o) { is IntArray -> arrayToString(o) is LongArray -> arrayToString(o) else -> StandardRepresentation.STANDARD_REPRESENTATION.toStringOf(o) } } override fun unambiguousToStringOf(o: Any?) = toStringOf(o) } private fun arrayToString(array: IntArray): String { val builder = StringBuilder() builder.append("[\n ") array.joinTo(builder, separator = ", $arraySeparator") builder.append("\n]") return builder.toString() } private fun arrayToString(array: LongArray): String { val builder = StringBuilder() builder.append("[\n ") array.joinTo(builder, separator = ", $arraySeparator") builder.append("\n]") return builder.toString() }
1
null
1
1
10909112361f331d3fbc92e9906afb05fa51c0cb
1,068
integrated-binary-packing
Apache License 2.0
sculptor-shared/src/main/kotlin/io/papermc/sculptor/shared/util/patches/Patcher.kt
PaperMC
776,033,668
false
{"Kotlin": 99146}
package io.papermc.sculptor.shared.util.patches import java.nio.file.Path interface Patcher { fun applyPatches(baseDir: Path, patchDir: Path, outputDir: Path, failedDir: Path): PatchResult } sealed interface PatchResult { val patches: List<Path> val failures: List<PatchFailureDetails> get() = emptyList() fun fold(next: PatchResult): PatchResult { return when { this is PatchSuccess && next is PatchSuccess -> PatchSuccess(this.patches + next.patches) else -> PatchFailure(this.patches + next.patches, this.failures + next.failures) } } } internal sealed interface PatchSuccess : PatchResult { companion object : PatchSuccess { operator fun invoke(patches: List<Path> = emptyList()): PatchSuccess = PatchSuccessFile(patches) operator fun invoke(patch: Path): PatchSuccess = PatchSuccessFile(listOf(patch)) override val patches: List<Path> get() = emptyList() } } private data class PatchSuccessFile(override val patches: List<Path>) : PatchSuccess data class PatchFailure(override val patches: List<Path>, override val failures: List<PatchFailureDetails>) : PatchResult { constructor(patch: Path, details: String) : this(listOf(patch), listOf(PatchFailureDetails(patch, details))) } data class PatchFailureDetails(val patch: Path, val details: String)
0
Kotlin
0
0
61852f191965a86915fb3e746620538d3e233dd4
1,384
sculptor
MIT License
sources/storage/src/main/java/com/mikyegresl/valostat/storage/StorageFactory.kt
sergey-lvovich-kim
629,918,357
false
null
package com.mikyegresl.valostat.storage import android.content.Context import androidx.datastore.preferences.preferencesDataStore import com.google.gson.Gson import com.mikyegresl.valostat.base.manager.FileManager import com.mikyegresl.valostat.base.storage.AppConfigStorage import com.mikyegresl.valostat.base.storage.ValorantStorage import com.mikyegresl.valostat.base.storage.service.AgentsLocalDataSource import com.mikyegresl.valostat.base.storage.service.WeaponsLocalDataSource import com.mikyegresl.valostat.storage.service.AgentsLocalDataSourceImpl import com.mikyegresl.valostat.storage.service.WeaponsLocalDataSourceImpl private const val MAIN_DATASTORE_FILENAME = "VALOSTAT_PREF" private val Context.mainDataStore by preferencesDataStore( name = MAIN_DATASTORE_FILENAME ) class StorageFactory( private val context: Context, private val gson: Gson, private val fileManager: FileManager ) { private val storage: ValorantStorage by lazy { ValorantStorageImpl( context.cacheDir.absolutePath, fileManager, gson ) } val appConfigStorage: AppConfigStorage by lazy { AppConfigStorageImpl(context.mainDataStore, gson) } val agentsLocalDataSource: AgentsLocalDataSource by lazy { AgentsLocalDataSourceImpl(storage) } val weaponsLocalDataSource: WeaponsLocalDataSource by lazy { WeaponsLocalDataSourceImpl(storage) } }
0
null
1
8
43d703892b9b21824508ab11762f3ad6b04b511b
1,426
ValoStat
Apache License 2.0
app/src/main/kotlin/com/krishnaZyala/faceRecognition/data/database/ListConverter.kt
ataurrahman112222
842,168,905
false
{"Kotlin": 105440}
package com.devs.faceRecognition.data.database import androidx.room.ProvidedTypeConverter import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.google.mlkit.vision.face.FaceLandmark import com.devs.faceRecognition.data.model.FaceInfo @ProvidedTypeConverter class ListConverter { private val stringListType = object : TypeToken<List<String>>() {}.type private val faceLandmarkListType = object : TypeToken<List<FaceLandmark>>() {}.type private val faceInfoListType = object : TypeToken<List<FaceInfo>>() {}.type @TypeConverter fun toString(value: List<String>): String = Gson().toJson(value, stringListType) @TypeConverter fun toStringList(value: String): List<String> = try { Gson().fromJson(value, stringListType) } catch (e: Exception) { listOf() } @TypeConverter fun toFaceLandmark(value: List<FaceLandmark>): String = Gson().toJson(value, faceLandmarkListType) @TypeConverter fun toFaceLandmarkList(value: String): List<FaceLandmark> = try { Gson().fromJson(value, faceLandmarkListType) } catch (e: Exception) { listOf() } @TypeConverter fun toFaceInfo(value: List<FaceInfo>): String = Gson().toJson(value, faceInfoListType) @TypeConverter fun toFaceInfo(value: String): List<FaceInfo> = try { Gson().fromJson(value, faceInfoListType) } catch (e: Exception) { listOf() } }
0
Kotlin
0
0
54b63d5c54b16efec757b6a6ff423056fbde507d
1,477
FaceRecognition
MIT License
app/src/test/java/com/lifecycle/demo/InfoEntity.kt
striveprince
211,611,448
false
null
package com.lifecycle.demo data class InfoEntity<T>(val code: Int,val msg: String,val result: T) data class Bean( val id:String, val issues:String, val master:String, val master_name:String, val max_number:Int, val observation_uid:String, val password:String )
0
Kotlin
0
2
651a6ecd744e8124c5002a075a4a8c325bebd977
290
kotlin
Apache License 2.0
1490.Clone N-ary Tree.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() { children = new ArrayList<Node>(); } public Node(int _val) { val = _val; children = new ArrayList<Node>(); } public Node(int _val,ArrayList<Node> _children) { val = _val; children = _children; } }; */ internal class Solution { fun cloneTree(root: Node?): Node? { if (root == null) { return null } val children: ArrayList<Node> = ArrayList() for (child in root.children) { children.add(cloneTree(child)) } return Node(root.`val`, children) } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
647
kotlin-leetcode
MIT License
app/src/androidTest/java/com/app/androidPixabay/ui/pixabay/list/PixabayListActivityTest.kt
yash786agg
241,149,101
false
null
package com.app.androidPixabay.ui.pixabay.list import androidx.test.espresso.Espresso.* import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.* import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.filters.LargeTest import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import androidx.test.rule.ActivityTestRule import com.app.androidPixabay.R import com.app.androidPixabay.utils.ConstantTest.Companion.TEST_TAG_VALUE import com.app.androidPixabay.utils.ConstantTest.Companion.TEST_USER_VALUE import com.app.androidPixabay.utils.EspressoIdlingResourceRule import com.app.androidPixabay.utils.RecyclerViewMatcher import org.junit.FixMethodOrder import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(AndroidJUnit4ClassRunner::class) @LargeTest class PixabayListActivityTest { @get:Rule var activityRule: ActivityTestRule<PixabayListActivity> = ActivityTestRule(PixabayListActivity::class.java,true,true) @get: Rule val espressoIdlingResourceRule = EspressoIdlingResourceRule() /* @Test fun a_test_isRcylvAndProgressBarVisible_onAppLaunch() { onView(withId(R.id.recylv_pixabay)) .check(matches(isDisplayed())) onView(withId(R.id.progress_bar)) .check(matches(CoreMatchers.not(isDisplayed()))) }*/ @Test fun checkDataInRecyclerView() { onView(RecyclerViewMatcher(R.id.recylv_pixabay).atPositionOnView(0, R.id.user_tv)) .check(matches(withText(TEST_USER_VALUE))) onView(RecyclerViewMatcher(R.id.recylv_pixabay).atPositionOnView(0, R.id.tag_tv)) .check(matches(withText(TEST_TAG_VALUE))) } @Test fun isAlertDialogVisible() { // Open Alert Dialog on click of list item onView(RecyclerViewMatcher(R.id.recylv_pixabay) .atPositionOnView(2, R.id.user_tv)) .perform(click()) onView(withId(android.R.id.button2)).perform((click())) } @Test fun selectRcylvItem_OpenDetailActivity() { // Click list item #LIST_ITEM_IN_TEST onView(RecyclerViewMatcher(R.id.recylv_pixabay) .atPositionOnView(0, R.id.user_tv)) .perform(click()) onView(withId(android.R.id.button1)).perform((click())) } }
0
Kotlin
0
0
a2ace2aa34b25afa6fa7adfee0d64868ff6ee2b7
2,445
PixaBay-Android
Apache License 2.0
app/src/main/java/com/stsd/selftaughtsoftwaredevelopers/androidsudokusolver/ui/component/DefaultIcon.kt
self-taught-software-developers
506,259,677
false
{"Kotlin": 88864}
package com.stsd.selftaughtsoftwaredevelopers.androidsudokusolver.ui.component import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import com.cerve.co.material3extension.designsystem.ExtendedTheme.sizes import com.cerve.co.material3extension.designsystem.ExtendedTheme.spacing import com.stsd.selftaughtsoftwaredevelopers.androidsudokusolver.ui.component.icon.Grid2x2 @Composable fun IconTitle( icon: ImageVector, text: String, modifier: Modifier = Modifier, onClick: () -> Unit = { } ) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(spacing.medium), horizontalAlignment = Alignment.CenterHorizontally ) { Surface( modifier = Modifier .clip(CircleShape) .clickable { onClick() }, color = Color.Black.copy(alpha = 0.1F) ) { Icon( modifier = Modifier .padding(spacing.medium) .size(sizes.xSmall), imageVector = icon, contentDescription = icon.name ) } Text( modifier = Modifier.padding(spacing.medium), text = text, textAlign = TextAlign.Center ) } } @Preview @Composable fun IconTitlePreview() { IconTitle( icon = Grid2x2, text = Grid2x2.name ) { } }
11
Kotlin
3
6
5e48440745ba653051a0bf403597bdc2e4887098
2,117
SudokuSolver
Apache License 2.0
src/main/kotlin/me/jakejmattson/discordkt/api/dsl/Command.kt
DiscordKt
271,063,846
false
null
@file:Suppress("unused") package me.jakejmattson.discordkt.api.dsl import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import me.jakejmattson.discordkt.api.* import me.jakejmattson.discordkt.api.arguments.ArgumentType import me.jakejmattson.discordkt.api.arguments.OptionalArg import me.jakejmattson.discordkt.api.locale.inject import me.jakejmattson.discordkt.internal.annotations.NestedDSL import me.jakejmattson.discordkt.internal.command.ParseResult import me.jakejmattson.discordkt.internal.command.convertArguments /** * The bundle of information to be executed when a command is invoked. * * @param arguments The ArgumentTypes accepted by this execution. * @param action The code to be run when this execution is fired. */ data class Execution<T : CommandEvent<*>>(val arguments: List<ArgumentType<*>>, val action: suspend T.() -> Unit) { /** * Mocks a method signature using [ArgumentType] names, ex: (a, b, c) */ val signature get() = "(${arguments.joinToString { it.name }})" /** * Each [ArgumentType] separated by a space ex: a b c */ val structure get() = arguments.joinToString(" ") { val type = it.name if (it is OptionalArg) "[$type]" else type } /** * Run the command logic. */ suspend fun execute(event: T) = action.invoke(event) } /** * @property names The name(s) this command can be executed by (case insensitive). * @property description A brief description of the command - used in documentation. * @property requiredPermission The permission level required to use this command. * @property category The category that this command belongs to - set automatically by CommandSet. * @property executions The list of [Execution] that this command can be run with. */ sealed class Command(open val names: List<String>, open var description: String, open var requiredPermission: Enum<*>) { /** * The first name in the [names] list. */ open val name: String get() = names.first() var category: String = "" val executions: MutableList<Execution<*>> = mutableListOf() /** * Whether or not the command can parse the given arguments into a container. * * @param args The raw string arguments to be provided to the command. * * @return The result of the parsing operation. */ suspend fun canParse(event: CommandEvent<*>, execution: Execution<*>, args: List<String>) = convertArguments(event, execution.arguments, args) is ParseResult.Success /** * Whether or not this command has permission to run with the given event. * * @param event The event context that will attempt to run the command. */ suspend fun hasPermissionToRun(event: CommandEvent<*>) = when { this is DmCommand && event.isFromGuild() -> false this is GuildCommand && !event.isFromGuild() -> false else -> { val config = event.discord.permissions val permissionLevels = config.levels val permissionContext = PermissionContext(event.discord, event.author, event.guild) val level = permissionLevels.indexOfFirst { (it as PermissionSet).hasPermission(permissionContext) } if (level != -1) level <= permissionLevels.indexOf(requiredPermission) else false } } /** * Invoke this command with the given args. */ @OptIn(DelicateCoroutinesApi::class) fun invoke(event: CommandEvent<TypeContainer>, args: List<String>) { GlobalScope.launch { val results = executions.map { it to convertArguments(event, it.arguments, args) } val success = results.firstOrNull { it.second is ParseResult.Success } if (success == null) { val failString = results.joinToString("\n") { val invocationExample = if (results.size > 1) "${event.rawInputs.rawMessageContent.substringBefore(" ")} ${it.first.structure}\n" else "" invocationExample + (it.second as ParseResult.Fail).reason } event.respond(internalLocale.badArgs.inject(event.rawInputs.commandName) + "\n$failString") return@launch } val (execution, result) = success event.args = (result as ParseResult.Success).argumentContainer (execution as Execution<CommandEvent<*>>).execute(event) } } protected fun <T : CommandEvent<*>> addExecution(argTypes: List<ArgumentType<*>>, execute: suspend T.() -> Unit) { executions.add(Execution(argTypes, execute)) } } /** * A command that can be executed from anywhere. */ open class GlobalCommand(override val names: List<String>, override var description: String, override var requiredPermission: Enum<*>) : Command(names, description, requiredPermission) { /** @suppress */ @NestedDSL fun execute(execute: suspend CommandEvent<NoArgs>.() -> Unit) = addExecution(listOf(), execute) /** @suppress */ @NestedDSL fun <A> execute(a: ArgumentType<A>, execute: suspend CommandEvent<Args1<A>>.() -> Unit) = addExecution(listOf(a), execute) /** @suppress */ @NestedDSL fun <A, B> execute(a: ArgumentType<A>, b: ArgumentType<B>, execute: suspend CommandEvent<Args2<A, B>>.() -> Unit) = addExecution(listOf(a, b), execute) /** @suppress */ @NestedDSL fun <A, B, C> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, execute: suspend CommandEvent<Args3<A, B, C>>.() -> Unit) = addExecution(listOf(a, b, c), execute) /** @suppress */ @NestedDSL fun <A, B, C, D> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, execute: suspend CommandEvent<Args4<A, B, C, D>>.() -> Unit) = addExecution(listOf(a, b, c, d), execute) /** @suppress */ @NestedDSL fun <A, B, C, D, E> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, e: ArgumentType<E>, execute: suspend CommandEvent<Args5<A, B, C, D, E>>.() -> Unit) = addExecution(listOf(a, b, c, d, e), execute) } /** * A command that can only be executed in a guild. */ open class GuildCommand(override val names: List<String>, override var description: String, override var requiredPermission: Enum<*>) : Command(names, description, requiredPermission) { /** @suppress */ @NestedDSL fun execute(execute: suspend GuildCommandEvent<NoArgs>.() -> Unit) = addExecution(listOf(), execute) /** @suppress */ @NestedDSL fun <A> execute(a: ArgumentType<A>, execute: suspend GuildCommandEvent<Args1<A>>.() -> Unit) = addExecution(listOf(a), execute) /** @suppress */ @NestedDSL fun <A, B> execute(a: ArgumentType<A>, b: ArgumentType<B>, execute: suspend GuildCommandEvent<Args2<A, B>>.() -> Unit) = addExecution(listOf(a, b), execute) /** @suppress */ @NestedDSL fun <A, B, C> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, execute: suspend GuildCommandEvent<Args3<A, B, C>>.() -> Unit) = addExecution(listOf(a, b, c), execute) /** @suppress */ @NestedDSL fun <A, B, C, D> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, execute: suspend GuildCommandEvent<Args4<A, B, C, D>>.() -> Unit) = addExecution(listOf(a, b, c, d), execute) /** @suppress */ @NestedDSL fun <A, B, C, D, E> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, e: ArgumentType<E>, execute: suspend GuildCommandEvent<Args5<A, B, C, D, E>>.() -> Unit) = addExecution(listOf(a, b, c, d, e), execute) } /** * A command that can only be executed in a DM. */ class DmCommand(override val names: List<String>, override var description: String, override var requiredPermission: Enum<*>) : Command(names, description, requiredPermission) { /** @suppress */ @NestedDSL fun execute(execute: suspend DmCommandEvent<NoArgs>.() -> Unit) = addExecution(listOf(), execute) /** @suppress */ @NestedDSL fun <A> execute(a: ArgumentType<A>, execute: suspend DmCommandEvent<Args1<A>>.() -> Unit) = addExecution(listOf(a), execute) /** @suppress */ @NestedDSL fun <A, B> execute(a: ArgumentType<A>, b: ArgumentType<B>, execute: suspend DmCommandEvent<Args2<A, B>>.() -> Unit) = addExecution(listOf(a, b), execute) /** @suppress */ @NestedDSL fun <A, B, C> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, execute: suspend DmCommandEvent<Args3<A, B, C>>.() -> Unit) = addExecution(listOf(a, b, c), execute) /** @suppress */ @NestedDSL fun <A, B, C, D> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, execute: suspend DmCommandEvent<Args4<A, B, C, D>>.() -> Unit) = addExecution(listOf(a, b, c, d), execute) /** @suppress */ @NestedDSL fun <A, B, C, D, E> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, e: ArgumentType<E>, execute: suspend DmCommandEvent<Args5<A, B, C, D, E>>.() -> Unit) = addExecution(listOf(a, b, c, d, e), execute) } /** * A command wrapper for a global discord slash command. * * @property name The name of the slash command. */ class GlobalSlashCommand(override val name: String, override var description: String, override var requiredPermission: Enum<*>) : Command(listOf(name), description, requiredPermission) { /** @suppress */ @NestedDSL fun execute(execute: suspend SlashCommandEvent<NoArgs>.() -> Unit) = addExecution(listOf(), execute) /** @suppress */ @NestedDSL fun <A> execute(a: ArgumentType<A>, execute: suspend SlashCommandEvent<Args1<A>>.() -> Unit) = addExecution(listOf(a), execute) /** @suppress */ @NestedDSL fun <A, B> execute(a: ArgumentType<A>, b: ArgumentType<B>, execute: suspend SlashCommandEvent<Args2<A, B>>.() -> Unit) = addExecution(listOf(a, b), execute) /** @suppress */ @NestedDSL fun <A, B, C> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, execute: suspend SlashCommandEvent<Args3<A, B, C>>.() -> Unit) = addExecution(listOf(a, b, c), execute) /** @suppress */ @NestedDSL fun <A, B, C, D> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, execute: suspend SlashCommandEvent<Args4<A, B, C, D>>.() -> Unit) = addExecution(listOf(a, b, c, d), execute) /** @suppress */ @NestedDSL fun <A, B, C, D, E> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, e: ArgumentType<E>, execute: suspend SlashCommandEvent<Args5<A, B, C, D, E>>.() -> Unit) = addExecution(listOf(a, b, c, d, e), execute) } /** * A command wrapper for a guild discord slash command. * * @property name The name of the slash command. */ class GuildSlashCommand(override val name: String, override var description: String, override var requiredPermission: Enum<*>) : Command(listOf(name), description, requiredPermission) { /** @suppress */ @NestedDSL fun execute(execute: suspend SlashCommandEvent<NoArgs>.() -> Unit) = addExecution(listOf(), execute) /** @suppress */ @NestedDSL fun <A> execute(a: ArgumentType<A>, execute: suspend SlashCommandEvent<Args1<A>>.() -> Unit) = addExecution(listOf(a), execute) /** @suppress */ @NestedDSL fun <A, B> execute(a: ArgumentType<A>, b: ArgumentType<B>, execute: suspend SlashCommandEvent<Args2<A, B>>.() -> Unit) = addExecution(listOf(a, b), execute) /** @suppress */ @NestedDSL fun <A, B, C> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, execute: suspend SlashCommandEvent<Args3<A, B, C>>.() -> Unit) = addExecution(listOf(a, b, c), execute) /** @suppress */ @NestedDSL fun <A, B, C, D> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, execute: suspend SlashCommandEvent<Args4<A, B, C, D>>.() -> Unit) = addExecution(listOf(a, b, c, d), execute) /** @suppress */ @NestedDSL fun <A, B, C, D, E> execute(a: ArgumentType<A>, b: ArgumentType<B>, c: ArgumentType<C>, d: ArgumentType<D>, e: ArgumentType<E>, execute: suspend SlashCommandEvent<Args5<A, B, C, D, E>>.() -> Unit) = addExecution(listOf(a, b, c, d, e), execute) } /** * Get a command by its name (case insensitive). */ operator fun MutableList<Command>.get(query: String) = firstOrNull { cmd -> cmd.names.any { it.equals(query, true) } }
2
Kotlin
9
51
cd7b9cd4e8b1d0270f0f99006e76df2abcf6e905
12,670
DiscordKt
MIT License
ChartboostMediation/src/main/java/com/chartboost/chartboostmediationsdk/domain/AdInteractionListener.kt
ChartBoost
647,839,758
false
{"Kotlin": 711726, "Ruby": 2509}
/* * Copyright 2022-2024 Chartboost, Inc. * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file. */ package com.chartboost.chartboostmediationsdk.domain /** * @suppress */ interface AdInteractionListener { fun onImpressionTracked(partnerAd: PartnerAd) fun onClicked(partnerAd: PartnerAd) fun onRewarded(partnerAd: PartnerAd) fun onDismissed( partnerAd: PartnerAd, error: ChartboostMediationAdException?, ) fun onExpired(partnerAd: PartnerAd) }
0
Kotlin
0
0
18948613638191a0639eb264ec6e39f3d37bf722
547
chartboost-mediation-android-sdk
MIT License
mvikotlin/src/commonMain/kotlin/com/arkivanov/mvikotlin/core/store/Executor.kt
arkivanov
437,014,963
false
{"Kotlin": 462372, "CSS": 842, "JavaScript": 716, "HTML": 583}
package com.arkivanov.mvikotlin.core.store import com.arkivanov.mvikotlin.core.annotations.MainThread import kotlin.js.JsName /** * `Executor` is the place for business logic. * It accepts `Intents` and `Actions` and produces `Messages` and `Labels`. * **Important**: please pay attention that it must not be a singleton. * * @see Store * @see Reducer * @see Bootstrapper */ interface Executor<in Intent : Any, in Action : Any, in State : Any, out Message : Any, out Label : Any> { /** * Initializes the [Executor], called internally by the [Store] * * @param callbacks an instance of [Callbacks] created by the [Store] */ @JsName("init") @MainThread fun init(callbacks: Callbacks<State, Message, Label>) /** * Called by the [Store] for every received `Intent` * * @param intent an `Intent` received by the [Store] */ @JsName("executeIntent") @MainThread fun executeIntent(intent: Intent) /** * Called by the [Store] for every `Action` produced by the [Bootstrapper] */ @JsName("executeAction") @MainThread fun executeAction(action: Action) /** * Disposes the [Executor], called by the [Store] when disposed */ @MainThread fun dispose() /** * A set of callbacks used for communication between the [Bootstrapper] and the [Store] */ interface Callbacks<out State, in Message, in Label> { /** * Returns current `State` of the [Store] */ val state: State /** * Dispatches the `Message` to the [Store], it then goes to the [Reducer]. * A new `State` will be immediately available after this method returns. * * @param message a `Message` to be dispatched to the [Reducer] */ @JsName("onMessage") @MainThread fun onMessage(message: Message) /** * Publishes the `Label`, it then will be emitted by the [Store] * * @param label a `Label` to be published */ @JsName("onLabel") @MainThread fun onLabel(label: Label) } }
7
Kotlin
24
661
b8f93f42bc6871e8d114135d8a026bf0de1bec68
2,148
MVIKotlin
Apache License 2.0
Meet_the_Kotlin_lecture/src/main/kotlin/net/milosvasic/conferences/bosch/meetup1/Main.kt
milos85vasic
104,644,926
false
null
package net.milosvasic.conferences.bosch.meetup1 /** * Meet the Kotlin: * * 1. Variables vs constants * 2. Nullability * 3. Collections * 4. Functions * 5. Classes, Abstract classes, Interfaces * 6. Data classes * 7. Extension functions * 8. Misc */ fun main(args: Array<String>) = println(logo)
0
Kotlin
0
2
450775f4041dfe5e96df7b06f026ab9b2e3e3537
315
Garage-Lab-Bosch-meetup
Apache License 2.0
src/main/kotlin/github/cheng/engine/TelegramBot.kt
YiGuan-z
702,319,315
false
{"Kotlin": 88335}
package github.cheng.engine import com.github.kotlintelegrambot.Bot import com.github.kotlintelegrambot.dispatch import com.github.kotlintelegrambot.logging.LogLevel import github.cheng.TelegramResources import github.cheng.application.Application import github.cheng.application.ApplicationEngine import github.cheng.application.env.getListOrNull import github.cheng.application.env.getStringOrNull import github.cheng.module.bot.bot import github.cheng.module.mkdirImageFinder import github.cheng.module.thisLogger import github.cheng.setOnce object TelegramBot : ApplicationEngine { @Suppress("MemberVisibilityCanBePrivate") internal var botInstance: Bot by setOnce() @PublishedApi internal var application:Application by setOnce() override fun create(application: Application) { this.application = application with(application) { configGlobalResource() mkdirImageFinder() configBot() } botInstance = application.instance(bot) } override fun start() { botInstance.startPolling().also { val logger = thisLogger<Application>() val botAccount = botInstance.getMe().getOrNull() ?: throw TelegramBotTokenError("get bot account failed, please check bot token or network") botAccount.toString() logger.info("机器人已启动") logger.info("机器人账号信息: $botAccount") } } override fun stop() { botInstance.stopPolling() } } class TelegramBotTokenError(msg: String, cause: Throwable? = null) : RuntimeException(msg, cause) context (Application) private fun configGlobalResource() { appEnvironment.property("bot.lang.default").getStringOrNull()?.let { TelegramResources.defaultLang = it } appEnvironment.property("bot.master").getStringOrNull()?.let { TelegramResources.adminName = it } appEnvironment.property("bot.images.file_storage").getStringOrNull()?.let { TelegramResources.imageStorage = it } appEnvironment.property("bot.images.max_images").getStringOrNull()?.let { TelegramResources.maxImages = it.toInt() } appEnvironment.property("bot.images.sticker_sources").getListOrNull()?.let { TelegramResources.stickerSources = it } } context (Application) private fun configBot() { install(bot) { token = appEnvironment.config("bot").property("tg_token").getString() logLevel = LogLevel.Error dispatch { val dispatcher = this botDispatcherModules.forEach { (_, botDispatcherModule) -> botDispatcherModule.apply { dispatcher.dispatch() } logger.info("Bot Dispatcher Module loaded: {}", botDispatcherModule.dispatcherName) logger.info("Bot Dispatcher Module description: {}", botDispatcherModule.description) } } } }
0
Kotlin
0
0
c6e213acebde1e41b335fee9a4d48f6244165ca9
2,917
telegram-stickers-collect-bot
MIT License
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/providers/defaults/DefaultAttachmentIconProvider.kt
sceyt
549,073,085
false
{"Kotlin": 2713714, "Java": 107920}
package com.sceyt.chatuikit.providers.defaults import android.content.Context import android.graphics.drawable.Drawable import com.sceyt.chatuikit.R import com.sceyt.chatuikit.data.models.messages.AttachmentTypeEnum import com.sceyt.chatuikit.data.models.messages.SceytAttachment import com.sceyt.chatuikit.extensions.getCompatDrawable import com.sceyt.chatuikit.providers.VisualProvider data object DefaultAttachmentIconProvider : VisualProvider<SceytAttachment, Drawable?> { override fun provide(context: Context, from: SceytAttachment): Drawable? { val drawableId = when (from.type) { AttachmentTypeEnum.File.value -> R.drawable.sceyt_ic_file_filled AttachmentTypeEnum.Link.value -> R.drawable.sceyt_ic_link_attachment AttachmentTypeEnum.Voice.value -> R.drawable.sceyt_ic_voice_white else -> return null } return context.getCompatDrawable(drawableId) } }
0
Kotlin
1
2
ce9c1b95555fadaafcd11f0d073fcdb07ca49600
940
sceyt-chat-android-uikit
MIT License
src/main/kotlin/me/jakejmattson/kutils/api/arguments/MemberArg.kt
markhc
271,817,502
true
{"Kotlin": 126651}
package me.jakejmattson.kutils.api.arguments import me.jakejmattson.kutils.api.dsl.arguments.* import me.jakejmattson.kutils.api.dsl.command.CommandEvent import me.jakejmattson.kutils.api.extensions.stdlib.trimToID import net.dv8tion.jda.api.entities.Member open class MemberArg(override val name: String = "Member", private val allowsBot: Boolean = false) : ArgumentType<Member>() { companion object : MemberArg() override fun convert(arg: String, args: List<String>, event: CommandEvent<*>): ArgumentResult<Member> { val guild = event.guild ?: return ArgumentResult.Error("Member's can only belong to guilds.") val id = arg.trimToID() val member = guild.getMemberById(id) ?: return ArgumentResult.Error("Could not find a member in this guild with ID $id") if (!allowsBot && member.user.isBot) return ArgumentResult.Error("A bot is not a valid member arg.") return ArgumentResult.Success(member) } override fun generateExamples(event: CommandEvent<*>) = listOf(event.author.id) }
0
null
0
0
473fcd9ca6391bef2512879aa383d010c6195e04
1,067
KUtils
MIT License
app/src/main/java/org/ballistic/dreamjournalai/feature_dream/presentation/add_edit_dream_screen/components/DateAndTimeButtons.kt
ErickSorto
546,852,272
false
null
package org.ballistic.dreamjournalai.feature_dream.presentation.add_edit_dream_screen.components import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults.buttonColors import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import org.ballistic.dreamjournalai.feature_dream.presentation.add_edit_dream_screen.AddEditDreamViewModel @RequiresApi(Build.VERSION_CODES.O) @Composable fun DateAndTimeButtonsLayout( viewModel: AddEditDreamViewModel = hiltViewModel(), ) { Row( modifier = Modifier .padding(0.dp, 8.dp, 0.dp, 8.dp) .clip(RoundedCornerShape(4.dp)) .background(Color.White.copy(alpha = 0.3f)), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { DateButton(viewModel = viewModel, modifier = Modifier .weight(1f) .background(Color.Transparent), onClick = { viewModel.calendarState.show() }) Spacer( modifier = Modifier .width(1.dp) .height(32.dp) .background(Color.Black.copy(alpha = 0.8f)) ) SleepTimeButton(viewModel = viewModel, modifier = Modifier.weight(1f), onClick = { viewModel.sleepTimePickerState.show() }) Spacer( modifier = Modifier .width(1.dp) .height(32.dp) .background(Color.Black.copy(alpha = 0.8f)) ) WakeTimeButton(viewModel = viewModel, modifier = Modifier.weight(1f), onClick = { viewModel.wakeTimePickerState.show() }) } } @RequiresApi(Build.VERSION_CODES.O) @Composable fun DateButton( viewModel: AddEditDreamViewModel, modifier: Modifier = Modifier, onClick: () -> Unit, ) { Button( onClick = onClick, modifier = modifier .padding(0.dp, 8.dp, 0.dp, 8.dp) .clip(RoundedCornerShape(4.dp)) .background(Color.Transparent), colors = buttonColors( containerColor = Color.Transparent, ) ) { Column( modifier = Modifier.background(Color.Transparent), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "Date", fontSize = 12.sp, color = Color.Black) Text( text = viewModel.dreamUiState.value.dreamInfo.dreamDate, fontSize = 10.sp, color = Color.Black, modifier = Modifier.padding(vertical = 1.dp) ) } } } @RequiresApi(Build.VERSION_CODES.O) @Composable fun SleepTimeButton( viewModel: AddEditDreamViewModel, modifier: Modifier = Modifier, onClick: () -> Unit, ) { Button( onClick = onClick, modifier = modifier .padding(0.dp, 8.dp, 0.dp, 8.dp) .clip(RoundedCornerShape(8.dp)) .background(Color.Transparent), colors = buttonColors( containerColor = Color.Transparent, ) ) { Column( modifier = Modifier.background(Color.Transparent), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "Sleep Time", fontSize = 12.sp, color = Color.Black) Text( text = viewModel.dreamUiState.value.dreamInfo.dreamSleepTime, fontSize = 14.sp, color = Color.Black ) } } } @RequiresApi(Build.VERSION_CODES.O) @Composable fun WakeTimeButton( viewModel: AddEditDreamViewModel, modifier: Modifier = Modifier, onClick: () -> Unit, ) { Button( onClick = onClick, modifier = modifier .padding(0.dp, 8.dp, 0.dp, 8.dp) .clip(RoundedCornerShape(8.dp)) .background(Color.Transparent), colors = buttonColors( containerColor = Color.Transparent, ) ) { Column( modifier = Modifier.background(Color.Transparent), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = "Wake Time", fontSize = 12.sp, color = Color.Black) Text( text = viewModel.dreamUiState.value.dreamInfo.dreamWakeTime, fontSize = 14.sp, color = Color.Black ) } } }
0
Kotlin
0
1
133a328b5e89c62f53bdfdab7d5e257977fb89b1
4,944
Dream-Journal-AI
MIT License
composeApp/src/commonMain/kotlin/com/borealnetwork/allen/modules/product/domain/navigation/ProductClientScreen.kt
baudelioandalon
742,906,893
false
{"Kotlin": 424981, "Java": 97326, "Swift": 532}
package com.borealnetwork.allen.modules.product.domain.navigation sealed class ProductClientScreen(val route: String) { data object SearchClientScreen : ProductClientScreen("search_client_screen") data object ResultProductsClient : ProductClientScreen("result_products_client_screen") data object ProductDetailClient : ProductClientScreen("product_detail_client_screen") data object RatingProductClient : ProductClientScreen("rating_product_client_screen") data object QuestionProductClient : ProductClientScreen("question_product_client_screen") data object FavoritesProductsClient : ProductClientScreen("favorites_products_client_screen") }
0
Kotlin
0
0
ad163dde7d0c7a9e2d66eb79f66417bd40d24d92
668
AllenMultiplatform
Apache License 2.0
convention-plugin-test-option/src/main/kotlin/EmulatorJobsMatrix.kt
GitLiveApp
213,915,094
false
{"Kotlin": 712421, "Ruby": 18024, "JavaScript": 469}
import com.google.gson.GsonBuilder import org.gradle.api.Project import java.io.File import java.util.Properties class EmulatorJobsMatrix { private val gson by lazy { GsonBuilder() .disableHtmlEscaping() .setPrettyPrinting() .create() } fun createMatrixJsonFiles(rootProject: Project) { mapOf( "emulator_jobs_matrix.json" to getEmulatorTaskList(rootProject = rootProject), "ios_test_jobs_matrix.json" to getIosTestTaskList(rootProject = rootProject), "js_test_jobs_matrix.json" to getJsTestTaskList(rootProject = rootProject), "jvm_test_jobs_matrix.json" to getJvmTestTaskList(rootProject = rootProject) ) .mapValues { entry -> entry.value.map { it.joinToString(separator = " ") } } .forEach { (fileName: String, taskList: List<String>) -> val matrix = mapOf("gradle_tasks" to taskList) val jsonText = gson.toJson(matrix) rootProject.layout.buildDirectory.asFile.get().also { buildDir -> buildDir.mkdirs() File(buildDir, fileName).writeText(jsonText) } } } fun getIosTestTaskList(rootProject: Project): List<List<String>> = rootProject.subprojects.filter { subProject -> subProject.name == "test-utils" || (rootProject.property("${subProject.name}.skipIosTests") == "true").not() }.map { subProject -> when (val osArch = System.getProperty("os.arch")) { "x86", "i386", "ia-32", "i686" -> "${subProject.path}:iosX86Test" "x86_64", "amd64", "x64", "x86-64" -> "${subProject.path}:iosX64Test" "arm", "arm-v7", "armv7", "arm32", "arm64", "arm-v8", "aarch64" -> "${subProject.path}:iosSimulatorArm64Test" else -> throw Error("Unexpected System.getProperty(\"os.arch\") = $osArch") } }.map { listOf("cleanTest", it) } fun getJsTestTaskList(rootProject: Project): List<List<String>> = rootProject.subprojects.filter { subProject -> subProject.name == "test-utils" || (rootProject.property("${subProject.name}.skipJsTests") == "true").not() }.map { subProject -> "${subProject.path}:jsTest" }.map { listOf("cleanTest", it) } fun getJvmTestTaskList(rootProject: Project): List<List<String>> = rootProject.subprojects.filter { subProject -> subProject.name == "test-utils" || (rootProject.property("${subProject.name}.skipJvmTests") == "true").not() }.map { subProject -> "${subProject.path}:jvmTest" }.map { listOf("cleanTest", it) } fun getEmulatorTaskList(rootProject: Project): List<List<String>> = rootProject.subprojects.filter { subProject -> File(subProject.projectDir, "src${File.separator}commonTest").exists() || File( subProject.projectDir, "src${File.separator}androidInstrumentedTest" ).exists() }.map { subProject -> "${subProject.path}:gradleManagedDeviceDebugAndroidTest" }.map { taskName -> mutableListOf(taskName).also { it.add("--no-parallel") it.add("--max-workers=1") it.add("-Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect") it.add("-Pandroid.experimental.testOptions.managedDevices.emulator.showKernelLogging=true") }.also { if (!true.toString().equals(other = System.getenv("CI"), ignoreCase = true)) { it.add("--enable-display") } } } } fun getAndroidSdkPath(rootDir: File): String? = Properties().apply { val propertiesFile = File(rootDir, "local.properties") if (propertiesFile.exists()) { load(propertiesFile.inputStream()) } }.getProperty("sdk.dir").let { propertiesSdkDirPath -> (propertiesSdkDirPath ?: System.getenv("ANDROID_HOME")) } fun getSdkmanagerFile(rootDir: File): File? = getAndroidSdkPath(rootDir = rootDir)?.let { sdkDirPath -> println("sdkDirPath: $sdkDirPath") val files = File(sdkDirPath).walk().filter { file -> file.path.contains("cmdline-tools") && file.path.endsWith("sdkmanager") } files.forEach { println("walk: ${it.absolutePath}") } val sdkmanagerFile = files.firstOrNull() println("sdkmanagerFile: $sdkmanagerFile") sdkmanagerFile }
83
Kotlin
155
1,138
312beedd23283042277ae6d00393ada87d907589
4,716
firebase-kotlin-sdk
Apache License 2.0
miruken/src/test/kotlin/com/miruken/callback/PropertiesTest.kt
coridrew
151,555,181
true
{"Kotlin": 521215}
package com.miruken.callback import com.miruken.assertAsync import com.miruken.concurrent.Promise import com.miruken.container.Managed import com.miruken.container.TestContainer import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import java.util.* import kotlin.test.* class PropertiesTest { @Rule @JvmField val testName = TestName() class Foo interface Auction { fun buy(itemId: Long): UUID } @Test fun `Delegates property to handler`() { val foo = Foo() val handler = Handler().provide(foo) val instance = object { val foo by handler.get<Foo>() } assertSame(foo, instance.foo) } @Test fun `Delegates optional property to handler`() { val foo = Foo() val handler = Handler().provide(foo) val instance = object { val foo by handler.get<Foo?>() } assertSame(foo, instance.foo) } @Test fun `Ignores missing optional property`() { val handler = Handler() val instance = object { val foo by handler.get<Foo?>() } assertNull(instance.foo) } @Test fun `Delegates list property to handler`() { val handler = object : Handler() { @Provides fun provideFoos() = listOf(Foo(), Foo(), Foo()) } val instance = object { val foos by handler.getAll<Foo>() } assertEquals(3, instance.foos.size) } @Test fun `Delegates array property to handler`() { val handler = object : Handler() { @Provides fun provideFoos() = listOf(Foo(), Foo(), Foo()) } val instance = object { val foos by handler.getArray<Foo>() } assertEquals(3, instance.foos.size) } @Test fun `Delegates primitive property to handler`() { val handler = object : Handler() { @Provides val primes = listOf(2,3,5,7,11) @Provides @Key("help") val primaryHelp = "www.help.com" @Provides @Key("help") val secondaryHelp = "www.help2.com" @Provides @Key("help") val criticalHelp = "www.help3.com" } val instance = object { val primes by handler.get<IntArray>() val help by handler.getArray<String>() } assertTrue(instance.primes.contentEquals(arrayOf(2,3,5,7,11).toIntArray())) assertEquals(3, instance.help.size) assertTrue(instance.help.contains("www.help.com")) assertTrue(instance.help.contains("www.help2.com")) assertTrue(instance.help.contains("www.help3.com")) } @Test fun `Uses empty list property if missing`() { val instance = object { val foos by Handler().getAll<Foo>() } assertEquals(0, instance.foos.size) } @Test fun `Delegates promise property to handler`() { val foo = Foo() val handler = Handler().provide(foo) val instance = object { val foo by handler.getAsync<Foo>() } assertAsync(testName) { done -> instance.foo then { assertSame(foo, it) done() } } } @Test fun `Delegates optional promise property to handler`() { val handler = Handler() val instance = object { val foo by handler.getAsync<Foo?>() } assertAsync(testName) { done -> instance.foo then { assertNull(it) done() } } } @Test fun `Delegates promise list property to handler`() { val handler = object : Handler() { @Provides fun provideFoos() = Promise.resolve(listOf(Foo(), Foo())) } val instance = object { val foo by handler.getAllAsync<Foo>() } assertAsync(testName) { done -> instance.foo then { assertEquals(2, it.size) done() } } } @Test fun `Delegates promise array property to handler`() { val handler = object : Handler() { @Provides fun provideFoos() = Promise.resolve(listOf(Foo(), Foo())) } val instance = object { val foo by handler.getArrayAsync<Foo>() } assertAsync(testName) { done -> instance.foo then { assertEquals(2, it.size) done() } } } @Test fun `Delegates proxy property to handler`() { val handler = object : Handler(), Auction { override fun buy(itemId: Long): UUID = UUID.randomUUID() } val instance = object { @Proxy val auction by handler.get<Auction>() } assertNotNull(instance.auction.buy(2)) } @Test fun `Delegates container property to handler`() { val handler = TestContainer() val instance = object { @Managed val foo by handler.get<Foo>() } assertNotNull(instance.foo) } @Test fun `Delegates promise container property to handler`() { val handler = TestContainer() val instance = object { @Managed val foo by handler.getAsync<Foo>() } assertAsync(testName) { done -> instance.foo then { assertNotNull(it) done() } } } @Test fun `Delegates property to handler once`() { val handler = object : Handler() { @Provides fun provideFoo() = Foo() } val instance = object { val foo by handler.get<Foo>() } assertSame(instance.foo, instance.foo) } @Test fun `Delegates property to handler always`() { val handler = object : Handler() { @Provides fun provideFoo() = Foo() } val instance = object { val foo by handler.link<Foo>() } assertNotSame(instance.foo, instance.foo) } @Test fun `Rejects property delegation if missing`() { val handler = Handler() val instance = object { val foo by handler.get<Foo>() } assertFailsWith(IllegalStateException::class) { instance.foo } } @Test fun `Rejects promise property delegation if missing`() { val handler = Handler() val instance = object { val foo by handler.getAsync<Foo>() } assertAsync(testName) { done -> instance.foo catch { assertTrue(it is IllegalStateException) done() } } } }
0
Kotlin
1
0
b39c281286eceda5479c0bf3561db9980fcf7f5a
6,835
Miruken-1
MIT License
src/main/kotlin/no/nav/amt/person/service/controller/dto/NavBrukerDto.kt
navikt
618,357,446
false
{"Kotlin": 318629, "PLpgSQL": 635, "Dockerfile": 156}
package no.nav.amt.person.service.controller.dto import no.nav.amt.person.service.nav_bruker.NavBruker import no.nav.amt.person.service.nav_enhet.NavEnhet import no.nav.amt.person.service.person.model.Adresse import java.util.UUID data class NavBrukerDto ( val personId: UUID, val personident: String, val fornavn: String, val mellomnavn: String?, val etternavn: String, val navVeilederId: UUID?, val navEnhet: NavEnhet?, val telefon: String?, val epost: String?, val erSkjermet: Boolean, val adresse: Adresse? ) fun NavBruker.toDto() = NavBrukerDto( personId = this.person.id, personident = this.person.personident, fornavn = this.person.fornavn, mellomnavn = this.person.mellomnavn, etternavn = this.person.etternavn, navVeilederId = this.navVeileder?.id, navEnhet = this.navEnhet, telefon = this.telefon, epost = this.epost, erSkjermet = this.erSkjermet, adresse = this.adresse )
0
Kotlin
0
0
9b894eb62ed622a0dc51986b5624565fe5924cee
908
amt-person-service
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/ExtensionHolder.kt
arkon
127,645,159
false
null
package eu.kanade.tachiyomi.ui.browse.extension import android.view.View import androidx.core.view.isVisible import coil.clear import coil.load import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.databinding.ExtensionItemBinding import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.util.system.LocaleHelper class ExtensionHolder(view: View, val adapter: ExtensionAdapter) : FlexibleViewHolder(view, adapter) { private val binding = ExtensionItemBinding.bind(view) init { binding.extButton.setOnClickListener { adapter.buttonClickListener.onButtonClick(bindingAdapterPosition) } binding.cancelButton.setOnClickListener { adapter.buttonClickListener.onCancelButtonClick(bindingAdapterPosition) } } fun bind(item: ExtensionItem) { val extension = item.extension binding.name.text = extension.name binding.version.text = extension.versionName binding.lang.text = LocaleHelper.getSourceDisplayName(extension.lang, itemView.context) binding.warning.text = when { extension is Extension.Untrusted -> itemView.context.getString(R.string.ext_untrusted) extension is Extension.Installed && extension.isUnofficial -> itemView.context.getString(R.string.ext_unofficial) extension is Extension.Installed && extension.isObsolete -> itemView.context.getString(R.string.ext_obsolete) else -> "" }.uppercase() binding.icon.clear() if (extension is Extension.Available) { binding.icon.load(extension.iconUrl) } else { extension.getApplicationIcon(itemView.context)?.let { binding.icon.setImageDrawable(it) } } bindButtons(item) } @Suppress("ResourceType") fun bindButtons(item: ExtensionItem) = with(binding.extButton) { val extension = item.extension val installStep = item.installStep setText( when (installStep) { InstallStep.Pending -> R.string.ext_pending InstallStep.Downloading -> R.string.ext_downloading InstallStep.Installing -> R.string.ext_installing InstallStep.Installed -> R.string.ext_installed InstallStep.Error -> R.string.action_retry InstallStep.Idle -> { when (extension) { is Extension.Installed -> { if (extension.hasUpdate) { R.string.ext_update } else { R.string.action_settings } } is Extension.Untrusted -> R.string.ext_trust is Extension.Available -> R.string.ext_install } } } ) val isIdle = installStep == InstallStep.Idle || installStep == InstallStep.Error binding.cancelButton.isVisible = !isIdle isEnabled = isIdle isClickable = isIdle } }
92
null
58
9
2f07f226b8182699884262ac67139454d5b7070d
3,237
tachiyomi
Apache License 2.0
core-db/src/main/java/io/novafoundation/nova/core_db/model/chain/ChainRuntimeInfoLocal.kt
novasamatech
415,834,480
false
{"Kotlin": 7667771, "Java": 14723, "JavaScript": 425}
package com.dfinn.wallet.core_db.model.chain import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index @Entity( tableName = "chain_runtimes", primaryKeys = ["chainId"], indices = [ Index(value = ["chainId"]) ], foreignKeys = [ ForeignKey( entity = ChainLocal::class, parentColumns = ["id"], childColumns = ["chainId"], onDelete = ForeignKey.CASCADE ) ] ) class ChainRuntimeInfoLocal( val chainId: String, val syncedVersion: Int, val remoteVersion: Int, )
17
Kotlin
6
9
67cd6fd77aae24728a27b81eb7f26ac586463aaa
594
nova-wallet-android
Apache License 2.0
shared/src/androidMain/kotlin/common/GalleryManager.android.kt
razaghimahdi
714,632,664
false
null
package permissions import android.content.ContentResolver import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import extensions.BitmapUtils @Composable actual fun rememberGalleryManager(onResult: (SharedImage?) -> Unit): GalleryManager { val context = LocalContext.current val contentResolver: ContentResolver = context.contentResolver val galleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> uri?.let { onResult.invoke(SharedImage(BitmapUtils.getBitmapFromUri(uri, contentResolver))) // } } return remember { GalleryManager(onLaunch = { galleryLauncher.launch( PickVisualMediaRequest( mediaType = ActivityResultContracts.PickVisualMedia.ImageOnly ) ) }) } } actual class GalleryManager actual constructor(private val onLaunch: () -> Unit) { actual fun launch() { onLaunch() } }
1
null
9
97
6047cf13ab86a9dd74c8ea4bcba7a9771ec8ad0e
1,285
Shopping-By-KMP
MIT License
src/main/kotlin/rocks/leight/core/api/message/MessageException.kt
marek-hanzal
242,307,099
false
null
package rocks.leight.core.api.message import rocks.leight.core.api.CoreException open class MessageException(message: String, cause: Throwable? = null) : CoreException(message, cause)
2
Kotlin
0
1
38ebc399d6e43ec3a433ae78d1545aae516cce27
186
leight-core
MIT License
app/src/main/java/com/perol/asdpl/pixivez/core/PicListFragment.kt
ultranity
258,955,010
false
null
/* * MIT License * * Copyright (c) 2023 Ultranity * * 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.perol.asdpl.pixivez.core import android.annotation.SuppressLint import android.app.DatePickerDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.perol.asdpl.pixivez.R import com.perol.asdpl.pixivez.base.MaterialDialogs import com.perol.asdpl.pixivez.base.checkUpdate import com.perol.asdpl.pixivez.data.model.Illust import com.perol.asdpl.pixivez.databinding.FragmentListFabBinding import com.perol.asdpl.pixivez.databinding.HeaderFilterBinding import com.perol.asdpl.pixivez.objects.CrashHandler import com.perol.asdpl.pixivez.objects.DataHolder import com.perol.asdpl.pixivez.objects.argument import com.perol.asdpl.pixivez.objects.argumentNullable import com.perol.asdpl.pixivez.services.Event import com.perol.asdpl.pixivez.services.FlowEventBus import com.perol.asdpl.pixivez.ui.FragmentActivity import com.perol.asdpl.pixivez.ui.home.trend.CalendarViewModel import com.perol.asdpl.pixivez.ui.settings.BlockViewModel import com.perol.asdpl.pixivez.ui.user.BookMarkTagViewModel import com.perol.asdpl.pixivez.ui.user.TagsShowDialog import com.perol.asdpl.pixivez.view.BounceEdgeEffectFactory import kotlinx.coroutines.launch open class PicListFragment : Fragment() { companion object { @JvmStatic fun newInstance( mode: String, tabPosition: Int = 0, extraArgs: MutableMap<String, Any?>? = null ) = PicListFragment().apply { this.TAG = mode this.tabPosition = tabPosition this.extraArgs = extraArgs } } protected open var TAG: String by argument("PicListFragment") private var tabPosition: Int by argument(0) var extraArgs: MutableMap<String, Any?>? by argumentNullable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.setonLoadFirstRx(TAG, extraArgs) filterModel.TAG = TAG } var isLoaded = false private var _binding: FragmentListFabBinding? = null private var _headerBinding: HeaderFilterBinding? = null // This property is only valid between onCreateView and onDestroyView. protected val binding get() = _binding!! protected val headerBinding get() = _headerBinding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListFabBinding.inflate(inflater, container, false) _headerBinding = HeaderFilterBinding.inflate(inflater) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null _headerBinding = null } override fun onResume() { isLoaded = viewModel.data.value != null super.onResume() CrashHandler.instance.d("PicListFragment", "$TAG $tabPosition resume $isLoaded") if (!isLoaded) { isLoaded = true viewModel.onLoadFirst() CrashHandler.instance.d("PicListFragment", "$TAG $tabPosition data reload") } else { //DataHolder.modifiedIllusts.forEach{ // picListAdapter.notifyItemChanged(picListAdapter.getItemRealPosition(it)) //} //picListAdapter.notifyBoundViewChanged() } } open fun onDataLoadedListener(illusts: MutableList<Illust>): MutableList<Illust> { return illusts } protected open val onDataAddedListener: (() -> Unit) = { updateHintText() } open lateinit var picListAdapter: PicListAdapter protected open fun ownerProducer(): ViewModelStoreOwner { return when (TAG) { TAG_TYPE.Rank.name -> { requireParentFragment()//requireActivity() } else -> this } } protected open val viewModel: PicListViewModel by viewModels() protected val filterModel: FilterViewModel by viewModels(::ownerProducer) @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //viewModel.filterModel = filterModel filterModel.init(TAG) filterModel.spanNum = 2 * requireContext().resources.configuration.orientation binding.recyclerview.layoutManager = StaggeredGridLayoutManager( filterModel.spanNum, StaggeredGridLayoutManager.VERTICAL ) configAdapter(false) picListAdapter.checkEmptyListener = { if (picListAdapter.data.size == 0) { picListAdapter.showEmptyView(false) //stop autoload as a warning if filter risky! if (picListAdapter.mData.size > 0) { picListAdapter.isAutoLoadMore = false picListAdapter.setOnManualLoadMoreListener { picListAdapter.isAutoLoadMore = true picListAdapter.setOnManualLoadMoreListener(null) } } } updateHintText() } viewModel.isRefreshing.observe(viewLifecycleOwner) { binding.swipeRefreshLayout.isRefreshing = it } viewModel.data.observe(viewLifecycleOwner) { if (it != null) { picListAdapter.initData(onDataLoadedListener(it)) //TODO: IllustCacheRepo.register(this, picListAdapter.mData) binding.recyclerview.edgeEffectFactory = BounceEdgeEffectFactory() } else { if (picListAdapter.mData.isEmpty()) //show error only if first load picListAdapter.showEmptyView(true) } isLoaded = true viewModel.isRefreshing.value = false } viewModel.dataAdded.observe(viewLifecycleOwner) { if (it != null) { picListAdapter.addFilterData(it) onDataAddedListener.invoke() } else { picListAdapter.loadMoreFail() } } viewModel.nextUrl.observe(viewLifecycleOwner) { if (it != null) { picListAdapter.loadMoreComplete() } else { picListAdapter.loadMoreEnd() } } filterModel.filter.blockTags = BlockViewModel.getBlockTagString() lifecycleScope.launch { //check change FlowEventBus.observe<Event.BlockTagsChanged>(viewLifecycleOwner) { filterModel.filter.blockTags = it.blockTags //refresh current picListAdapter.resetFilterFlag() } } headerBinding.imgBtnConfig.setOnClickListener { //TODO: support other layoutManager val layoutManager = binding.recyclerview.layoutManager as StaggeredGridLayoutManager showFilterDialog( requireContext(), this, filterModel, layoutInflater, layoutManager, ).apply { if (TAG != TAG_TYPE.Collect.name) neutralButton(R.string.download) { DataHolder.dataListRef = viewModel.data.value DataHolder.nextUrlRef = viewModel.nextUrl.value FragmentActivity.start(requireContext(), TAG_TYPE.Collect.name) } } } configByTAG() //TODO: check // binding.recyclerview.addItemDecoration(GridItemDecoration()) binding.swipeRefreshLayout.setOnRefreshListener { viewModel.onLoadFirst() } picListAdapter.setOnLoadMoreListener { viewModel.onLoadMore() } } @SuppressLint("SetTextI18n") private fun updateHintText() { headerBinding.imgBtnConfig.text = "${picListAdapter.data.size}/${picListAdapter.mData.size}" } open fun configByTAG() = when (TAG) { TAG_TYPE.UserBookmark.name -> { val tagModel: BookMarkTagViewModel by viewModels(::ownerProducer) headerBinding.imgBtnR.setText(R.string.publics) headerBinding.imgBtnR.setOnClickListener { val id = extraArgs!!["userid"] as Int tagModel.tags.value.also { TagsShowDialog.newInstance(id).also { it.callback = TagsShowDialog.Callback { tag, public -> extraArgs!!["tag"] = tag extraArgs!!["pub"] = public viewModel.onLoadFirst() } }.show(childFragmentManager) } ?: run { //TODO: viewModel.getTags(id) } } } TAG_TYPE.Rank.name -> { val shareModel: CalendarViewModel by viewModels(::ownerProducer) shareModel.picDateShare.value?.also { extraArgs!!["pickDate"] = it } shareModel.picDateShare.observe(viewLifecycleOwner) { viewModel.onLoadFirst() } //TODO: RecycledViewPool 导致 list 间 item click/longclick事件 错误配置 //binding.recyclerview.setRecycledViewPool(shareModel.pool) headerBinding.imgBtnR.apply { setText(R.string.choose_date) setIconResource(R.drawable.ic_calendar) setTextColor( AppCompatResources.getColorStateList( requireContext(), com.google.android.material.R.color.mtrl_tabs_icon_color_selector_colored ) ) } headerBinding.imgBtnR.setOnClickListener { val dateNow = shareModel.getDateStr() shareModel.apply { DatePickerDialog( requireContext(), { p0, year, month, day -> ymd.setDate(year, month, day) if (ymd.toStr() == dateNow) { picDateShare.checkUpdate(null) } else { picDateShare.checkUpdate(ymd.toStr()) } extraArgs!!["pickDate"] = picDateShare.value }, ymd.year, ymd.month, ymd.day ).also { it.datePicker.maxDate = System.currentTimeMillis() } .show() } } } else -> { val restrictTypes = resources.getStringArray(R.array.restrict_type) viewModel.restrict.observe(viewLifecycleOwner) { if (viewModel.restrict.currentVersion > 0) viewModel.onLoadFirst() headerBinding.imgBtnR.text = restrictTypes[viewModel.restrict.value.ordinal] } headerBinding.imgBtnR.setOnClickListener { MaterialDialogs(requireContext()).show { setSingleChoiceItems(restrictTypes, viewModel.restrict.value.ordinal) { dialog, index -> viewModel.restrict.checkUpdate(RESTRICT_TYPE.entries[index]) headerBinding.imgBtnR.text = restrictTypes[index] } } } } } open fun configAdapter(renew: Boolean = true) { if (renew) { picListAdapter.removeAllHeaderView() } else { if (::picListAdapter.isInitialized) { binding.recyclerview.adapter = picListAdapter return } } picListAdapter = filterModel.getAdapter() //TODO: decouple header view picListAdapter.addHeaderView(headerBinding.root) //binding.recyclerview.swapAdapter(picListAdapter, true) binding.recyclerview.adapter = picListAdapter } }
6
null
33
692
d5caf81746e4f16a1af64d45490a358fd19aec1a
13,556
Pix-EzViewer
MIT License
app/src/main/java/com/ncs/o2/Domain/Models/User.kt
arpitmx
647,358,015
false
null
package com.ncs.o2.Domain.Models import com.google.firebase.Timestamp import com.google.firebase.firestore.Exclude import com.ncs.o2.Domain.Utility.Later /* File : Contributor.kt -> com.ncs.o2.Models Description : Model for Contributor Author : <NAME> (VC uname : apple) Link : https://github.com/arpitmx From : Bitpolarity x Noshbae (@Project : O2 Android) Creation : 1:36 am on 05/06/23 Todo > Tasks CLEAN CODE : Tasks BUG FIXES : Tasks FEATURE MUST HAVE : Tasks FUTURE ADDITION : */ @Later("Add name") data class User ( val firebaseID : String? = null , val profileDPUrl : String? = null, val profileIDUrl : String?= null, val post: String? = null, val username : String? = null, val role:Int? = null, val timestamp:Timestamp? =null, val designation:String?= null, val fcmToken: String?= null, @Exclude var isChecked : Boolean = false, )
3
null
2
2
5caa232eda2cd52c89277aec67067728f0d3b8dd
941
Oxygen
MIT License
app/src/main/java/com/leichui/shortviedeo/activity/XuanDizhiActivity.kt
kknet
378,407,063
true
{"Gradle": 5, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 389, "Java Properties": 2, "Proguard": 3, "JSON": 25, "Java": 407, "Kotlin": 80}
package com.leichui.shortviedeo.activity import android.content.Intent import android.support.v7.widget.LinearLayoutManager import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter import com.leichui.shortviedeo.base.BaseActivity import com.leichui.shortviedeo.bean.AddressListBean import com.leichui.shortviedeo.http.OkGoStringCallBack import com.leichui.shortviedeo.mapper.ApiMapper import com.tencent.qcloud.ugckit.module.upload.TCUserMgr import com.tencent.qcloud.xiaoshipin.R import kotlinx.android.synthetic.main.activity_dizhi_guanli.* import npay.npay.yinmengyuan.fragment.adapter.DiZhiGuanLiAdapter class XuanDizhiActivity : BaseActivity() { lateinit var adapter: DiZhiGuanLiAdapter override fun setLayoutId(): Int { return R.layout.activity_dizhi_guanli } override fun startAction() { showLeftBackButton() setTitleCenter("选择地址") initView() add_dizhi.setOnClickListener { var inn = Intent(this, AddAdressActivity::class.java) startActivity(inn) } } private fun initView() { adapter = DiZhiGuanLiAdapter(this) dizhi_recyclerView.adapter = adapter val linearLayoutManager = LinearLayoutManager(this) dizhi_recyclerView.setLayoutManager(linearLayoutManager) } override fun onResume() { super.onResume() getList() } fun getList() { ApiMapper.getMyAddressList(TCUserMgr.getInstance().userToken,object : OkGoStringCallBack<AddressListBean>(this@XuanDizhiActivity, AddressListBean::class.java) { override fun onSuccess2Bean(bean: AddressListBean) { adapter.clear() adapter.addAll(bean.data) adapter.setOnItemClickListener(object : RecyclerArrayAdapter.OnItemClickListener { override fun onItemClick(position: Int) { var intent = Intent() intent.putExtra("name", bean.data[position].name+" "+bean.data[position].tel) intent.putExtra("address", bean.data[position].address_info) intent.putExtra("id", bean.data[position].address_id) setResult(2, intent) finish() //结束当前的activity的生命周期 } }) } }) } }
0
null
1
0
8f8f69b200886d4b6671bcc0b2eb11a5343fd7fd
2,373
VideoChat
Apache License 2.0
src/test/kotlin/com/kalikov/game/SpritesZTest.kt
kalikov
696,277,791
false
{"Kotlin": 392286}
package com.kalikov.game import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals class SpritesZTest { private lateinit var tank: Tank private lateinit var explosion: Explosion private lateinit var bullet: Bullet private lateinit var base: Base private lateinit var points: Points private lateinit var water: Water private lateinit var trees: Trees private lateinit var ice: Ice private lateinit var brickWall: BrickWall private lateinit var steelWall: SteelWall private lateinit var powerUp: PowerUp private lateinit var cursor: Cursor @BeforeEach fun beforeEach() { tank = mockTank() explosion = mockTankExplosion(tank = tank) bullet = tank.createBullet() base = mockBase() points = mockPoints() water = mockWater() trees = mockTrees() ice = mockIce() brickWall = mockBrickWall() steelWall = mockSteelWall() powerUp = mockPowerUp() cursor = mockCursor() } @Test fun `walls should have same z value`() { assertEquals(brickWall.z, steelWall.z) } @Test fun `trees are above walls`() { assertTrue(trees.z > brickWall.z) assertTrue(trees.z > steelWall.z) } @Test fun `water is below tank`() { assertTrue(water.z < tank.z) } @Test fun `tank is above walls`() { assertTrue(tank.z > brickWall.z) assertTrue(tank.z > steelWall.z) } @Test fun `tank is above water`() { assertTrue(tank.z > water.z) } @Test fun `base and walls have the same z value`() { assertEquals(base.z, brickWall.z) assertEquals(base.z, steelWall.z) } @Test fun `tank is above base`() { assertTrue(tank.z > base.z) } @Test fun `tank is below trees`() { assertTrue(tank.z < trees.z) } @Test fun `bullet is below trees`() { assertTrue(bullet.z < trees.z) } @Test fun `bullet is above tank`() { assertTrue(bullet.z > tank.z) } @Test fun `tank is below explosion`() { assertTrue(tank.z < explosion.z) } @Test fun `base is below explosion`() { assertTrue(base.z < explosion.z) } @Test fun `base is below trees`() { assertTrue(base.z < trees.z) } @Test fun `base is above water`() { assertTrue(base.z > water.z) } @Test fun `power-up is above trees`() { assertTrue(powerUp.z > trees.z) } @Test fun `points are above trees`() { assertTrue(points.z > trees.z) } @Test fun `water and ice have the same z value`() { assertEquals(water.z, ice.z) } @Test fun `explosion is above tree`() { assertTrue(explosion.z > trees.z) } @Test fun `cursor is above everything`() { assertTrue(cursor.z > tank.z) assertTrue(cursor.z > explosion.z) assertTrue(cursor.z > bullet.z) assertTrue(cursor.z > base.z) assertTrue(cursor.z > points.z) assertTrue(cursor.z > water.z) assertTrue(cursor.z > trees.z) assertTrue(cursor.z > brickWall.z) assertTrue(cursor.z > steelWall.z) assertTrue(cursor.z > powerUp.z) } }
0
Kotlin
0
0
81abd90ae81286f1118d06540c4a45d9c1c88486
3,400
battle-city
MIT License
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/tasks/TasksOutputsBackup.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.tasks import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileSystemOperations import org.gradle.api.logging.Logger import org.gradle.api.provider.Provider import java.io.File import java.net.URI import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.zip.Deflater import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream internal class TaskOutputsBackup( private val fileSystemOperations: FileSystemOperations, val buildDirectory: DirectoryProperty, val snapshotsDir: Provider<Directory>, /** * Task outputs to back up and restore. * * Note that this could be a subset of all the outputs of a task because there could be task outputs that we don't want to back up and * restore (e.g., if (1) they are too big and (2) they are updated only at the end of the task execution so in a failed task run, they * are usually unchanged and therefore don't need to be restored). */ val outputsToRestore: List<File>, val logger: Logger ) { fun createSnapshot() { // Kotlin JS compilation task declares one file from 'destinationDirectory' output as task `@OutputFile' // property. To avoid snapshot sync collisions, each snapshot output directory has also 'index' as prefix. outputsToRestore.toSortedSet().forEachIndexed { index, outputPath -> if (outputPath.isDirectory && !outputPath.isEmptyDirectory) { val snapshotFile = File(snapshotsDir.get().asFile, index.asSnapshotArchiveName) logger.debug("Packing $outputPath as $snapshotFile to make a backup") compressDirectoryToZip( snapshotFile, outputPath ) } else if (!outputPath.exists()) { logger.debug("Ignoring $outputPath in making a backup as it does not exist") File(snapshotsDir.get().asFile, index.asNotExistsMarkerFile).createNewFile() } else { val snapshotFile = snapshotsDir.map { it.file(index.asSnapshotDirectoryName).asFile } logger.debug("Copying $outputPath as $snapshotFile to make a backup") fileSystemOperations.copy { spec -> spec.from(outputPath) spec.into(snapshotFile) } } } } fun restoreOutputs() { fileSystemOperations.delete { it.delete(outputsToRestore) } outputsToRestore.toSortedSet().forEachIndexed { index, outputPath -> val snapshotDir = snapshotsDir.get().file(index.asSnapshotDirectoryName).asFile if (snapshotDir.isDirectory) { logger.debug("Copying files from $snapshotDir into ${outputPath.parentFile} to restore from backup") fileSystemOperations.copy { spec -> spec.from(snapshotDir) spec.into(outputPath.parentFile) } } else if (snapshotsDir.get().file(index.asNotExistsMarkerFile).asFile.exists()) { // do nothing } else { val snapshotArchive = snapshotsDir.get().file(index.asSnapshotArchiveName).asFile logger.debug("Unpacking $snapshotArchive into $outputPath to restore from backup") if (!snapshotArchive.exists()) { logger.warn( """ |Failed to restore task outputs as snapshot file ${snapshotArchive.absolutePath} does not exist! |On recompilation full rebuild will be performed. """.trimMargin() ) return } uncompressZipIntoDirectory(snapshotArchive, outputPath) } } } fun deleteSnapshot() { fileSystemOperations.delete { it.delete(snapshotsDir) } } /** * Kotlin's compilation in a "fat" project may contain a lot of small files that is slow to copy * So we speeding it up by archiving them into single zip file without compression. Such approach reduces snapshotting * time up to half ot the time needed to copy similar files. */ private fun compressDirectoryToZip( snapshotFile: File, outputPath: File ) { snapshotFile.parentFile.mkdirs() snapshotFile.createNewFile() ZipOutputStream(snapshotFile.outputStream().buffered()).use { zip -> zip.setLevel(Deflater.NO_COMPRESSION) outputPath .walkTopDown() .filter { file -> !file.isDirectory || file.isEmptyDirectory } .forEach { file -> val suffix = if (file.isDirectory) "/" else "" val entry = ZipEntry(file.relativeTo(outputPath).invariantSeparatorsPath + suffix) zip.putNextEntry(entry) if (!file.isDirectory) { file.inputStream().buffered().use { it.copyTo(zip) } } zip.closeEntry() } zip.flush() } } private fun uncompressZipIntoDirectory( snapshotFile: File, outputDirectory: File ) { val outputPath = outputDirectory.toPath() val snapshotUri = URI.create("jar:${snapshotFile.toURI()}") FileSystems.newFileSystem(snapshotUri, emptyMap<String, Any>()).use { zipFs -> zipFs.rootDirectories.forEach { rootDir -> Files.walk(rootDir).use { paths -> paths.forEach { if (Files.isDirectory(it)) { Files.createDirectories(outputPath.resolve(it.normalizedToBeRelative)) } else if (Files.isRegularFile(it)) { Files.copy(it, outputPath.resolve(it.normalizedToBeRelative), StandardCopyOption.REPLACE_EXISTING) } } } } } } private val File.isEmptyDirectory: Boolean get() = !Files.list(toPath()).use { it.findFirst().isPresent } private val Path.normalizedToBeRelative: String get() = if (toString() == "/") "." else toString().removePrefix("/") private val Int.asSnapshotArchiveName: String get() = "$this.zip" private val Int.asNotExistsMarkerFile: String get() = "$this.not-exists" private val Int.asSnapshotDirectoryName: String get() = "$this" }
7
null
5686
46,039
f98451e38169a833f60b87618db4602133e02cf2
6,917
kotlin
Apache License 2.0
app/src/main/java/com/digitalinclined/edugate/ui/fragments/mainactivity/PDFWebViewFragment.kt
thisisvd
447,564,444
false
{"Kotlin": 360695}
package com.digitalinclined.edugate.ui.fragments.mainactivity import android.os.Bundle import android.util.Base64 import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.digitalinclined.edugate.R import com.digitalinclined.edugate.constants.Constants import com.digitalinclined.edugate.data.viewmodel.LocalViewModel import com.digitalinclined.edugate.databinding.FragmentPDFWebViewBinding import com.digitalinclined.edugate.ui.fragments.MainActivity import com.google.android.material.snackbar.Snackbar class PDFWebViewFragment : Fragment() { // TAG private val TAG = "PDFWebViewFragment" // view binding private var _binding: FragmentPDFWebViewBinding? = null private val binding get() = _binding!! // view models private val viewModel: LocalViewModel by viewModels() // args private val args: PDFWebViewFragmentArgs by navArgs() // toggle button private lateinit var toggle: ActionBarDrawerToggle override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentPDFWebViewBinding.inflate(inflater, container, false) // change the title bar (activity as MainActivity).findViewById<TextView>(R.id.toolbarTitle).text = "Pdf Viewer" toggle = (activity as MainActivity).toggle toggle.isDrawerIndicatorEnabled = false val drawable = requireActivity().getDrawable(R.drawable.ic_baseline_arrow_back_ios_new_24) toggle.setHomeAsUpIndicator(drawable) Constants.IS_BACK_TOOLBAR_BTN_ACTIVE = true return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { if (args.pdfLink.isNotEmpty()) { // loading a pdf view viewModel.getSelectedPdf(args.pdfLink).observe(viewLifecycleOwner) { if (it != null) { var getBytes = Base64.decode(it.fileData, Base64.NO_WRAP) Log.d(TAG, "$it : $getBytes") pdfView.fromBytes(getBytes).load() } else { pdfView.fromAsset("machine_learning.pdf").load() } } } else { Snackbar.make(binding.root, "Failed to load pdf!", Snackbar.LENGTH_SHORT).show() pdfProgressBar.visibility = View.GONE } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
5dc3146cadc4b6831cee6847390a2902a2348ef0
2,903
Eduvae-plus
Apache License 2.0
app/src/main/java/com/digitalinclined/edugate/ui/fragments/mainactivity/PDFWebViewFragment.kt
thisisvd
447,564,444
false
{"Kotlin": 360695}
package com.digitalinclined.edugate.ui.fragments.mainactivity import android.os.Bundle import android.util.Base64 import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.digitalinclined.edugate.R import com.digitalinclined.edugate.constants.Constants import com.digitalinclined.edugate.data.viewmodel.LocalViewModel import com.digitalinclined.edugate.databinding.FragmentPDFWebViewBinding import com.digitalinclined.edugate.ui.fragments.MainActivity import com.google.android.material.snackbar.Snackbar class PDFWebViewFragment : Fragment() { // TAG private val TAG = "PDFWebViewFragment" // view binding private var _binding: FragmentPDFWebViewBinding? = null private val binding get() = _binding!! // view models private val viewModel: LocalViewModel by viewModels() // args private val args: PDFWebViewFragmentArgs by navArgs() // toggle button private lateinit var toggle: ActionBarDrawerToggle override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentPDFWebViewBinding.inflate(inflater, container, false) // change the title bar (activity as MainActivity).findViewById<TextView>(R.id.toolbarTitle).text = "Pdf Viewer" toggle = (activity as MainActivity).toggle toggle.isDrawerIndicatorEnabled = false val drawable = requireActivity().getDrawable(R.drawable.ic_baseline_arrow_back_ios_new_24) toggle.setHomeAsUpIndicator(drawable) Constants.IS_BACK_TOOLBAR_BTN_ACTIVE = true return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { if (args.pdfLink.isNotEmpty()) { // loading a pdf view viewModel.getSelectedPdf(args.pdfLink).observe(viewLifecycleOwner) { if (it != null) { var getBytes = Base64.decode(it.fileData, Base64.NO_WRAP) Log.d(TAG, "$it : $getBytes") pdfView.fromBytes(getBytes).load() } else { pdfView.fromAsset("machine_learning.pdf").load() } } } else { Snackbar.make(binding.root, "Failed to load pdf!", Snackbar.LENGTH_SHORT).show() pdfProgressBar.visibility = View.GONE } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
5dc3146cadc4b6831cee6847390a2902a2348ef0
2,903
Eduvae-plus
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/utbetalingstidslinje/ArbeidsgiverperiodesubsumsjonTest.kt
navikt
193,907,367
false
{"Kotlin": 6542815, "PLpgSQL": 2738, "Dockerfile": 168}
package no.nav.helse.utbetalingstidslinje import java.time.LocalDate import java.util.UUID import no.nav.helse.Grunnbeløp import no.nav.helse.etterlevelse.Paragraf import no.nav.helse.etterlevelse.Subsumsjon import no.nav.helse.etterlevelse.Subsumsjon.Utfall import no.nav.helse.etterlevelse.Subsumsjonslogg import no.nav.helse.etterlevelse.annetLedd import no.nav.helse.etterlevelse.bokstavA import no.nav.helse.etterlevelse.fjerdeLedd import no.nav.helse.etterlevelse.folketrygdloven import no.nav.helse.etterlevelse.førsteLedd import no.nav.helse.etterlevelse.paragraf import no.nav.helse.etterlevelse.tredjeLedd import no.nav.helse.hendelser.Periode import no.nav.helse.hendelser.Periode.Companion.grupperSammenhengendePerioder import no.nav.helse.hendelser.til import no.nav.helse.januar import no.nav.helse.nesteDag import no.nav.helse.person.inntekt.Refusjonsopplysning import no.nav.helse.person.inntekt.Refusjonsopplysning.Refusjonsopplysninger.Companion.refusjonsopplysninger import no.nav.helse.sykdomstidslinje.Sykdomstidslinje import no.nav.helse.testhelpers.A import no.nav.helse.testhelpers.S import no.nav.helse.testhelpers.opphold import no.nav.helse.testhelpers.resetSeed import no.nav.helse.økonomi.Inntekt.Companion.månedlig import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class ArbeidsgiverperiodesubsumsjonTest { @Test fun ingenting() { undersøke(1.A + 29.opphold + 1.A) assertEquals(31, observatør.dager) assertEquals(23, observatør.arbeidsdager) assertEquals(8, observatør.fridager) assertEquals(4, jurist.subsumsjoner) assertEquals(8, jurist.`§ 8-17 ledd 2`) } @Test fun kurant() { undersøke(31.S) assertEquals(31, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(15, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(1, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(4, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) } @Test fun spredt() { undersøke(4.S + 1.A + 4.S + 1.A + 4.S + 10.A + 11.S) assertEquals(35, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(7, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(1, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(2, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) assertEquals(3, jurist.`§ 8-19 tredje ledd - beregning`) } @Test fun `spredt utbetalingsperiode`() { undersøke(17.S + 10.A + 4.S + 10.A + 4.S) assertEquals(45, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(9, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(1, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(2, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) assertEquals(0, jurist.`§ 8-19 tredje ledd - beregning`) } @Test fun `ny arbeidsgiverperiode etter fullført`() { undersøke(16.S + 32.A + 16.S) assertEquals(64, observatør.dager) assertEquals(32, observatør.arbeidsgiverperiodedager) assertEquals(0, observatør.utbetalingsdager) assertEquals(9, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(32, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(0, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(0, jurist.`§ 8-11 første ledd`) assertEquals(32, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(2, jurist.`§ 8-19 første ledd - beregning`) assertEquals(0, jurist.`§ 8-19 tredje ledd - beregning`) assertEquals(1, jurist.`§ 8-19 fjerde ledd - beregning`) } @Test fun `ny arbeidsgiverperiode etter halvferdig`() { undersøke(8.S + 32.A + 16.S) assertEquals(56, observatør.dager) assertEquals(24, observatør.arbeidsgiverperiodedager) assertEquals(0, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(24, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(0, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(0, jurist.`§ 8-11 første ledd`) assertEquals(24, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) assertEquals(0, jurist.`§ 8-19 tredje ledd - beregning`) assertEquals(0, jurist.`§ 8-19 fjerde ledd - beregning`) } @Test fun `siste dag i arbeidsgiverperioden er også første dag etter opphold i arbeidsgiverperioden`() { undersøke(15.S + 1.A + 2.S) assertEquals(18, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(1, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(1, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(0, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) assertEquals(1, jurist.`§ 8-19 tredje ledd - beregning`) } @Test fun `utbetaling kun i helg`() { undersøke(3.opphold + 18.S) assertEquals(18, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(2, observatør.utbetalingsdager) assertEquals(6, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(0, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(2, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) } @Test fun infotrygd() { undersøke(31.S, infotrygdBetalteDager = listOf(1.januar til 10.januar)) assertEquals(31, observatør.dager) assertEquals(0, observatør.arbeidsgiverperiodedager) assertEquals(31, observatør.utbetalingsdager) assertEquals(4, jurist.subsumsjoner) assertEquals(8, jurist.`§ 8-11 første ledd`) assertEquals(0, jurist.`§ 8-19 første ledd - beregning`) assertEquals(0, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(0, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) } @Test fun `infotrygd etter arbeidsgiverperiode`() { undersøke(31.S, infotrygdBetalteDager = listOf(17.januar til 20.januar)) assertEquals(31, observatør.dager) assertEquals(16, observatør.arbeidsgiverperiodedager) assertEquals(15, observatør.utbetalingsdager) assertEquals(7, jurist.subsumsjoner) assertEquals(0, jurist.`§ 8-17 ledd 2`) assertEquals(16, jurist.`§ 8-17 første ledd bokstav a - ikke oppfylt`) assertEquals(1, jurist.`§ 8-17 første ledd bokstav a - oppfylt`) assertEquals(4, jurist.`§ 8-11 første ledd`) assertEquals(16, jurist.`§ 8-19 andre ledd - beregning`) assertEquals(1, jurist.`§ 8-19 første ledd - beregning`) } private lateinit var jurist: Subsumsjonobservatør private lateinit var teller: Arbeidsgiverperiodeteller private lateinit var observatør: Dagobservatør @BeforeEach fun setup() { resetSeed() jurist = Subsumsjonobservatør() teller = Arbeidsgiverperiodeteller.NormalArbeidstaker } private fun undersøke(tidslinje: Sykdomstidslinje, infotrygdBetalteDager: List<Periode> = emptyList()) { val arbeidsgiverperiodeberegner = Arbeidsgiverperiodeberegner(teller) val arbeidsgiverperioder = arbeidsgiverperiodeberegner.resultat(tidslinje, infotrygdBetalteDager) arbeidsgiverperioder.forEach { it.subsummering(jurist, tidslinje) } val builder = UtbetalingstidslinjeBuilderVedtaksperiode( faktaavklarteInntekter = ArbeidsgiverFaktaavklartInntekt( skjæringstidspunkt = 1.januar, `6G` = Grunnbeløp.`6G`.beløp(1.januar), fastsattÅrsinntekt = 31000.månedlig, gjelder = 1.januar til LocalDate.MAX, refusjonsopplysninger = Refusjonsopplysning(UUID.randomUUID(), 1.januar, null, 31000.månedlig).refusjonsopplysninger ), regler = ArbeidsgiverRegler.Companion.NormalArbeidstaker, subsumsjonslogg = Subsumsjonslogg.EmptyLog, arbeidsgiverperiode = arbeidsgiverperioder.flatMap { it.arbeidsgiverperiode }.grupperSammenhengendePerioder() ) val utbetalingstidslinje = builder.result(tidslinje) observatør = Dagobservatør(utbetalingstidslinje) val subsummering = Utbetalingstidslinjesubsumsjon(jurist, tidslinje, utbetalingstidslinje) subsummering.subsummer(tidslinje.periode()!!, ArbeidsgiverRegler.Companion.NormalArbeidstaker) } private class Subsumsjonobservatør : Subsumsjonslogg { var subsumsjoner = 0 var `§ 8-17 første ledd bokstav a - ikke oppfylt` = 0 var `§ 8-17 første ledd bokstav a - oppfylt` = 0 var `§ 8-17 ledd 2` = 0 var `§ 8-11 første ledd` = 0 var `§ 8-19 første ledd - beregning`= 0 var `§ 8-19 andre ledd - beregning` = 0 var `§ 8-19 tredje ledd - beregning` = 0 var `§ 8-19 fjerde ledd - beregning` = 0 private val sykepengerFraTrygden = folketrygdloven.paragraf(Paragraf.PARAGRAF_8_17) private val beregningAvArbeidsgiverperiode = folketrygdloven.paragraf(Paragraf.PARAGRAF_8_19) private fun ClosedRange<LocalDate>.antallDager() = start.datesUntil(endInclusive.nesteDag).count().toInt() private fun Collection<ClosedRange<LocalDate>>.antallDager() = sumOf { it.antallDager() } private val Subsumsjon.perioder get() = output["perioder"] ?.let { it as List<*> } ?.map { it as Map<*, *> } ?.mapNotNull { val fom = it["fom"] as? LocalDate val tom = it["tom"] as? LocalDate if (fom != null && tom != null) fom..tom else null } ?: emptyList() override fun logg(subsumsjon: Subsumsjon) { when { subsumsjon.er(folketrygdloven.paragraf(Paragraf.PARAGRAF_8_11).førsteLedd) -> { subsumsjoner += 1 `§ 8-11 første ledd` += subsumsjon.perioder.antallDager() } subsumsjon.er(sykepengerFraTrygden.førsteLedd.bokstavA) -> { subsumsjoner += 1 if (subsumsjon.utfall == Utfall.VILKAR_OPPFYLT) `§ 8-17 første ledd bokstav a - oppfylt` += subsumsjon.perioder.antallDager() else `§ 8-17 første ledd bokstav a - ikke oppfylt` += subsumsjon.perioder.antallDager() } subsumsjon.er(sykepengerFraTrygden.annetLedd) -> { subsumsjoner += 1 `§ 8-17 ledd 2` += subsumsjon.perioder.antallDager() } subsumsjon.er(beregningAvArbeidsgiverperiode.førsteLedd) -> { subsumsjoner += 1 `§ 8-19 første ledd - beregning` += 1 } subsumsjon.er(beregningAvArbeidsgiverperiode.annetLedd) -> { subsumsjoner += 1 `§ 8-19 andre ledd - beregning` += subsumsjon.perioder.antallDager() } subsumsjon.er(beregningAvArbeidsgiverperiode.tredjeLedd) -> { subsumsjoner += 1 `§ 8-19 tredje ledd - beregning` += subsumsjon.perioder.antallDager() } subsumsjon.er(beregningAvArbeidsgiverperiode.fjerdeLedd) -> { subsumsjoner += 1 `§ 8-19 fjerde ledd - beregning` += 1 } } } } private class Dagobservatør(utbetalingstidslinje: Utbetalingstidslinje) { val dager get() = fridager + arbeidsdager + arbeidsgiverperiodedager + utbetalingsdager + foreldetdager + avvistdager var fridager = 0 var arbeidsdager = 0 var arbeidsgiverperiodedager = 0 var arbeidsgiverperiodedagerNavAnsvar = 0 var utbetalingsdager = 0 var foreldetdager = 0 var avvistdager = 0 init { utbetalingstidslinje.forEach { dag -> when (dag) { is Utbetalingsdag.Arbeidsdag -> arbeidsdager += 1 is Utbetalingsdag.ArbeidsgiverperiodeDag -> arbeidsgiverperiodedager += 1 is Utbetalingsdag.ArbeidsgiverperiodedagNav -> arbeidsgiverperiodedagerNavAnsvar += 1 is Utbetalingsdag.AvvistDag -> avvistdager += 1 is Utbetalingsdag.ForeldetDag -> foreldetdager += 1 is Utbetalingsdag.Fridag -> fridager += 1 is Utbetalingsdag.NavDag -> utbetalingsdager += 1 is Utbetalingsdag.NavHelgDag -> utbetalingsdager += 1 is Utbetalingsdag.UkjentDag -> {} } } } } }
2
Kotlin
7
3
fc9b0c7dc3dd3a755f3cc191f35f1c510e62a2cd
14,388
helse-spleis
MIT License
demo/src/main/java/com/iflytek/cyber/evs/demo/utils/PrefUtil.kt
iFLYOS-OPEN
206,514,105
false
null
package com.iflytek.cyber.evs.demo.utils import android.content.Context object PrefUtil { private val PREF_NAME = "com.iflytek.cyber.evs.demo.pref" fun setToPref(context : Context, key : String, value : String) { context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).edit().run { putString(key, value) apply() } } fun getFromPref(context: Context, key : String) : String { val pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) if (pref.contains(key)) { return pref.getString(key, null) } return "" } }
0
null
5
3
1e72910bc614e33b4a4d05222625dcd37151a148
693
SDK-EVS-Android
Apache License 2.0
src/main/kotlin/com/example/gungjeonjegwa/domain/order/exception/AddressNotFoundException.kt
gungjeonjegwa
579,803,041
false
null
package com.example.gungjeonjegwa.domain.order.exception import com.example.gungjeonjegwa.global.exception.ErrorCode import com.example.gungjeonjegwa.global.exception.exceptions.BasicException class AddressNotFoundException : BasicException(ErrorCode.ADDRESS_NOT_FOUND) { }
0
Kotlin
0
0
30a77ac8c8ec594a6d1267ae36df365f1622f250
275
GGJG-Backend
MIT License
src/main/kotlin/bpm/common/property/Property.kt
sincyn
852,470,964
false
{"Kotlin": 1211965, "GLSL": 2785}
package bpm.common.property import bpm.common.network.NetUtils import org.joml.* import java.util.* import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.starProjectedType /** * Casts the value type of this property to the specified type [T]. * * @return A new property with the value type casted to [T]. * * @throws ClassCastException If the value type cannot be casted to [T]. * * @param T The desired type to cast to. */ inline fun <reified T : Property<*>> Property<*>.cast(): T = this as T inline infix fun <reified T : Property<*>> Property<*>.castOr(crossinline block: () -> T): T = this as? T ?: block() /** * Retrieves the property with the specified name. * * @return The property object with the specified name. */ interface Property<T : Any> { /** * Retrieves the value of type T. * * @return the value of type T */ fun get(): T /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ val bytes: kotlin.Int /** * Sets the value of the property. * * @param value the new value for the property * @return the updated Property object */ fun set(value: T) /** * Executes the `get` function and returns its result. * * @return The result of executing the `get` function. */ operator fun invoke() = get() fun copy(): Property<T> /** * Represents a null property which holds no value. */ object Null : Property<Unit> { /** * Retrieves the data. */ override fun get() = Unit /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 0 override fun copy(): Property<Unit> = this /** * Sets the value of the property. * * @param value the new value to be set * @return the updated Property instance */ override fun set(value: Unit) = Unit override fun toString(): kotlin.String = "NullProperty" } /** * Represents a property that holds an integer value. * * This class inherits from the `PrimitiveProperty` class to provide common functionality for * working with primitive properties. * * @param defaultValue The default value of the property (default is 0). */ class Int(defaultValue: kotlin.Int = 0) : PropertyLiteral<kotlin.Int>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 override fun copy(): Property<kotlin.Int> = Int(this()) } /** * Represents a property that holds a value of type Double. * * This class is a subclass of [PropertyLiteral] and provides additional methods and functionality specific to Double values. * * @param defaultValue The default value of the property. */ class Double(defaultValue: kotlin.Double = 0.0) : PropertyLiteral<kotlin.Double>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 8 override fun copy(): Property<kotlin.Double> = Double(this()) } /** * Represents a property that holds a string value. * * This class extends the `PrimitiveProperty` class to provide additional functionality for string values. * * @param defaultValue The default value for the property. Default value is an empty string `""`. * * @see PropertyLiteral * */ class String(defaultValue: kotlin.String = "") : PropertyLiteral<kotlin.String>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 + get().length override fun copy(): Property<kotlin.String> = String(this()) } /** * Represents a UUID property literal. * * @property defaultValue The default value for the UUID property. */ class UUID(defaultValue: java.util.UUID = NetUtils.DefaultUUID) : PropertyLiteral<java.util.UUID>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 16 override fun copy(): Property<java.util.UUID> = UUID(this()) } /** * Represents a Boolean property. * * This class extends the `PrimitiveProperty` class, which provides the basic functionality of a property. * The `BooleanProperty` class specifically handles properties with boolean values. * * @param defaultValue The default value of the property. Defaults to `false` if not specified. * * @constructor Creates a new BooleanProperty object with the specified default value. */ class Boolean(defaultValue: kotlin.Boolean = false) : PropertyLiteral<kotlin.Boolean>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 1 override fun copy(): Property<kotlin.Boolean> = Boolean(this()) } /** * Represents a property with a long value. * * @param defaultValue The default value of the property. */ class Long(defaultValue: kotlin.Long = 0L) : PropertyLiteral<kotlin.Long>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 8 override fun copy(): Property<kotlin.Long> = Long(this()) } /** * A property that stores a float value. * * @param defaultValue The default value of the property. Defaults to 0.0f. */ class Float(defaultValue: kotlin.Float = 0.0f) : PropertyLiteral<kotlin.Float>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 override fun copy(): Property<kotlin.Float> = Float(this()) } /** * Represents a property that holds a value of type Short. * * @property defaultValue The default value of the property. * * @constructor Creates a ShortProperty with the specified default value. * * @param defaultValue The default value of the property. */ class Short(defaultValue: kotlin.Short = 0) : PropertyLiteral<kotlin.Short>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 2 override fun copy(): Property<kotlin.Short> = Short(this()) } /** * Represents a property that holds a value of type Byte. * * This class extends the `PrimitiveProperty` class and encapsulates a Byte value. * It provides methods to get and set the value, as well as methods to observe changes to the value. * * @param defaultValue The default value of the property. Defaults to 0 if not specified. */ class Byte(defaultValue: kotlin.Byte = 0) : PropertyLiteral<kotlin.Byte>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 1 override fun copy(): Property<kotlin.Byte> = Byte(this()) } /** * Represents a character property that can hold a single character value. * * @param defaultValue The default character value for the property. */ class Char(defaultValue: kotlin.Char = ' ') : PropertyLiteral<kotlin.Char>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 1 override fun copy(): Property<kotlin.Char> = Char(this()) } /** * Represents a color property. * @property defaultValue The default value of the color property. * @constructor Creates a color property with the given default value. * @param defaultValue The default value of the color property. Defaults to Vector4i(40, 20, 69, 255). */ class Vec2f(defaultValue: Vector2f) : PropertyLiteral<Vector2f>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 8 override fun copy(): Property<Vector2f> = Vec2f(this()) } /** * A class representing a 3-dimensional vector of floats. * * @param defaultValue The default value of the vector. */ class Vec3f(defaultValue: Vector3f) : PropertyLiteral<Vector3f>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 12 override fun copy(): Property<Vector3f> = Vec3f(this()) } /** * Represents a 4-component vector in 3D space. * * This class extends the [PropertyLiteral] class and provides specialized methods and properties for working with 4D vectors. * * @param defaultValue The default value for the vector. */ class Vec4f(defaultValue: Vector4f) : PropertyLiteral<Vector4f>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 16 override fun copy(): Property<Vector4f> = Vec4f(this()) } /** * Represents a 2D vector of integers. * * @property defaultValue The default value of the vector. * @constructor Creates a Vec2i object with the specified default value. */ class Vec2i(defaultValue: Vector2i) : PropertyLiteral<Vector2i>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 8 override fun copy(): Property<Vector2i> = Vec2i(this()) } /** * Represents a 3D vector of integers. * * This class extends the `PropertyLiteral` class and provides additional functionality for 3D integer vectors. * It holds three integer values representing the x, y, and z components of the vector. * * @constructor Creates a `Vec3i` instance with the specified default value. * @param defaultValue The default value for the vector. */ class Vec3i(defaultValue: Vector3i) : PropertyLiteral<Vector3i>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 12 override fun copy(): Property<Vector3i> = Vec3i(this()) } /** * Represents a 4-dimensional integer vector. * * @param defaultValue The default value of the vector. */ class Vec4i(defaultValue: Vector4i) : PropertyLiteral<Vector4i>(defaultValue) { /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 16 override fun copy(): Property<Vector4i> = Vec4i(this()) } class Class(val value: java.lang.Class<*>) : Property<java.lang.Class<*>> { override fun get(): java.lang.Class<*> = value /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 + get().javaClass.name.length override fun copy(): Property<java.lang.Class<*>> = Class(this()) override fun set(value: java.lang.Class<*>) { throw UnsupportedOperationException("Cannot set value of ClassProperty") } override fun toString(): kotlin.String { return "ClassProperty(${get().simpleName})" } } /** * Represents a class that stores a collection of properties. * * @property properties A mutable map that holds the properties. */ open class Object(private val properties: ConcurrentHashMap<kotlin.String, Property<*>> = ConcurrentHashMap()) : PropertyMap { override fun get() = properties /** * Finds a property by it's qualified name. * * This can include numbers for list indices, e.g. `list.0.test`. */ override fun find(name: kotlin.String): Property<*>? { if (!name.contains('.')) return get()[name] val parts = name.split('.') var current: Property<*>? = get()[parts[0]] for (i in 1 until parts.size) { if (current is List) { current = current.getTyped<PropertyList>(parts[i].toIntOrNull() ?: 0) continue } if (current !is Object) return null current = current.getTyped<Object>(parts[i]) } return current } /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 + get().values.sumOf { it.bytes } + get().keys.sumOf { it.length + 4 } override fun copy() = Object(ConcurrentHashMap(this().mapValues { it.value.copy() })) private fun takeFirstPart(name: kotlin.String): kotlin.String { val index = name.indexOf('.') return if (index == -1) name else name.substring(0, index) } override fun equals(other: Any?): kotlin.Boolean { if (this === other) return true if (other !is Object) return false if (properties != other.properties) return false return true } override fun hashCode(): kotlin.Int { return properties.hashCode() } companion object { operator fun invoke(apply: PropertyMap.() -> Unit): Object { val obj = Object() obj.apply() return obj } } } /** * Represents a list property that holds a mutable list of properties. * Implements the PropertyList interface. * * @property properties The mutable list of properties. */ class List(private val properties: MutableList<Property<*>> = mutableListOf()) : PropertyList { override fun get(): kotlin.collections.List<Property<*>> = properties /** * This variable represents the number of bytes. * * @property bytes The number of bytes. */ override val bytes: kotlin.Int = 4 + get().sumOf { it.bytes } override fun copy() = List(this().map { it.copy() }.toMutableList()) override fun toString(): kotlin.String = "ListProperty(${get()})" override fun equals(other: Any?): kotlin.Boolean { if (this === other) return true if (other !is List) return false if (properties != other.properties) return false return true } override fun hashCode(): kotlin.Int { return properties.hashCode() } companion object { operator fun invoke(apply: PropertyList.() -> Unit): List { val list = List() list.apply() return list } } } companion object { /** * Creates and returns a Property object based on the given value. * * @param value the value to create the Property object from. * @return a Property object representing the given value. * @throws IllegalArgumentException if the value's type cannot be converted to a Property object. */ fun of(value: Any): Property<*> { return when (value) { is kotlin.Int -> Int(value) is kotlin.Double -> Double(value) is kotlin.String -> String(value) is kotlin.Boolean -> Boolean(value) is kotlin.Long -> Long(value) is kotlin.Float -> Float(value) is kotlin.Short -> Short(value) is kotlin.Byte -> Byte(value) is kotlin.Char -> Char(value) is java.util.UUID -> UUID(value) is java.lang.Class<*> -> Class(value) is Map<*, *> -> { val map = value as Map<kotlin.String, *> Object { map.forEach { (key, value) -> this[key] = of(value!!) } } } is MutableList<*> -> List(value as MutableList<Property<*>>) is kotlin.collections.List<*> -> List(value.toMutableList() as MutableList<Property<*>>) else -> ofVector(value) } } private fun ofVector(value: Any): Property<*> = when (value) { is Vector2f -> Vec2f(value) is Vector3f -> Vec3f(value) is Vector4f -> Vec4f(value) is Vector2i -> Vec2i(value) is Vector3i -> Vec3i(value) is Vector4i -> Vec4i(value) else -> throw IllegalArgumentException("Cannot create property of type ${value::class.simpleName}") } } } /** * An interface representing an object holder that holds a set of properties. */ interface PropertySupplier { val properties: PropertyMap } inline fun <reified T : PropertySupplier> configured(crossinline apply: PropertyMap.() -> Unit): T { val type = T::class //Find a constructor that only takes a PropertyMap val propertiesConstructor = type.constructors.find { it.parameters.size == 1 && (it.parameters[0].type == PropertyMap::class || it.parameters[0].type.isSubtypeOf( PropertyMap::class.starProjectedType )) } ?: throw IllegalArgumentException("Cannot find constructor for type $type that takes a PropertyMap") val obj = propertiesConstructor.call(Property.Object { apply() }) return obj }
5
Kotlin
1
0
caf36397c9aa72a21e2b19f6051d76db66c9f77c
18,966
bpm.core
MIT License
app/src/main/java/cn/sskbskdrin/record/mesh/Mesh.kt
sskbskdrin
179,249,401
false
{"C++": 3560091, "Java": 257858, "Kotlin": 50162, "C": 38126, "CMake": 4860}
package cn.sskbskdrin.record.mesh import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.nio.ShortBuffer import javax.microedition.khronos.opengles.GL10 /** * Created by ex-keayuan001 on 2018/11/30. * * @author ex-keayuan001 */ public open class Mesh { // Our vertex buffer. private var verticesBuffer: FloatBuffer? = null // Our index buffer. private var indicesBuffer: ShortBuffer? = null // The number of indices. private var numOfIndices = -1 // Flat Color private val rgba = floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f) // Smooth Colors private var colorBuffer: FloatBuffer? = null // Translate params. var x = 0f var y = 0f var z = -0f // Rotate params. var rx = 0f var ry = 0f var rz = 0f open fun draw(gl: GL10) { // gl.glPushMatrix() // Counter-clockwise winding. gl.glFrontFace(GL10.GL_CCW) // Enable face culling. gl.glEnable(GL10.GL_CULL_FACE) // What faces to remove with the face culling. gl.glCullFace(GL10.GL_BACK) // Enabled the vertices buffer for writing and //to be used during // rendering. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY) // Specifies the location and data format //of an array of vertex // coordinates to use when rendering. gl.glVertexPointer(3, GL10.GL_FLOAT, 0, verticesBuffer) // Set flat color gl.glColor4f(rgba[0], rgba[1], rgba[2], rgba[3]) // Smooth color if (colorBuffer != null) { // Enable the color array buffer to be //used during rendering. gl.glEnableClientState(GL10.GL_COLOR_ARRAY) gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer) } gl.glTranslatef(x, y, z) gl.glRotatef(rx, 1f, 0f, 0f) gl.glRotatef(ry, 0f, 1f, 0f) gl.glRotatef(rz, 0f, 0f, 1f) // Point out the where the color buffer is. gl.glDrawElements(GL10.GL_TRIANGLES, numOfIndices, GL10.GL_UNSIGNED_SHORT, indicesBuffer) // Disable the vertices buffer. if (colorBuffer != null) { gl.glDisableClientState(GL10.GL_COLOR_ARRAY) } gl.glDisableClientState(GL10.GL_VERTEX_ARRAY) // Disable face culling. gl.glDisable(GL10.GL_CULL_FACE) // gl.glPopMatrix() } public fun setVertices(vertices: FloatArray) { // a float is 4 bytes, therefore //we multiply the number if // vertices with 4. val vbb = ByteBuffer.allocateDirect(vertices.size * 4) vbb.order(ByteOrder.nativeOrder()) verticesBuffer = vbb.asFloatBuffer() verticesBuffer!!.put(vertices) verticesBuffer!!.position(0) } public fun setIndices(indices: ShortArray) { // short is 2 bytes, therefore we multiply //the number if // vertices with 2. val ibb = ByteBuffer.allocateDirect(indices.size * 2) ibb.order(ByteOrder.nativeOrder()) indicesBuffer = ibb.asShortBuffer() indicesBuffer!!.put(indices) indicesBuffer!!.position(0) numOfIndices = indices.size } public fun setColor(red: Float, green: Float, blue: Float, alpha: Float) { // Setting the flat color. rgba[0] = red rgba[1] = green rgba[2] = blue rgba[3] = alpha } public fun setColors(colors: FloatArray) { // float has 4 bytes. val cbb = ByteBuffer.allocateDirect(colors.size * 4) cbb.order(ByteOrder.nativeOrder()) colorBuffer = cbb.asFloatBuffer() colorBuffer!!.put(colors) colorBuffer!!.position(0) } } class Plane(width: Float = 1f, height: Float = 1f, widthSegments: Int = 1, heightSegments: Int = 1) : Mesh() { init { val vertices = FloatArray((widthSegments + 1) * (heightSegments + 1) * 3) val indices = ShortArray((widthSegments + 1) * (heightSegments + 1) * 6) val xOffset = width / -2 val yOffset = height / -2 val xWidth = width / widthSegments val yHeight = height / heightSegments var currentVertex = 0 var currentIndex = 0 val w = (widthSegments + 1).toShort() for (y in 0 until heightSegments + 1) { for (x in 0 until widthSegments + 1) { vertices[currentVertex] = xOffset + x * xWidth vertices[currentVertex + 1] = yOffset + y * yHeight vertices[currentVertex + 2] = 0f currentVertex += 3 val n = y * (widthSegments + 1) + x if (y < heightSegments && x < widthSegments) { // Face one indices[currentIndex] = n.toShort() indices[currentIndex + 1] = (n + 1).toShort() indices[currentIndex + 2] = (n + w).toShort() // Face two indices[currentIndex + 3] = (n + 1).toShort() indices[currentIndex + 4] = (n + 1 + w.toInt()).toShort() indices[currentIndex + 5] = (n + 1 + w.toInt() - 1).toShort() currentIndex += 6 } } } setIndices(indices) setVertices(vertices) } } class Cube(var width: Float, var height: Float, var depth: Float) : Mesh() { val group = MeshGroup() init { width /= 2f height /= 2f depth /= 2f val vertices = floatArrayOf(-width, -height, -depth, // 0 width, -height, -depth, // 1 width, height, -depth, // 2 -width, height, -depth, // 3 -width, -height, depth, // 4 width, -height, depth, // 5 width, height, depth, // 6 -width, height, depth)// 7 val indices = shortArrayOf(0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2) setIndices(indices) setVertices(vertices) group.add(Square(0.5f)) group.get(0).z = 0.25f group.get(0).x = -0.175f group.get(0).ry = -45f group.get(0).rx = 30f group.get(0).setColor(1f, 0f, 0f, 1f) group.add(Square(0.5f)) group.get(1).z = 0.25f group.get(1).x = 0.175f group.get(1).ry = 45f group.get(1).rx = 30f group.get(1).setColor(0f, 1f, 0f, 1f) // group.add(Square(0.5f)) } override fun draw(gl: GL10) { group.draw(gl) } } class Square(var width: Float) : Mesh() { init { // val vertices = floatArrayOf( // 0.5f, 0.28125f, -0.5f, // 0, Top Left // -0.5f, 0.28125f, -0.5f, // 1, Bottom Left // -0.5f, -0.28125f, -0.5f, // 2, Bottom Right // 0.5f, -0.28125f, -0.5f, // 3, Top Right // 0.5f, 0.28125f, 0.5f, // -0.5f, 0.28125f, 0.5f, // -0.5f, -0.28125f, 0.5f, // 0.5f, -0.28125f, 0.5f // ) // val indices = shortArrayOf( // 0, 1, 2, // 0, 2, 3, // // 0, 5, 4, // 0, 1, 5, // // 0, 4, 7, // 0, 7, 3, // // 6, 5, 1, // 6, 1, 2, // // 6, 7, 2, // 6, 3, 2, // // 6, 7, 4, // 6, 4, 5 // ) width /= 2 val height = width * 0.5625f val vertices = floatArrayOf( -width, height, 0f, -width, -height, 0f, width, -height, 0f, width, height, 0f ) val indices = shortArrayOf(0, 1, 2, 0, 2, 3) setIndices(indices) setVertices(vertices) } } class MeshGroup : Mesh() { private val child = ArrayList<Mesh>() init { setVertices(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)) setIndices(shortArrayOf(0, 1, 2)) } fun contains(element: Mesh): Boolean { return child.contains(element) } fun get(index: Int): Mesh { return child[index] } fun indexOf(element: Mesh): Int { return child.indexOf(element) } fun isEmpty(): Boolean { return child.isEmpty() } fun lastIndexOf(element: Mesh): Int { return child.lastIndexOf(element) } fun add(element: Mesh): Boolean { return child.add(element) } fun add(index: Int, element: Mesh) { child.add(index, element) } fun addAll(index: Int, elements: Collection<Mesh>): Boolean { return child.addAll(index, elements) } fun addAll(elements: Collection<Mesh>): Boolean { return child.addAll(elements) } fun clear() { child.clear() } fun remove(element: Mesh): Boolean { return child.remove(element) } override fun draw(gl: GL10) { for (mesh in child) { mesh.draw(gl) } super.draw(gl) } }
0
C++
1
0
612219433faeec74a36c08c9f8f61d3e4078da20
9,161
AudioVideo
Apache License 2.0
app/src/test/java/com/sale/hive/content/ProductContent.kt
kelvinkioko
609,795,163
false
null
package com.sale.hive.content import com.sale.hive.content.VotesContent.Content.fridgeVoteOneDTO import com.sale.hive.content.VotesContent.Content.fridgeVoteOneModel import com.sale.hive.content.VotesContent.Content.fridgeVoteTwoDTO import com.sale.hive.content.VotesContent.Content.fridgeVoteTwoModel import com.sale.hive.content.VotesContent.Content.microwaveVoteDownVoteDTO import com.sale.hive.content.VotesContent.Content.microwaveVoteDownVoteModel import com.sale.hive.content.VotesContent.Content.microwaveVoteOneDTO import com.sale.hive.content.VotesContent.Content.microwaveVoteOneModel import com.sale.hive.content.VotesContent.Content.microwaveVoteTwoDTO import com.sale.hive.content.VotesContent.Content.microwaveVoteTwoModel import com.sale.hive.content.VotesContent.Content.microwaveVoteUpVoteDTO import com.sale.hive.content.VotesContent.Content.microwaveVoteUpVoteModel import com.sale.hive.data.local.entity.ProductEntity import com.sale.hive.data.remote.dto.ProductDTO import com.sale.hive.domain.model.ProductModel class ProductContent { companion object Content { val fridgeDTO = ProductDTO( productID = "PRD001", userID = "USR001", name = "Side-by-Side Refrigerator, 641 Net Capacity", description = "Side-by-Side Refrigerator, 641 Net Capacity", image = "", originalCost = "120,000.00 KES", discountCost = "79,000.00 KES", discountPercentage = "34%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023", votes = mutableListOf( fridgeVoteOneDTO, fridgeVoteTwoDTO ) ) val microwaveDTO = ProductDTO( productID = "PRD002", userID = "USR001", name = "<NAME>, 40L", description = "Grill Microwave Oven, 40L. 1300W (Grill) / 1600W (Microwave), Ceramic Enamel", image = "", originalCost = "20,000.00 KES", discountCost = "15,000.00 KES", discountPercentage = "25%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023", votes = mutableListOf( microwaveVoteOneDTO, microwaveVoteTwoDTO, microwaveVoteUpVoteDTO, microwaveVoteDownVoteDTO ) ) val fridgeEntity = ProductEntity( productID = "PRD001", userID = "USR001", name = "Side-by-Side Refrigerator, 641 Net Capacity", description = "Side-by-Side Refrigerator, 641 Net Capacity", image = "", originalCost = "120,000.00 KES", discountCost = "79,000.00 KES", discountPercentage = "34%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023" ) val microwaveEntity = ProductEntity( productID = "PRD002", userID = "USR001", name = "<NAME>, 40L", description = "Grill Microwave Oven, 40L. 1300W (Grill) / 1600W (Microwave), Ceramic Enamel", image = "", originalCost = "20,000.00 KES", discountCost = "15,000.00 KES", discountPercentage = "25%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023" ) val fridgeModel = ProductModel( productID = "PRD001", userID = "USR001", name = "Side-by-Side Refrigerator, 641 Net Capacity", description = "Side-by-Side Refrigerator, 641 Net Capacity", image = "", originalCost = "120,000.00 KES", discountCost = "79,000.00 KES", discountPercentage = "34%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023", votes = mutableListOf( fridgeVoteOneModel, fridgeVoteTwoModel ) ) val microwaveModel = ProductModel( productID = "PRD002", userID = "USR001", name = "<NAME>, 40L", description = "Grill Microwave Oven, 40L. 1300W (Grill) / 1600W (Microwave), Ceramic Enamel", image = "", originalCost = "20,000.00 KES", discountCost = "15,000.00 KES", discountPercentage = "25%", status = "Active", dateUpdated = "07/03/2023", dateCreated = "07/03/2023", votes = mutableListOf( microwaveVoteOneModel, microwaveVoteTwoModel, microwaveVoteUpVoteModel, microwaveVoteDownVoteModel ) ) } }
0
Kotlin
0
0
9015d1f68db90e8d64559fcc4a77c9cc6393f3cc
4,866
Sale-Hive
Apache License 2.0
app/src/main/java/com/pachatary/presentation/common/injection/scheduler/SchedulerProvider.kt
jordifierro
116,311,809
false
null
package com.pachatary.presentation.common.injection.scheduler import io.reactivex.Scheduler class SchedulerProvider(private val subscriberScheduler: Scheduler, private val observerScheduler: Scheduler) { fun subscriber() = subscriberScheduler fun observer() = observerScheduler }
0
Kotlin
0
2
ac6ba680b0d149027bb0e75266f160fce30fd5de
315
pachatary-android
Apache License 2.0
app/src/main/java/dev/vengateshm/android_kotlin_compose_practice/parallax_scroll_effect/ParallaxComponent.kt
vengateshm
670,054,614
false
null
package dev.vengateshm.android_kotlin_compose_practice.parallax_scroll_effect import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import dev.vengateshm.android_kotlin_compose_practice.utils.toDp @Composable fun ParallaxComponent() { val moonScrollSpeed = 0.08f val midBgScrollSpeed = 0.03f val imageHeight = (LocalConfiguration.current.screenWidthDp * (2f / 3f)).dp val lazyListState = rememberLazyListState() var moonScrollOffset by remember { mutableStateOf(0f) } var midBgScrollOffset by remember { mutableStateOf(0f) } val nestedScrollConnection = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { val delta = available.y val layoutInfo = lazyListState.layoutInfo // Check if first item is visible if (lazyListState.firstVisibleItemIndex == 0) return Offset.Zero if (layoutInfo.visibleItemsInfo.lastOrNull()?.index == layoutInfo.totalItemsCount - 1) return Offset.Zero moonScrollOffset += delta * moonScrollSpeed midBgScrollOffset += delta * midBgScrollSpeed return Offset.Zero // Whatever the user scrolls with his finger } } LazyColumn( state = lazyListState, modifier = Modifier .fillMaxWidth() .nestedScroll(nestedScrollConnection), content = { items(10) { Text( modifier = Modifier .fillMaxWidth() .padding(16.dp), text = "Sample Item" ) } item { Box( modifier = Modifier .clipToBounds() .fillMaxWidth() .height(imageHeight + midBgScrollOffset.toDp()) .background( brush = Brush.verticalGradient( colors = listOf( Color(0xFFf36b21), Color(0XFFf9a521) ) ) ) ) { Image( painter = painterResource(id = dev.vengateshm.android_kotlin_compose_practice.R.drawable.ic_moonbg), contentDescription = "moon", contentScale = ContentScale.FillWidth, alignment = Alignment.BottomCenter, modifier = Modifier .matchParentSize() .graphicsLayer { translationY = moonScrollOffset }) Image( painter = painterResource(id = dev.vengateshm.android_kotlin_compose_practice.R.drawable.ic_midbg), contentDescription = "mid bg", contentScale = ContentScale.FillWidth, alignment = Alignment.BottomCenter, modifier = Modifier .matchParentSize() .graphicsLayer { translationY = midBgScrollOffset }) Image( painter = painterResource(id = dev.vengateshm.android_kotlin_compose_practice.R.drawable.ic_outerbg), contentDescription = "outer bg", contentScale = ContentScale.FillWidth, alignment = Alignment.BottomCenter, modifier = Modifier.matchParentSize() ) } } items(20) { Text( modifier = Modifier .fillMaxWidth() .padding(16.dp), text = "Sample Item" ) } }) }
0
null
0
1
b329264313e7f46cf3b5879d2316071cdfefdb33
5,407
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
modules/Plugin_Main/src/main/java/com/example/main/MainActivity.kt
VintLin
536,855,586
false
null
package com.example.main import android.os.Bundle import com.example.main.BR import com.example.main.R import com.example.base.activity.CommonActivity import com.example.base.jetpack.binding.DataBindingConfig import com.example.main.viewmodel.MainViewModel class MainActivity : CommonActivity() { private lateinit var mState: MainViewModel override fun initViewModel() { mState = getActivityScopeViewModel(MainViewModel::class.java) } override fun getDataBindingConfig(): DataBindingConfig { return DataBindingConfig(R.layout.activity_main, BR.vm, mState) } }
1
null
1
1
974d954f364fb863bc220ba4038703826a1c2534
600
Jetpack-Seed
Apache License 2.0
src/main/kotlin/mathlingua/frontend/chalktalk/phase2/ast/group/toplevel/defineslike/MeansSection.kt
DominicKramer
203,428,613
false
null
/* * Copyright 2022 The MathLingua Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mathlingua.frontend.chalktalk.phase2.ast.group.toplevel.defineslike import mathlingua.frontend.chalktalk.phase1.ast.Phase1Node import mathlingua.frontend.chalktalk.phase2.CodeWriter import mathlingua.frontend.chalktalk.phase2.ast.DEFAULT_EXTENDING_SECTION import mathlingua.frontend.chalktalk.phase2.ast.clause.Statement import mathlingua.frontend.chalktalk.phase2.ast.clause.validateStatement import mathlingua.frontend.chalktalk.phase2.ast.common.Phase2Node import mathlingua.frontend.chalktalk.phase2.ast.validateSection import mathlingua.frontend.support.ParseError internal data class MeansSection( val statements: List<Statement>, override val row: Int, override val column: Int ) : Phase2Node { override fun forEach(fn: (node: Phase2Node) -> Unit) = statements.forEach(fn) override fun toCode(isArg: Boolean, indent: Int, writer: CodeWriter): CodeWriter { writer.writeIndent(isArg, indent) writer.writeHeader("means") for (i in statements.indices) { val stmt = statements[i] if (stmt.isInline) { if (i != 0) { writer.writeComma() } writer.writeSpace() writer.writeStatement(stmt.text, stmt.texTalkRoot) } else { writer.writeNewline() writer.writeIndent(true, 2) writer.writeStatement(stmt.text, stmt.texTalkRoot) } } return writer } override fun transform(chalkTransformer: (node: Phase2Node) -> Phase2Node) = chalkTransformer( MeansSection( statements = statements.map { it.transform(chalkTransformer) as Statement }, row, column)) } internal fun validateExtendingSection(node: Phase1Node, errors: MutableList<ParseError>) = validateSection(node.resolve(), errors, DEFAULT_EXTENDING_SECTION) { // more robust validation is done in the // SourceCollection.findInvalidMeansSection(DefinesGroup) // because it needs to know what vars are defined in the `Defines:` section val statements = it.args.map { arg -> validateStatement(arg, errors, arg.isInline) } MeansSection(statements = statements, node.row, node.column) }
4
Kotlin
0
67
c264bc61ac7d9e520018f2652b110c4829876c82
2,904
mathlingua
Apache License 2.0
android/src/main/java/com/layerinfinity/matrixuniversalsdk/RNEventEmitter.kt
layerinfinity
636,077,251
false
null
package com.layerinfinity.matrixuniversalsdk import com.facebook.react.bridge.ReactApplicationContext class RNEventEmitter(private val reactContext: ReactApplicationContext) { companion object { // Event types const val RN_EVENT_ERROR = "OnError" } }
1
Kotlin
0
1
7a875aeda1a34d8a028cede6529814681638ad51
265
react-native-matrix-universal-sdk
MIT License
kmmresult-test/src/commonMain/kotlin/at/asitplus/TestExtensions.kt
a-sit-plus
567,159,135
false
{"Kotlin": 24340, "Java": 547}
/* * Copyright 2021 - 2023 A-SIT Plus GmbH. Obviously inspired and partially copy-pasted from kotlin.Result. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package at.asitplus import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldBe /** * Shorthand for `getOrThrow() shouldBe expected` */ infix fun <T> KmmResult<T>.shouldSucceedWith(expected: T): T = getOrThrow() shouldBe expected /** * [KmmResult] matcher. Use as follows: `okResult should succeed`, `errResult shouldNot succeed` */ @Suppress("ClassNaming") object succeed : Matcher<KmmResult<*>> { override fun test(value: KmmResult<*>) = MatcherResult( value.isSuccess, failureMessageFn = { "Should have succeeded, but failed:\n${ value.exceptionOrNull()!!.stackTraceToString() }" }, negatedFailureMessageFn = { "Should have failed, but succeeded with ${value.getOrNull()!!}" } ) } /** * Asserts that this KmmResult should succeed and returns the contained value */ fun <T> KmmResult<T>.shouldSucceed(): T { this should succeed return getOrThrow() }
1
Kotlin
2
8
78acabccdf7d87f20dac3591392a5c4cb69da29c
1,295
KmmResult
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/settings/notifications/NotificationsFragment.kt
fahimaltinordu
312,207,740
false
null
package com.starbase.bankwallet.modules.settings.notifications import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.RecyclerView import io.horizontalsystems.bankwallet.R import io.horizontalsystems.bankwallet.core.BaseFragment import io.horizontalsystems.bankwallet.core.setOnSingleClickListener import io.horizontalsystems.bankwallet.modules.settings.notifications.bottommenu.BottomNotificationMenu import io.horizontalsystems.core.findNavController import io.horizontalsystems.views.ListPosition import io.horizontalsystems.views.SettingsViewDropdown import io.horizontalsystems.views.inflate import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.fragment_notifications.* import kotlinx.android.synthetic.main.view_holder_notification_coin_name.* class NotificationsFragment : BaseFragment(), NotificationItemsAdapter.Listener { private val viewModel by viewModels<NotificationsViewModel> { NotificationsModule.Factory() } private lateinit var notificationItemsAdapter: NotificationItemsAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_notifications, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) toolbar.setNavigationOnClickListener { findNavController().popBackStack() } buttonAndroidSettings.setOnSingleClickListener { viewModel.openSettings() } deactivateAll.setOnSingleClickListener { viewModel.deactivateAll() } notificationItemsAdapter = NotificationItemsAdapter(this) notifications.adapter = notificationItemsAdapter switchNotification.setOnClickListener { switchNotification.switchToggle() } switchNotification.setOnCheckedChangeListener { viewModel.switchAlertNotification(it) } observeViewModel() } override fun onResume() { super.onResume() viewModel.onResume() } override fun onItemClick(item: NotificationViewItem) { viewModel.onDropdownTap(item) } private fun observeViewModel() { viewModel.itemsLiveData.observe(viewLifecycleOwner, Observer { notificationItemsAdapter.items = it notificationItemsAdapter.notifyDataSetChanged() }) viewModel.openNotificationSettings.observe(viewLifecycleOwner, Observer { context?.let { val intent = Intent() intent.action = "android.settings.APP_NOTIFICATION_SETTINGS" intent.putExtra("android.provider.extra.APP_PACKAGE", it.packageName) startActivity(intent) } }) viewModel.controlsVisible.observe(viewLifecycleOwner, Observer { notifications.isVisible = it deactivateAll.isVisible = it }) viewModel.setWarningVisible.observe(viewLifecycleOwner, Observer { showWarning -> switchNotification.isVisible = !showWarning textDescription.isVisible = !showWarning textWarning.isVisible = showWarning buttonAndroidSettings.isVisible = showWarning }) viewModel.notificationIsOnLiveData.observe(viewLifecycleOwner, Observer { enabled -> switchNotification.setChecked(enabled) }) viewModel.openOptionsDialog.observe(viewLifecycleOwner, Observer { (coinName, coinId, mode) -> BottomNotificationMenu.show(childFragmentManager, mode, coinName, coinId) }) viewModel.setDeactivateButtonEnabled.observe(viewLifecycleOwner, Observer { enabled -> context?.let { val color = if (enabled) R.color.lucian else R.color.grey_50 deactivateAllText.setTextColor(it.getColor(color)) } deactivateAll.isEnabled = enabled }) } } class NotificationItemsAdapter(private val listener: Listener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var items = listOf<NotificationViewItem>() interface Listener { fun onItemClick(item: NotificationViewItem) } private val coinName = 1 private val notificationOption = 2 override fun getItemViewType(position: Int): Int { return when (items[position].type) { NotificationViewItemType.CoinName -> coinName else -> notificationOption } } override fun getItemId(position: Int): Long { return items[position].hashCode().toLong() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { notificationOption -> NotificationItemViewHolder(inflate(parent, R.layout.view_holder_setting_with_dropdown, false), onClick = { index -> listener.onItemClick(items[index]) }) coinName -> NotificationCoinNameViewHolder(inflate(parent, R.layout.view_holder_notification_coin_name, false)) else -> throw Exception("Invalid view type") } } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is NotificationItemViewHolder -> holder.bind(items[position]) is NotificationCoinNameViewHolder -> holder.bind(items[position]) } } } class NotificationCoinNameViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(item: NotificationViewItem) { coinName.text = item.coinName } } class NotificationItemViewHolder(override val containerView: View, val onClick: (position: Int) -> Unit) : RecyclerView.ViewHolder(containerView), LayoutContainer { private val dropdownView = containerView.findViewById<SettingsViewDropdown>(R.id.dropdownView) fun bind(item: NotificationViewItem) { dropdownView.apply { showTitle(item.titleRes?.let { containerView.context.getString(it) }) showDropdownValue(itemView.context.getString(item.dropdownValue)) setListPosition(getListPosition(item.type)) } containerView.setOnClickListener { onClick(bindingAdapterPosition) } } private fun getListPosition(type: NotificationViewItemType): ListPosition { return when (type) { NotificationViewItemType.ChangeOption -> ListPosition.First else -> ListPosition.Last } } }
128
null
141
4
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
6,913
WILC-wallet-android
MIT License
app/src/main/java/org/citruscircuits/viewer/MainViewerActivity.kt
frc1678
804,234,032
false
{"Kotlin": 418437}
package org.citruscircuits.viewer import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.LinearLayout import android.widget.PopupWindow import android.widget.TextView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.core.view.GravityCompat import androidx.customview.widget.ViewDragHelper import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.FragmentManager import androidx.lifecycle.lifecycleScope import com.google.android.material.navigation.NavigationView import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import kotlinx.android.synthetic.main.activity_main.container import kotlinx.android.synthetic.main.field_map_popup.view.blue_chip import kotlinx.android.synthetic.main.field_map_popup.view.chip_group import kotlinx.android.synthetic.main.field_map_popup.view.close_button import kotlinx.android.synthetic.main.field_map_popup.view.field_map import kotlinx.android.synthetic.main.field_map_popup.view.none_chip import kotlinx.android.synthetic.main.field_map_popup.view.red_chip import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.citruscircuits.viewer.constants.Constants import org.citruscircuits.viewer.data.Match import org.citruscircuits.viewer.data.NotesApi import org.citruscircuits.viewer.fragments.alliance_details.AllianceDetailsFragment import org.citruscircuits.viewer.fragments.groups.GroupsFragment //import org.citruscircuits.viewer.fragments.live_picklist.LivePicklistFragment import org.citruscircuits.viewer.fragments.match_schedule.MatchScheduleFragment import org.citruscircuits.viewer.fragments.pickability.PickabilityFragment import org.citruscircuits.viewer.fragments.preferences.PreferencesFragment import org.citruscircuits.viewer.fragments.ranking.RankingFragment import org.citruscircuits.viewer.fragments.team_list.TeamListFragment import java.io.File import java.io.FileOutputStream import java.io.FileReader import java.io.FileWriter import java.io.InputStream import java.io.OutputStream /** * Main activity class that handles navigation. */ class MainViewerActivity : ViewerActivity() { private lateinit var toggle: ActionBarDrawerToggle companion object { var matchCache = mutableMapOf<String, Match>() var teamList = listOf<String>() var starredMatches = mutableSetOf<String>() var eliminatedAlliances = mutableSetOf<String>() val refreshManager = RefreshManager() val leaderboardCache = mutableMapOf<String, Leaderboard>() var notesCache = mutableMapOf<String, String>() var mapMode = 1 /** Update Viewer Notes locally by pulling from Grosbeak*/ suspend fun updateNotesCache() { val notesList = NotesApi.getAll(Constants.EVENT_KEY) notesCache = notesList.toMutableMap() Log.d("notes", "updated notes cache") } } /** * Overrides the back button to go back to last fragment. * Disables the back button and returns nothing when in the startup match schedule. */ @SuppressLint("MissingSuperCall") override fun onBackPressed() { val drawerLayout: DrawerLayout = findViewById(R.id.container) if (drawerLayout.isDrawerOpen(GravityCompat.START)) drawerLayout.closeDrawer(GravityCompat.START) if (supportFragmentManager.backStackEntryCount > 1) supportFragmentManager.popBackStack() } override fun onResume() { super.onResume() // Creates the files for user data points and starred matches UserDataPoints.read(this) StarredMatches.read() EliminatedAlliances.read() // Pull the set of starred matches from the downloads file viewer_starred_matches. val jsonStarred = StarredMatches.contents.get("starredMatches")?.asJsonArray if (jsonStarred != null) { for (starred in jsonStarred) { starredMatches.add(starred.asString) } } // Pull the set of eliminated alliances from the downloads file viewer_eliminated_alliances. val jsonEliminated = EliminatedAlliances.contents.get("eliminatedAlliances")?.asJsonArray if (jsonEliminated != null) { for (alliance in jsonEliminated) { eliminatedAlliances.add(alliance.asString) } } } /** Creates the main activity, containing the top app bar, nav drawer, and shows by default the match schedule page*/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportActionBar?.hide() setToolbarText(actionBar, supportActionBar) val drawerLayout: DrawerLayout = findViewById(R.id.container) val navView: NavigationView = findViewById(R.id.navigation) // Defaults navView.setCheckedItem(R.id.nav_menu_match_schedule) toggle = ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close) drawerLayout.addDrawerListener(toggle) toggle.syncState() // Creates leaderboards for each datapoint for the Rankings page (Constants.FIELDS_TO_BE_DISPLAYED_TEAM_DETAILS + Constants.FIELDS_TO_BE_DISPLAYED_LFM).forEach { if (it !in Constants.CATEGORY_NAMES) createLeaderboard(it) } // Creates a refresher that will call updateNavFooter() every so often refreshManager.addRefreshListener { Log.d("data-refresh", "Updated: ranking") updateNavFooter() } if (!Constants.USE_TEST_DATA) { lifecycleScope.launch { updateNotesCache() } } // Make the back button in the top action bar only go back one screen and not to the first screen supportActionBar?.setDisplayHomeAsUpEnabled(true) // Creates fragments val matchScheduleFragment = MatchScheduleFragment() val rankingFragment = RankingFragment() //val livePicklistFragment = LivePicklistFragment() val pickabilityFragment = PickabilityFragment() val teamListFragment = TeamListFragment() val allianceDetailsFragment = AllianceDetailsFragment() val preferencesFragment = PreferencesFragment() updateNavFooter() // default screen when the viewer starts (after pulling data) - the match schedule page supportFragmentManager.beginTransaction().addToBackStack(null) .replace(R.id.nav_host_fragment, matchScheduleFragment, "matchSchedule").commit() // Listener to open the nav drawer container.addDrawerListener(NavDrawerListener(navView, supportFragmentManager, this)) // Set a listener for each item in the drawer navView.setNavigationItemSelectedListener { if (drawerLayout.isDrawerOpen(GravityCompat.START)) drawerLayout.closeDrawer( GravityCompat.START ) when (it.itemId) { R.id.nav_menu_match_schedule -> { MatchScheduleFragment.lastPageMatchDetails = false supportFragmentManager.popBackStack(0, 0) supportFragmentManager.beginTransaction().addToBackStack(null) .replace(R.id.nav_host_fragment, matchScheduleFragment, "matchSchedule") .commit() } R.id.nav_menu_rankings -> { supportFragmentManager.beginTransaction().addToBackStack(null) .replace(R.id.nav_host_fragment, rankingFragment, "rankings").commit() } // R.id.nav_menu_picklist -> { // supportFragmentManager.beginTransaction().addToBackStack(null) // .replace(R.id.nav_host_fragment, livePicklistFragment, "picklist").commit() // } R.id.nav_menu_pickability -> { val ft = supportFragmentManager.beginTransaction() if (supportFragmentManager.fragments.last().tag != "pickability") ft.addToBackStack( null ) ft.replace(R.id.nav_host_fragment, pickabilityFragment, "pickability").commit() } R.id.nav_menu_team_list -> { val ft = supportFragmentManager.beginTransaction() if (supportFragmentManager.fragments.last().tag != "teamList") ft.addToBackStack( null ) ft.replace(R.id.nav_host_fragment, teamListFragment, "teamlist").commit() } R.id.nav_menu_alliance_details -> { val ft = supportFragmentManager.beginTransaction() if (supportFragmentManager.fragments.last().tag != "allianceDetails") ft.addToBackStack( null ) ft.replace(R.id.nav_host_fragment, allianceDetailsFragment, "allianceDetails") .commit() } R.id.nav_menu_groups -> { val ft = supportFragmentManager.beginTransaction() if (supportFragmentManager.fragments.last().tag != "groups") ft.addToBackStack( null ) ft.replace(R.id.nav_host_fragment, GroupsFragment(), "groups").commit() } R.id.nav_menu_preferences -> { val ft = supportFragmentManager.beginTransaction() if (supportFragmentManager.fragments.last().tag != "preferences") ft.addToBackStack( null ) ft.replace(R.id.nav_host_fragment, preferencesFragment, "preferences").commit() } } true } lifecycleScope.launch(Dispatchers.IO) { Groups.startListener() } } override fun onOptionsItemSelected(item: MenuItem) = if (toggle.onOptionsItemSelected(item)) true else super.onOptionsItemSelected(item) /** Inflate the top bar, which includes the field map button */ override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.toolbar, menu) val fieldMapItem: MenuItem = menu.findItem(R.id.field_map_button) val fieldButton = fieldMapItem.actionView // Field map button fieldButton?.setOnClickListener { val popupView = View.inflate(this, R.layout.field_map_popup, null) val width = LinearLayout.LayoutParams.MATCH_PARENT val height = LinearLayout.LayoutParams.MATCH_PARENT val popupWindow = PopupWindow(popupView, width, height, false) popupWindow.showAtLocation(it, Gravity.CENTER, 0, 0) when (mapMode) { 0 -> { popupView.red_chip.isChecked = true popupView.none_chip.isChecked = false popupView.blue_chip.isChecked = false popupView.field_map.setImageResource(R.drawable.field_red_map_24) } 1 -> { popupView.red_chip.isChecked = false popupView.none_chip.isChecked = true popupView.blue_chip.isChecked = false popupView.field_map.setImageResource(R.drawable.field_24) } 2 -> { popupView.red_chip.isChecked = false popupView.none_chip.isChecked = false popupView.blue_chip.isChecked = true popupView.field_map.setImageResource(R.drawable.field_blue_map_24) } } popupView.red_chip.setOnClickListener { popupView.red_chip.isChecked = true } popupView.blue_chip.setOnClickListener { popupView.blue_chip.isChecked = true } popupView.none_chip.setOnClickListener { popupView.none_chip.isChecked = true } popupView.chip_group.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { popupView.red_chip.id -> { popupView.field_map.setImageResource(R.drawable.field_red_map_24) mapMode = 0 } popupView.none_chip.id -> { popupView.field_map.setImageResource(R.drawable.field_24) mapMode = 1 } popupView.blue_chip.id -> { popupView.field_map.setImageResource(R.drawable.field_blue_map_24) mapMode = 2 } } return@setOnCheckedChangeListener } popupView.close_button.setOnClickListener { popupWindow.dismiss() } } return super.onCreateOptionsMenu(menu) } /** Nav footer that displays when the viewer was last refreshed. */ private fun updateNavFooter() { val footer = findViewById<TextView>(R.id.nav_footer) footer.text = if (Constants.USE_TEST_DATA) getString(R.string.test_data) else getString(R.string.last_updated, super.getTimeText()) } /** Object to extract the datapoints of the user preferences file and write to it. */ object UserDataPoints { /** Holds a user's datapoints */ var contents: JsonObject? = null private var gson = Gson() /** User preferences file*/ val file = File(Constants.DOWNLOADS_FOLDER, "viewer_user_data_prefs.json") /** Get contents from User Preferences file. This file should always exist unless a mismatch is found, in which the file will be deleted*/ fun read(context: Context) { // Load defaults if no file exists if (!fileExists()) copyDefaults(context) // Try to pull from file try { contents = JsonParser.parseReader(FileReader(file)).asJsonObject } catch (e: Exception) { Log.e("UserDataPoints.read", "Failed to read user datapoints file") } // Gets user val user = contents?.get("selected")?.asString // Gets user's datapoints val userDataPoints = contents?.get(user)?.asJsonArray // If the datapoints exist, check if they match with Constants TEAM / TIM datapoints if (userDataPoints != null) { for (i in userDataPoints) { if ( i.asString !in Constants.FIELDS_TO_BE_DISPLAYED_TEAM_DETAILS && i.asString !in Constants.FIELDS_TO_BE_DISPLAYED_MATCH_DETAILS_PLAYED && i.asString != "See Matches" && i.asString != "TEAM" && i.asString != "TIM" ) { file.delete() // If not, that means someone forgot to update either Constants or User Datapoints defaults Log.e( "UserDataPoints.read", "Datapoint ${i.asString} does not exist in Constants" ) // Reset back to defaults copyDefaults(context) break } } } } fun write() { val writer = FileWriter(file, false) gson.toJson(contents as JsonElement, writer) writer.close() } /** Check if user preferences file exists*/ private fun fileExists(): Boolean = file.exists() /**Copies the default preferences to the User Preferences file*/ fun copyDefaults(context: Context) { // Read from user preferences file val inputStream: InputStream = context.resources.openRawResource(R.raw.default_prefs) try { // Copies over the contents of the defaults (inputStream) to the file val outputStream: OutputStream = FileOutputStream(file) val buffer = ByteArray(1024) var len: Int? while (inputStream.read(buffer, 0, buffer.size).also { len = it } != -1) { outputStream.write(buffer, 0, len!!) } inputStream.close() outputStream.close() try { // Add the other default elements to the file contents = JsonParser.parseReader(FileReader(file)).asJsonObject contents?.remove("key") contents?.addProperty("key", Constants.DEFAULT_KEY) contents?.remove("schedule") contents?.addProperty("schedule", Constants.DEFAULT_SCHEDULE) contents?.remove("default_key") contents?.addProperty("default_key", Constants.DEFAULT_KEY) contents?.remove("default_schedule") contents?.addProperty("default_schedule", Constants.DEFAULT_SCHEDULE) write() } catch (e: Exception) { Log.e("UserDataPoints.read", "Failed to read user datapoints file") } } catch (e: Exception) { Log.e("copyDefaults", "Failed to copy default preferences to file, $e") } } } /** * Writes file to store the starred matches on the viewer */ object StarredMatches { var contents = JsonObject() private var gson = Gson() // Creates a list that stores all the match numbers that team 1678 is in val citrusMatches = matchCache.filter { return@filter it.value.blueTeams.contains("1678") or it.value.redTeams.contains("1678") }.map { return@map it.value.matchNumber } private val file = File(Constants.DOWNLOADS_FOLDER, "viewer_starred_matches.json") fun read() { if (!fileExists()) write() try { contents = JsonParser.parseReader(FileReader(file)).asJsonObject } catch (e: Exception) { Log.e("StarredMatches.read", "Failed to read starred matches file") } } private fun write() { val writer = FileWriter(file, false) gson.toJson(contents as JsonElement, writer) writer.close() } private fun fileExists(): Boolean = file.exists() /** * Updates the file with the currently starred matches based on the companion object starredMatches */ fun input() { val starredJsonArray = JsonArray() for (starred in starredMatches) starredJsonArray.add(starred) contents.remove("starredMatches") contents.add("starredMatches", starredJsonArray) write() } } /** Object to read and write eliminated alliances data. This was not used this year. */ object EliminatedAlliances { var contents = JsonObject() private var gson = Gson() private val file = File(Constants.DOWNLOADS_FOLDER, "viewer_eliminated_alliances.json") fun read() { if (!fileExists()) write() try { contents = JsonParser.parseReader(FileReader(file)).asJsonObject } catch (e: Exception) { Log.e("EliminatedAlliances.read", "Failed to read eliminated alliances file") } } private fun write() { val writer = FileWriter(file, false) gson.toJson(contents as JsonElement, writer) writer.close() } private fun fileExists(): Boolean = file.exists() fun input() { val eliminatedJsonArray = JsonArray() for (alliance in eliminatedAlliances) eliminatedJsonArray.add(alliance) contents.remove("eliminatedAlliances") contents.add("eliminatedAlliances", eliminatedJsonArray) write() } } /** * An object to read/write the starred teams file with. */ object StarredTeams { private val gson = Gson() private val teams = mutableSetOf<String>() fun add(team: String) { teams.add(team) write() } fun remove(team: String) { teams.remove(team) write() } fun contains(team: String) = teams.contains(team) private val file = File(Constants.DOWNLOADS_FOLDER, "viewer_starred_teams.json") fun read() { if (!file.exists()) write() try { JsonParser.parseReader(FileReader(file)).asJsonArray.forEach { teams.add(it.asString) } } catch (e: Exception) { Log.e("StarredTeams.read", "Failed to read starred teams file") } } private fun write() { val writer = FileWriter(file, false) gson.toJson(teams, writer) writer.close() } } } fun Activity.hideKeyboard() { hideKeyboard(currentFocus ?: View(this)) } fun Context.hideKeyboard(view: View) { val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } /** Class for creating listeners for all fragments (manages state changes)*/ class NavDrawerListener( private val navView: NavigationView, private val fragManager: FragmentManager, private val activity: Activity ) : DrawerLayout.DrawerListener { override fun onDrawerSlide(drawerView: View, slideOffset: Float) {} override fun onDrawerOpened(drawerView: View) = activity.hideKeyboard() override fun onDrawerClosed(drawerView: View) {} override fun onDrawerStateChanged(newState: Int) { if (newState == ViewDragHelper.STATE_SETTLING) { when (fragManager.fragments.last().tag) { "matchSchedule" -> navView.setCheckedItem(R.id.nav_menu_match_schedule) "rankings" -> navView.setCheckedItem(R.id.nav_menu_rankings) "picklist" -> navView.setCheckedItem(R.id.nav_menu_picklist) "pickability" -> navView.setCheckedItem(R.id.nav_menu_pickability) "teamList" -> navView.setCheckedItem(R.id.nav_menu_team_list) "allianceDetails" -> navView.setCheckedItem(R.id.nav_menu_alliance_details) "groups" -> navView.setCheckedItem(R.id.nav_menu_groups) "preferences" -> navView.setCheckedItem(R.id.nav_menu_preferences) } } } }
0
Kotlin
0
0
f38e2f99c1b16f6f5a89342b4619c19082346b09
23,156
viewer-2024-public
MIT License
conductor-client/src/main/kotlin/com/openlattice/edm/processors/GetPartitionsFromEntitySetEntryProcessor.kt
openlattice
101,697,464
false
null
package com.openlattice.edm.processors import com.openlattice.edm.EntitySet import com.openlattice.rhizome.DelegatedIntSet import com.openlattice.rhizome.hazelcast.entryprocessors.AbstractReadOnlyRhizomeEntryProcessor import java.util.* class GetPartitionsFromEntitySetEntryProcessor : AbstractReadOnlyRhizomeEntryProcessor<UUID, EntitySet, DelegatedIntSet>() { override fun process(entry: MutableMap.MutableEntry<UUID, EntitySet?>): DelegatedIntSet { val value = entry.value ?: return DelegatedIntSet(setOf()) return DelegatedIntSet(value.partitions) } }
2
Kotlin
0
2
de0b93da64826f129db41055a874cebf73ce95d8
581
openlattice
Apache License 2.0
app/src/main/java/com/andre/apps/filamentdroid/data/network/UserResponse.kt
andrejoshua
693,715,679
false
{"Kotlin": 35695}
package com.andre.apps.filamentdroid.data.network import com.google.gson.annotations.SerializedName data class UserResponse( @SerializedName("id") val id: Long, @SerializedName("uid") val uid: String, @SerializedName("first_name") val firstName: String, @SerializedName("last_name") val lastName: String, @SerializedName("username") val username: String, @SerializedName("email") val email: String, @SerializedName("avatar") val avatar: String, @SerializedName("gender") val gender: String, @SerializedName("phone_number") val phoneNumber: String, @SerializedName("social_insurance_number") val socialInsuranceNumber: String, @SerializedName("date_of_birth") val dateOfBirth: String, @SerializedName("employment") val employment: EmploymentResponse, @SerializedName("address") val address: AddressResponse, @SerializedName("credit_card") val cc: CreditCardResponse, @SerializedName("subscription") val subscription: SubscriptionResponse, )
0
Kotlin
0
0
ccf4579a2618b66fc39339de29014e347fd48c18
1,001
filament-droid
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/pin/PinInteractor.kt
amitkpandey
157,035,948
true
{"Kotlin": 392733, "Ruby": 4476}
package io.horizontalsystems.bankwallet.modules.pin import io.horizontalsystems.bankwallet.core.IAdapterManager import io.horizontalsystems.bankwallet.core.IKeyStoreSafeExecute import io.horizontalsystems.bankwallet.core.IPinManager import io.horizontalsystems.bankwallet.core.IWordsManager class PinInteractor( private val pinManager: IPinManager, private val wordsManager: IWordsManager, private val adapterManager: IAdapterManager, private val keystoreSafeExecute: IKeyStoreSafeExecute) : PinModule.IPinInteractor { var delegate: PinModule.IPinInteractorDelegate? = null private var storedPin: String? = null override fun set(pin: String?) { storedPin = pin } override fun validate(pin: String): Boolean { return storedPin == pin } override fun save(pin: String) { keystoreSafeExecute.safeExecute( action = Runnable { pinManager.store(pin) }, onSuccess = Runnable { delegate?.didSavePin() }, onFailure = Runnable { delegate?.didFailToSavePin() } ) } override fun unlock(pin: String): Boolean { return pinManager.validate(pin) } override fun startAdapters() { keystoreSafeExecute.safeExecute( action = Runnable { wordsManager.safeLoad() adapterManager.start() }, onSuccess = Runnable { delegate?.didStartedAdapters() } ) } }
0
Kotlin
0
1
cbcaed74f977fbec7d2ed1b13bb0b08d9a0f8ef6
1,543
bank-wallet-android
MIT License
app/src/main/java/dev/vengateshm/artbookappandroidtestingudemy/drag_drop/DragDropAdapter.kt
vengateshm
716,970,555
false
{"Kotlin": 53714, "Java": 3653}
package dev.vengateshm.artbookappandroidtestingudemy.drag_drop import android.annotation.SuppressLint import android.content.ClipData import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.View.DragShadowBuilder import android.view.View.OnTouchListener import android.view.ViewGroup import android.widget.TextView import androidx.cardview.widget.CardView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import dev.vengateshm.artbookappandroidtestingudemy.R import dev.vengateshm.artbookappandroidtestingudemy.drag_drop.DragDropAdapter.ListViewHolder class DragDropAdapter( var list: List<String>, private val listener: Listener? ) : RecyclerView.Adapter<ListViewHolder>(), OnTouchListener { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_drag_drop, parent, false) return ListViewHolder(view) } @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: ListViewHolder, position: Int) { holder.tvGrid.text = list[position] holder.cvGrid.tag = position holder.cvGrid.setOnTouchListener(this) holder.cvGrid.setOnDragListener(DragListener(listener)) } override fun getItemCount(): Int { return list.size } @SuppressLint("ClickableViewAccessibility") override fun onTouch(view: View, event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { val data = ClipData.newPlainText("", "") val shadowBuilder = DragShadowBuilder(view) view.startDragAndDrop(data, shadowBuilder, view, 0) return true } return false } fun updateList(list: List<String>) { this.list = list } val dragInstance: DragListener? get() = if (listener != null) { DragListener(listener) } else { null } inner class ListViewHolder(itemView: View) : ViewHolder(itemView) { var tvGrid: TextView var cvGrid: CardView init { tvGrid = itemView.findViewById(R.id.tvGrid) cvGrid = itemView.findViewById(R.id.cvGrid) } } }
0
Kotlin
0
0
a4bebf307750fe65a20abb6f7efda17c02831f44
2,374
android_testing_udemy_art_book_app
Apache License 2.0
source-downloader-core/src/main/kotlin/xyz/shoaky/sourcedownloader/core/DefaultPluginContext.kt
shoaky009
607,575,763
false
null
package xyz.shoaky.sourcedownloader.core import com.google.common.cache.CacheBuilder import org.springframework.stereotype.Component import xyz.shoaky.sourcedownloader.sdk.* import xyz.shoaky.sourcedownloader.sdk.component.SdComponentSupplier import java.util.concurrent.ConcurrentHashMap class DefaultPluginContext( private val componentManager: SdComponentManager, private val instanceManager: InstanceManager, private val cacheManager: MemoryCacheManager ) : PluginContext { override fun registerSupplier(vararg suppliers: SdComponentSupplier<*>) { componentManager.registerSupplier(*suppliers) } override fun registerInstanceFactory(vararg factories: InstanceFactory<*>) { instanceManager.registerInstanceFactory(*factories) } override fun <T> load(name: String, klass: Class<T>, props: Properties?): T { return instanceManager.load(name, klass, props) } override fun getInstanceManager(): InstanceManager { return instanceManager } } @Component class MemoryCacheManager { private val caches: MutableMap<String, Cache<*, *>> = ConcurrentHashMap() @Suppress("UNCHECKED_CAST") fun <K : Any, V : Any> getCache(name: String, loader: CacheLoader<K, V>): Cache<K, V> { val cache = caches.getOrPut(name) { MemoryCache(loader) } as? Cache<K, V> ?: throw IllegalStateException("cache $name is not a MemoryCache") return cache } } class MemoryCache<K : Any, V : Any>( private val loader: CacheLoader<K, V> ) : Cache<K, V> { private val cache = CacheBuilder.newBuilder().maximumSize(2000).build( object : com.google.common.cache.CacheLoader<K, V>() { override fun load(key: K): V { return loader.load(key) } } ) override fun get(key: K): V { return cache.get(key) } }
1
Kotlin
0
7
5d1a3d0ed55f6f935aeee93e96033fd918eca14c
1,883
source-downloader
Apache License 2.0
mazeview/src/main/java/com/zetzaus/mazeview/extension/ContextExtensions.kt
SebastianLiando
337,328,176
false
null
package com.zetzaus.mazeview.extension import android.content.Context import android.graphics.Bitmap import android.util.TypedValue import androidx.annotation.AttrRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat @Throws(IllegalArgumentException::class) fun Context.getDrawableOrThrow(@DrawableRes id: Int) = ContextCompat.getDrawable(this, id) ?: throw IllegalArgumentException("Id $id does not exist!") /** * Returns the color that is relevant to the current theme. * * @param id The color id. Theme relevant color ids can be found in [R.attr.*]. * @return The color. */ fun Context.getThemeColor(@AttrRes id: Int): Int { val typed = TypedValue() val attributes = obtainStyledAttributes(typed.data, IntArray(1) { id }) val color = attributes.getColor(0, 0) attributes.recycle() return color } /** * Returns the image. * * @param id The drawable resource id. * @param size The size of the image. * * @return The image. */ fun Context.getBitmap(@DrawableRes id: Int, size: Int): Bitmap { return getDrawableOrThrow(id).toScaledBitmap(size, size) }
0
Kotlin
0
0
b0d270f8fa86b4eaa1b6271f2979bf81e5c7e1d5
1,129
maze-mdp
MIT License
library/src/main/java/com/aminography/primedatepicker/picker/PrimeDatePickerImpl.kt
aminography
188,271,012
false
null
package com.aminography.primedatepicker.picker import android.content.Context import android.content.DialogInterface import android.content.res.ColorStateList import android.graphics.Typeface import android.os.Bundle import android.view.View import android.widget.Toast import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.widget.ImageViewCompat import androidx.fragment.app.FragmentManager import com.aminography.primecalendar.PrimeCalendar import com.aminography.primecalendar.civil.CivilCalendar import com.aminography.primecalendar.common.CalendarFactory import com.aminography.primecalendar.common.CalendarType import com.aminography.primedatepicker.R import com.aminography.primedatepicker.calendarview.PrimeCalendarView import com.aminography.primedatepicker.common.Direction import com.aminography.primedatepicker.common.OnDayPickedListener import com.aminography.primedatepicker.common.OnMonthLabelClickListener import com.aminography.primedatepicker.common.PickType import com.aminography.primedatepicker.picker.action.ActionBarView import com.aminography.primedatepicker.picker.base.BaseLazyView import com.aminography.primedatepicker.picker.callback.BaseDayPickCallback import com.aminography.primedatepicker.picker.callback.MultipleDaysPickCallback import com.aminography.primedatepicker.picker.callback.RangeDaysPickCallback import com.aminography.primedatepicker.picker.callback.SingleDayPickCallback import com.aminography.primedatepicker.picker.go.GotoView import com.aminography.primedatepicker.picker.selection.SelectionBarView import com.aminography.primedatepicker.picker.selection.multiple.MultipleDaysSelectionBarView import com.aminography.primedatepicker.picker.selection.range.RangeDaysSelectionBarView import com.aminography.primedatepicker.picker.selection.single.SingleDaySelectionBarView import com.aminography.primedatepicker.picker.theme.LightThemeFactory import com.aminography.primedatepicker.picker.theme.base.ThemeFactory import com.aminography.primedatepicker.picker.theme.base.applyTheme import com.aminography.primedatepicker.utils.* import kotlinx.android.synthetic.main.fragment_date_picker_bottom_sheet.view.* import kotlinx.coroutines.CoroutineScope import java.util.* /** * `PrimeDatePickerBottomSheet` contains the logic of picking days in a bottom sheet view. * * @author aminography */ @Suppress("unused") internal class PrimeDatePickerImpl( private var onDismiss: (() -> Unit)? = null ) : PrimeDatePicker, OnDayPickedListener, OnMonthLabelClickListener { private lateinit var context: Context private lateinit var coroutineScope: CoroutineScope private var onCancelListener: DialogInterface.OnCancelListener? = null private var onDismissListener: DialogInterface.OnDismissListener? = null private var onDayPickCallback: BaseDayPickCallback? = null private var onDayPickedListener: OnDayPickedListener? = null private var internalPickType: PickType = PickType.NOTHING private lateinit var initialDateCalendar: PrimeCalendar private val calendarType: CalendarType get() = initialDateCalendar.calendarType private val locale: Locale get() = initialDateCalendar.locale override val pickType: PickType get() = internalPickType private lateinit var rootView: View private lateinit var selectionBarView: SelectionBarView private var gotoView: BaseLazyView? = null private var direction: Direction = Direction.LTR private var typeface: Typeface? = null private var autoSelectPickEndDay: Boolean = true private lateinit var themeFactory: ThemeFactory internal fun onCreate(context: Context, coroutineScope: CoroutineScope) { this.context = context this.coroutineScope = coroutineScope } internal fun onInitViews(rootView: View, arguments: Bundle?) { this.rootView = rootView initialDateCalendar = DateUtils.restoreCalendar( arguments?.getString("initialDateCalendar") ) ?: CivilCalendar() arguments?.getInt("firstDayOfWeek", -1)?.takeIf { it != -1 }?.let { initialDateCalendar.firstDayOfWeek = it } arguments?.getBoolean("autoSelectPickEndDay", true)?.let { autoSelectPickEndDay = it } arguments?.getString("pickType")?.let { internalPickType = PickType.valueOf(it) } arguments?.getBoolean("initiallyPickEndDay")?.takeIf { it }?.let { internalPickType = PickType.RANGE_END } direction = calendarType.findDirection(locale) themeFactory = arguments?.getSerializable("themeFactory") as? ThemeFactory ?: LightThemeFactory() themeFactory.context = context themeFactory.typefacePath?.let { typeface = Typeface.createFromAsset(context.assets, it) } with(rootView) { themeFactory.let { ImageViewCompat.setImageTintList( cardBackgroundImageView, ColorStateList.valueOf(it.dialogBackgroundColor) ) generateTopGradientDrawable(it.gotoViewBackgroundColor).let { drawable -> circularRevealFrameLayout.setBackgroundDrawableCompat(drawable) } } typeface?.let { calendarView.typeface = it } calendarView.doNotInvalidate { if (it.pickType == PickType.NOTHING) { it.calendarType = calendarType val minFeasibleDate = CalendarFactory.newInstance(calendarType).also { calendar -> calendar.set(1, 0, 1) } val maxFeasibleDate = CalendarFactory.newInstance(calendarType).also { calendar -> calendar.set(9999, 11, 29) } it.minDateCalendar = DateUtils.restoreCalendar(arguments?.getString("minDateCalendar"))?.takeIf { min -> min.after(minFeasibleDate) } ?: minFeasibleDate it.maxDateCalendar = DateUtils.restoreCalendar(arguments?.getString("maxDateCalendar"))?.takeIf { max -> max.before(maxFeasibleDate) } ?: maxFeasibleDate arguments?.getStringArrayList("disabledDaysList")?.run { it.disabledDaysList = map { list -> DateUtils.restoreCalendar(list)!! } } it.pickType = internalPickType it.pickedSingleDayCalendar = DateUtils.restoreCalendar(arguments?.getString("pickedSingleDayCalendar")) it.pickedRangeStartCalendar = DateUtils.restoreCalendar(arguments?.getString("pickedRangeStartCalendar")) it.pickedRangeEndCalendar = DateUtils.restoreCalendar(arguments?.getString("pickedRangeEndCalendar")) arguments?.getStringArrayList("pickedMultipleDaysList")?.run { it.pickedMultipleDaysList = map { list -> DateUtils.restoreCalendar(list)!! } } it.applyTheme(themeFactory) } } initActionBar() initSelectionBar() calendarView.onDayPickedListener = this@PrimeDatePickerImpl calendarView.onMonthLabelClickListener = this@PrimeDatePickerImpl calendarView.goto(initialDateCalendar) } } internal fun onResume() { // To be sure of calendar view state restoration is done. with(rootView) { fab.isExpanded = false if (calendarView.pickType != PickType.NOTHING) { internalPickType = calendarView.pickType when (internalPickType) { PickType.RANGE_START, PickType.RANGE_END -> { (selectionBarView as RangeDaysSelectionBarView).run { pickType = internalPickType } } else -> { } } } } } private fun handleOnPositiveButtonClick(calendarView: PrimeCalendarView) { when (calendarView.pickType) { PickType.SINGLE -> { if (calendarView.pickedSingleDayCalendar == null) { toast(context.forceLocaleStrings(locale, R.string.no_day_is_selected)[0]) } else { (onDayPickCallback as? SingleDayPickCallback)?.onSingleDayPicked( calendarView.pickedSingleDayCalendar!! ) onDismiss?.invoke() } } PickType.RANGE_START, PickType.RANGE_END -> { if (calendarView.pickedRangeStartCalendar == null || calendarView.pickedRangeEndCalendar == null) { toast(context.forceLocaleStrings(locale, R.string.no_range_is_selected)[0]) } else { (onDayPickCallback as? RangeDaysPickCallback)?.onRangeDaysPicked( calendarView.pickedRangeStartCalendar!!, calendarView.pickedRangeEndCalendar!! ) onDismiss?.invoke() } } PickType.MULTIPLE -> { if (calendarView.pickedMultipleDaysList.isEmpty()) { toast(context.forceLocaleStrings(locale, R.string.no_day_is_selected)[0]) } else { (onDayPickCallback as? MultipleDaysPickCallback)?.onMultipleDaysPicked( calendarView.pickedMultipleDaysList ) onDismiss?.invoke() } } PickType.NOTHING -> { } } } private fun initActionBar() { with(rootView) { ActionBarView(actionBarViewStub, direction).also { it.locale = locale it.typeface = typeface it.onTodayButtonClick = { initialDateCalendar.clone().also { calendar -> calendar.timeInMillis = System.currentTimeMillis() }.let { calendar -> calendarView.goto(calendar, true) } } it.onPositiveButtonClick = { handleOnPositiveButtonClick(calendarView) } it.onNegativeButtonClick = { onDismiss?.invoke() } it.applyTheme(themeFactory) } } } private fun initSelectionBar() { when (pickType) { PickType.SINGLE -> initSelectionBarSingle(typeface) PickType.RANGE_START, PickType.RANGE_END -> initSelectionBarRange(typeface) PickType.MULTIPLE -> initSelectionBarMultiple(typeface) PickType.NOTHING -> { } } with(rootView) { ImageViewCompat.setImageTintList( selectionBarBackgroundImageView, ColorStateList.valueOf(themeFactory.selectionBarBackgroundColor) ) } } private fun initSelectionBarSingle(typeface: Typeface?) { with(rootView) { selectionBarView = SingleDaySelectionBarView(selectionBarViewStub).also { it.applyTheme(themeFactory) it.locale = locale it.typeface = typeface it.pickedDay = calendarView.pickedSingleDayCalendar it.onPickedDayClickListener = { calendarView.pickedSingleDayCalendar?.let { day -> day.firstDayOfWeek = initialDateCalendar.firstDayOfWeek calendarView.focusOnDay(day) } } } } } private fun initSelectionBarRange(typeface: Typeface?) { with(rootView) { selectionBarView = RangeDaysSelectionBarView(selectionBarViewStub, direction).also { it.applyTheme(themeFactory) it.locale = locale it.typeface = typeface it.pickType = calendarView.pickType it.pickedRangeStartDay = calendarView.pickedRangeStartCalendar it.pickedRangeEndDay = calendarView.pickedRangeEndCalendar it.onRangeStartClickListener = { calendarView.pickType = PickType.RANGE_START calendarView.pickedRangeStartCalendar?.let { day -> day.firstDayOfWeek = initialDateCalendar.firstDayOfWeek calendarView.goto(day, true) } } it.onRangeEndClickListener = { calendarView.pickType = PickType.RANGE_END calendarView.pickedRangeEndCalendar?.let { day -> day.firstDayOfWeek = initialDateCalendar.firstDayOfWeek calendarView.goto(day, true) } } } } } private fun initSelectionBarMultiple(typeface: Typeface?) { with(rootView) { selectionBarView = MultipleDaysSelectionBarView(selectionBarViewStub, direction, coroutineScope).also { it.applyTheme(themeFactory) it.locale = locale it.typeface = typeface it.onPickedDayClickListener = { day -> day.firstDayOfWeek = initialDateCalendar.firstDayOfWeek calendarView.focusOnDay(day) } it.pickedDays = calendarView?.pickedMultipleDaysList } } } override fun onDayPicked( pickType: PickType, singleDay: PrimeCalendar?, startDay: PrimeCalendar?, endDay: PrimeCalendar?, multipleDays: List<PrimeCalendar> ) { when (pickType) { PickType.SINGLE -> { (selectionBarView as SingleDaySelectionBarView).pickedDay = singleDay } PickType.RANGE_START, PickType.RANGE_END -> { (selectionBarView as RangeDaysSelectionBarView).let { it.pickedRangeStartDay = startDay it.pickedRangeEndDay = endDay if (autoSelectPickEndDay && pickType == PickType.RANGE_START && endDay == null) { it.animateBackground(false) it.onRangeEndClickListener?.invoke() } } } PickType.MULTIPLE -> { (selectionBarView as MultipleDaysSelectionBarView).pickedDays = multipleDays } PickType.NOTHING -> { } } onDayPickedListener?.onDayPicked(pickType, singleDay, startDay, endDay, multipleDays) } override fun onMonthLabelClicked(calendar: PrimeCalendar, touchedX: Int, touchedY: Int) { with(rootView) { fun expandGoto(isExpanded: Boolean, touchedX: Int, touchedY: Int) { if (isExpanded) { (fab.layoutParams as CoordinatorLayout.LayoutParams).apply { leftMargin = touchedX topMargin = touchedY } } fab.post { fab.isExpanded = isExpanded } } if (gotoView == null) { gotoView = GotoView(gotoViewStub, direction).also { it.typeface = typeface it.minDateCalendar = calendarView.minDateCalendar it.maxDateCalendar = calendarView.maxDateCalendar it.applyTheme(themeFactory) } } (gotoView as? GotoView)?.also { it.calendar = calendar it.onCloseClickListener = { expandGoto(false, touchedX, touchedY) } it.onGoClickListener = { year, month -> expandGoto(false, touchedX, touchedY) postDelayed({ initialDateCalendar.clone().let { calendar -> calendar.year = year calendar.month = month calendarView.goto(calendar, true) } }, 250) } } expandGoto(true, touchedX, touchedY) } } internal fun onCancel(dialog: DialogInterface) { onCancelListener?.onCancel(dialog) } internal fun onDismiss(dialog: DialogInterface) { onDismissListener?.onDismiss(dialog) onCancelListener = null onDismissListener = null onDayPickCallback = null onDayPickedListener = null onDismiss = null } override fun show(manager: FragmentManager, tag: String?) { // do nothing! } override fun setOnCancelListener(listener: DialogInterface.OnCancelListener?) { onCancelListener = listener } override fun setOnDismissListener(listener: DialogInterface.OnDismissListener?) { onDismissListener = listener } override fun setDayPickCallback(callback: BaseDayPickCallback?) { onDayPickCallback = callback } override fun setOnEachDayPickedListener(listener: OnDayPickedListener?) { onDayPickedListener = listener } private fun toast(text: String) = Toast.makeText(context, text, Toast.LENGTH_SHORT).show() }
23
null
45
427
9ad06c7010963b25943121ef97eab7463db3cdfa
17,569
PrimeDatePicker
Apache License 2.0
app/src/main/java/com/jonareas/rentapp/data/model/Department.kt
soymegh
434,097,806
false
null
package com.jonareas.rentapp.data.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "department") data class Department ( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "department_id") val departmentId: Int = 0, @ColumnInfo(name = "departmentName") val departmentName : String ) : Persistable
0
Kotlin
0
0
6fa758b84bece723d05546cebcf65449dcc9aaaf
391
NewRentApp
MIT License