path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/kotlin/_50to100/Task79Test.kt
embuc
735,933,359
false
{"Kotlin": 136592, "Java": 79261}
package _50to100 import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import se.embuc._50to100.Task79 class Task79Test { @Test fun solve() { assertEquals("73162890", Task79().solve()) assertEquals("73162890", JTask79().solve()) } }
0
Kotlin
0
1
74af4e8537be183d43fa26d1a08032d7785ab862
275
projecteuler
MIT License
src/test/kotlin/no/nav/tiltaksarrangor/controller/TiltaksarrangorControllerTest.kt
navikt
616,496,742
false
null
package no.nav.tiltaksarrangor.controller import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import no.nav.tiltaksarrangor.IntegrationTest import no.nav.tiltaksarrangor.ingest.model.AnsattRolle import no.nav.tiltaksarrangor.ingest.model.EndringsmeldingType import no.nav.tiltaksarrangor.ingest.model.Innhold import no.nav.tiltaksarrangor.model.DeltakerStatusAarsak import no.nav.tiltaksarrangor.model.StatusType import no.nav.tiltaksarrangor.model.Veiledertype import no.nav.tiltaksarrangor.repositories.AnsattRepository import no.nav.tiltaksarrangor.repositories.ArrangorRepository import no.nav.tiltaksarrangor.repositories.DeltakerRepository import no.nav.tiltaksarrangor.repositories.DeltakerlisteRepository import no.nav.tiltaksarrangor.repositories.EndringsmeldingRepository import no.nav.tiltaksarrangor.repositories.model.AnsattDbo import no.nav.tiltaksarrangor.repositories.model.AnsattRolleDbo import no.nav.tiltaksarrangor.repositories.model.ArrangorDbo import no.nav.tiltaksarrangor.repositories.model.EndringsmeldingDbo import no.nav.tiltaksarrangor.repositories.model.VeilederDeltakerDbo import no.nav.tiltaksarrangor.testutils.getDeltaker import no.nav.tiltaksarrangor.testutils.getDeltakerliste import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import java.time.LocalDate import java.util.UUID class TiltaksarrangorControllerTest : IntegrationTest() { private val template = NamedParameterJdbcTemplate(postgresDataSource) private val ansattRepository = AnsattRepository(template) private val deltakerRepository = DeltakerRepository(template) private val deltakerlisteRepository = DeltakerlisteRepository(template, deltakerRepository) private val endringsmeldingRepository = EndringsmeldingRepository(template) private val arrangorRepository = ArrangorRepository(template) @AfterEach internal fun tearDown() { mockAmtTiltakServer.resetHttpServer() mockAmtArrangorServer.resetHttpServer() cleanDatabase() } @Test fun `getMineRoller - ikke autentisert - returnerer 401`() { val response = sendRequest( method = "GET", path = "/tiltaksarrangor/meg/roller" ) response.code shouldBe 401 } @Test fun `getMineRoller - autentisert - returnerer 200`() { val personIdent = "12345678910" mockAmtArrangorServer.addAnsattResponse(personIdent = personIdent) val response = sendRequest( method = "GET", path = "/tiltaksarrangor/meg/roller", headers = mapOf("Authorization" to "Bearer ${getTokenxToken(fnr = personIdent)}") ) response.code shouldBe 200 response.body?.string() shouldBe "[\"KOORDINATOR\",\"VEILEDER\"]" } @Test fun `getDeltaker - ikke autentisert - returnerer 401`() { val response = sendRequest( method = "GET", path = "/tiltaksarrangor/deltaker/${UUID.randomUUID()}" ) response.code shouldBe 401 } @Test fun `getDeltaker - autentisert, har ikke tilgang - returnerer 403`() { val personIdent = "12345678910" val arrangorId = UUID.randomUUID() arrangorRepository.insertOrUpdateArrangor( ArrangorDbo( id = arrangorId, navn = "Orgnavn", organisasjonsnummer = "orgnummer", overordnetArrangorId = null ) ) val deltakerliste = getDeltakerliste(arrangorId) deltakerlisteRepository.insertOrUpdateDeltakerliste(deltakerliste) val deltakerId = UUID.randomUUID() deltakerRepository.insertOrUpdateDeltaker(getDeltaker(deltakerId, deltakerliste.id)) ansattRepository.insertOrUpdateAnsatt( AnsattDbo( id = UUID.randomUUID(), personIdent = personIdent, fornavn = "Fornavn", mellomnavn = null, etternavn = "Etternavn", roller = listOf( AnsattRolleDbo(UUID.randomUUID(), AnsattRolle.KOORDINATOR) ), deltakerlister = emptyList(), veilederDeltakere = emptyList() ) ) val response = sendRequest( method = "GET", path = "/tiltaksarrangor/deltaker/$deltakerId", headers = mapOf("Authorization" to "Bearer ${getTokenxToken(fnr = personIdent)}") ) response.code shouldBe 403 } @Test fun `getDeltaker - autentisert, har tilgang - returnerer 200`() { val personIdent = "12345678910" val arrangorId = UUID.randomUUID() arrangorRepository.insertOrUpdateArrangor( ArrangorDbo( id = arrangorId, navn = "Orgnavn", organisasjonsnummer = "orgnummer", overordnetArrangorId = null ) ) val deltakerliste = getDeltakerliste(arrangorId).copy( id = UUID.fromString("9987432c-e336-4b3b-b73e-b7c781a0823a"), startDato = LocalDate.of(2023, 2, 1) ) deltakerlisteRepository.insertOrUpdateDeltakerliste(deltakerliste) val deltakerId = UUID.fromString("977350f2-d6a5-49bb-a3a0-773f25f863d9") val deltaker = getDeltaker(deltakerId, deltakerliste.id).copy( personident = "10987654321", telefonnummer = "90909090", epost = "<EMAIL>", status = StatusType.DELTAR, statusOpprettetDato = LocalDate.of(2023, 2, 1).atStartOfDay(), startdato = LocalDate.of(2023, 2, 1), dagerPerUke = 2.5f, innsoktDato = LocalDate.of(2023, 1, 15), bestillingstekst = "Tror deltakeren vil ha nytte av dette", navKontor = "<NAME>", navVeilederId = UUID.randomUUID(), navVeilederNavn = "Veileder Veiledersen", navVeilederTelefon = "56565656", navVeilederEpost = "<EMAIL>" ) deltakerRepository.insertOrUpdateDeltaker(deltaker) val endringsmeldinger = getAktiveEndringsmeldinger(deltakerId) endringsmeldinger.forEach { endringsmeldingRepository.insertOrUpdateEndringsmelding(it) } ansattRepository.insertOrUpdateAnsatt( AnsattDbo( id = UUID.fromString("2d5fc2f7-a9e6-4830-a987-4ff135a70c10"), personIdent = personIdent, fornavn = "Fornavn", mellomnavn = null, etternavn = "Etternavn", roller = listOf( AnsattRolleDbo(arrangorId, AnsattRolle.VEILEDER) ), deltakerlister = emptyList(), veilederDeltakere = listOf(VeilederDeltakerDbo(deltakerId, Veiledertype.VEILEDER)) ) ) ansattRepository.insertOrUpdateAnsatt( AnsattDbo( id = UUID.fromString("7c43b43b-43be-4d4b-8057-d907c5f1e5c5"), personIdent = UUID.randomUUID().toString(), fornavn = "Per", mellomnavn = null, etternavn = "Person", roller = listOf( AnsattRolleDbo(arrangorId, AnsattRolle.VEILEDER) ), deltakerlister = emptyList(), veilederDeltakere = listOf(VeilederDeltakerDbo(deltakerId, Veiledertype.MEDVEILEDER)) ) ) val response = sendRequest( method = "GET", path = "/tiltaksarrangor/deltaker/$deltakerId", headers = mapOf("Authorization" to "Bearer ${getTokenxToken(fnr = personIdent)}") ) val expectedJson = """ {"id":"977350f2-d6a5-49bb-a3a0-773f25f863d9","deltakerliste":{"id":"9987432c-e336-4b3b-b73e-b7c781a0823a","startDato":"2023-02-01","sluttDato":null,"erKurs":false},"fornavn":"Fornavn","mellomnavn":null,"etternavn":"Etternavn","fodselsnummer":"10987654321","telefonnummer":"90909090","epost":"<EMAIL>","status":{"type":"DELTAR","endretDato":"2023-02-01T00:00:00"},"startDato":"2023-02-01","sluttDato":null,"deltakelseProsent":null,"dagerPerUke":2.5,"soktInnPa":"Gjennomføring 1","soktInnDato":"2023-01-15T00:00:00","tiltakskode":"ARBFORB","bestillingTekst":"Tror deltakeren vil ha nytte av dette","fjernesDato":null,"navInformasjon":{"navkontor":"<NAME>","navVeileder":{"navn":"Veileder Veiledersen","epost":"<EMAIL>","telefon":"56565656"}},"veiledere":[{"ansattId":"2d5fc2f7-a9e6-4830-a987-4ff135a70c10","deltakerId":"977350f2-d6a5-49bb-a3a0-773f25f863d9","veiledertype":"VEILEDER","fornavn":"Fornavn","mellomnavn":null,"etternavn":"Etternavn"},{"ansattId":"7c43b43b-43be-4d4b-8057-d907c5f1e5c5","deltakerId":"977350f2-d6a5-49bb-a3a0-773f25f863d9","veiledertype":"MEDVEILEDER","fornavn":"Per","mellomnavn":null,"etternavn":"Person"}],"aktiveEndringsmeldinger":[{"id":"27446cc8-30ad-4030-94e3-de438c2af3c6","innhold":{"sluttdato":"2023-03-30","aarsak":{"type":"SYK","beskrivelse":"har blitt syk"}},"type":"AVSLUTT_DELTAKELSE"},{"id":"5029689f-3de6-4d97-9cfa-552f75625ef2","innhold":null,"type":"DELTAKER_ER_AKTUELL"},{"id":"362c7fdd-04e7-4f43-9e56-0939585856eb","innhold":{"sluttdato":"2023-05-03"},"type":"ENDRE_SLUTTDATO"}]} """.trimIndent() response.code shouldBe 200 response.body?.string() shouldBe expectedJson } @Test fun `fjernDeltaker - ikke autentisert - returnerer 401`() { val response = sendRequest( method = "DELETE", path = "/tiltaksarrangor/deltaker/${UUID.randomUUID()}" ) response.code shouldBe 401 } @Test fun `fjernDeltaker - autentisert - returnerer 200`() { val deltakerId = UUID.fromString("27446cc8-30ad-4030-94e3-de438c2af3c6") val personIdent = "12345678910" val arrangorId = UUID.randomUUID() arrangorRepository.insertOrUpdateArrangor( ArrangorDbo( id = arrangorId, navn = "Orgnavn", organisasjonsnummer = "orgnummer", overordnetArrangorId = null ) ) val deltakerliste = getDeltakerliste(arrangorId).copy( id = UUID.fromString("9987432c-e336-4b3b-b73e-b7c781a0823a"), startDato = LocalDate.of(2023, 2, 1) ) deltakerlisteRepository.insertOrUpdateDeltakerliste(deltakerliste) val deltaker = getDeltaker(deltakerId, deltakerliste.id).copy( personident = "10987654321", status = StatusType.HAR_SLUTTET, statusOpprettetDato = LocalDate.of(2023, 2, 1).atStartOfDay() ) deltakerRepository.insertOrUpdateDeltaker(deltaker) val ansattId = UUID.randomUUID() ansattRepository.insertOrUpdateAnsatt( AnsattDbo( id = ansattId, personIdent = personIdent, fornavn = "Fornavn", mellomnavn = null, etternavn = "Etternavn", roller = listOf( AnsattRolleDbo(arrangorId, AnsattRolle.VEILEDER) ), deltakerlister = emptyList(), veilederDeltakere = listOf(VeilederDeltakerDbo(deltakerId, Veiledertype.VEILEDER)) ) ) mockAmtTiltakServer.addSkjulDeltakerResponse(deltakerId) val response = sendRequest( method = "DELETE", path = "/tiltaksarrangor/deltaker/$deltakerId", headers = mapOf("Authorization" to "Bearer ${getTokenxToken(fnr = personIdent)}") ) response.code shouldBe 200 val deltakerFraDb = deltakerRepository.getDeltaker(deltakerId) deltakerFraDb?.skjultAvAnsattId shouldBe ansattId deltakerFraDb?.skjultDato shouldNotBe null } private fun getAktiveEndringsmeldinger(deltakerId: UUID): List<EndringsmeldingDbo> { return listOf( EndringsmeldingDbo( id = UUID.fromString("27446cc8-30ad-4030-94e3-de438c2af3c6"), deltakerId = deltakerId, innhold = Innhold.AvsluttDeltakelseInnhold( sluttdato = LocalDate.of(2023, 3, 30), aarsak = DeltakerStatusAarsak( type = DeltakerStatusAarsak.Type.SYK, beskrivelse = "har blitt syk" ) ), type = EndringsmeldingType.AVSLUTT_DELTAKELSE ), EndringsmeldingDbo( id = UUID.fromString("5029689f-3de6-4d97-9cfa-552f75625ef2"), deltakerId = deltakerId, innhold = Innhold.DeltakerErAktuellInnhold(), type = EndringsmeldingType.DELTAKER_ER_AKTUELL ), EndringsmeldingDbo( id = UUID.fromString("362c7fdd-04e7-4f43-9e56-0939585856eb"), deltakerId = deltakerId, innhold = Innhold.EndreSluttdatoInnhold( sluttdato = LocalDate.of(2023, 5, 3) ), type = EndringsmeldingType.ENDRE_SLUTTDATO ) ) } }
5
Kotlin
0
2
c2c1c9501375018b40ef0ac94baf44570b1f37c9
11,242
amt-tiltaksarrangor-bff
MIT License
core/src/commonMain/kotlin/work/socialhub/kmastodon/api/BlocksResource.kt
uakihir0
783,390,459
false
{"Kotlin": 167667, "Ruby": 2191, "Shell": 2164, "Makefile": 319}
package work.socialhub.kmastodon.api import work.socialhub.kmastodon.api.request.blocks.BlocksBlocksRequest import work.socialhub.kmastodon.api.response.Response import work.socialhub.kmastodon.api.response.blocks.BlocksBlocksResponse import kotlin.js.JsExport @JsExport interface BlocksResource { /** * Fetching a user's blocks. */ fun blocks( request: BlocksBlocksRequest ): Response<Array<BlocksBlocksResponse>> }
0
Kotlin
0
1
8d3278cff7a164cbe9e9ad978a9b28e743d1c96d
451
kmastodon
MIT License
src/main/kotlin/no/nav/dagpenger/iverksett/utbetaling/tilstand/IverksettingsresultatService.kt
navikt
611,752,955
false
{"Kotlin": 322143, "Gherkin": 57891, "Shell": 626, "Dockerfile": 121}
package no.nav.dagpenger.iverksett.utbetaling.tilstand import no.nav.dagpenger.iverksett.utbetaling.domene.Iverksettingsresultat import no.nav.dagpenger.iverksett.utbetaling.domene.OppdragResultat import no.nav.dagpenger.iverksett.utbetaling.domene.TilkjentYtelse import no.nav.dagpenger.kontrakter.felles.Fagsystem import no.nav.dagpenger.kontrakter.felles.GeneriskId import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import java.util.UUID @Service class IverksettingsresultatService(private val iverksettingsresultatRepository: IverksettingsresultatRepository) { fun opprettTomtResultat( fagsystem: Fagsystem, sakId: GeneriskId, behandlingId: UUID, iverksettingId: String?, ) { iverksettingsresultatRepository.insert(Iverksettingsresultat(fagsystem, sakId, behandlingId, iverksettingId)) } @Transactional(propagation = Propagation.REQUIRES_NEW) fun oppdaterTilkjentYtelseForUtbetaling( fagsystem: Fagsystem, sakId: GeneriskId, behandlingId: UUID, tilkjentYtelseForUtbetaling: TilkjentYtelse, iverksettingId: String?, ) { val iverksettResultat = iverksettingsresultatRepository.findByIdOrThrow(fagsystem, sakId, behandlingId, iverksettingId) iverksettingsresultatRepository.update(iverksettResultat.copy(tilkjentYtelseForUtbetaling = tilkjentYtelseForUtbetaling)) } @Transactional(propagation = Propagation.REQUIRES_NEW) fun oppdaterOppdragResultat( fagsystem: Fagsystem, sakId: GeneriskId, behandlingId: UUID, oppdragResultat: OppdragResultat, iverksettingId: String?, ) { val iverksettResultat = iverksettingsresultatRepository.findByIdOrThrow(fagsystem, sakId, behandlingId, iverksettingId) iverksettingsresultatRepository.update(iverksettResultat.copy(oppdragResultat = oppdragResultat)) } fun hentTilkjentYtelse( fagsystem: Fagsystem, sakId: GeneriskId, behandlingId: UUID, iverksettingId: String?, ): TilkjentYtelse? { return iverksettingsresultatRepository.findByIdOrNull(fagsystem, sakId, behandlingId, iverksettingId)?.tilkjentYtelseForUtbetaling } fun hentIverksettingsresultat( fagsystem: Fagsystem, sakId: GeneriskId, behandlingId: UUID, iverksettingId: String?, ): Iverksettingsresultat? { return iverksettingsresultatRepository.findByIdOrNull(fagsystem, sakId, behandlingId, iverksettingId) } }
1
Kotlin
1
0
e22bac4134604455dec0f70a6f3d5e9fe78391d6
2,638
dp-iverksett
MIT License
libraries/stdlib/src/kotlin/reflect/typeOf.kt
dotlin-org
434,960,829
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. * Copyright 2021-2022 Wilko Manger * * 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 kotlin.reflect /** * Returns a runtime representation of the given reified type [T] as an instance of [KType]. */ @SinceKotlin("1.6") inline fun <reified T> typeOf(): KType = throw UnsupportedOperationException("This function is implemented as an intrinsic on all supported platforms.")
0
Kotlin
0
30
633430bfa0786923bde86d9068323f18eb5c24d5
940
dotlin
Apache License 2.0
buildSrc/src/Dependencies.kt
ye-yu
283,407,597
false
{"Gradle Kotlin DSL": 4, "Gradle": 1, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "JSON": 3, "Java": 14, "Kotlin": 63}
object Jetbrains { private const val annotationsVersion = "17.0.0" const val annotations = "org.jetbrains:annotations:$annotationsVersion" object Kotlin { const val version = "1.3.72" const val stdLib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$version" const val reflect = "org.jetbrains.kotlin:kotlin-reflect:$version" } object Kotlinx { const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.7" const val serialization = "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0" } } object Mods { const val modmenu = "io.github.prospector:modmenu:1.14.5+build.+" } object Fabric { object Kotlin { const val version = "${Jetbrains.Kotlin.version}+build.+" } object Loader { const val version = "0.9.0+build.204" // https://maven.fabricmc.net/net/fabricmc/fabric-loader/ } object API { const val version = "0.16.0+build.384-1.16.1" } object Loom { const val version = "0.4-SNAPSHOT" } object YarnMappings { const val version = "${Minecraft.version}+build.21" } } object Minecraft { const val version = "1.16.1" } object CurseGradle { const val version = "1.4.0" }
1
null
1
1
99309d74839a9470e7940e6edc9c80087bb5abad
1,254
fabric-kotlin-mod-template
MIT License
app/src/main/java/com/hfut/schedule/ViewModel/LoginSuccessViewModel.kt
Chiu-xaH
705,508,343
false
{"Kotlin": 1439177, "HTML": 77257, "Java": 686}
package com.hfut.schedule.ViewModel //import com.hfut.schedule.logic.network.ServiceCreator.Login.OneGetNewTicketServiceCreator.client import android.annotation.SuppressLint import android.os.Build import android.util.Base64 import android.util.Log import androidx.annotation.RequiresApi import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonPrimitive import com.hfut.schedule.logic.Enums.LibraryItems import com.hfut.schedule.logic.utils.SharePrefs.prefs import com.hfut.schedule.logic.datamodel.Jxglstu.lessonResponse import com.hfut.schedule.logic.datamodel.One.BorrowBooksResponse import com.hfut.schedule.logic.datamodel.One.SubBooksResponse import com.hfut.schedule.logic.datamodel.One.getTokenResponse import com.hfut.schedule.logic.datamodel.zjgd.FeeType import com.hfut.schedule.logic.datamodel.zjgd.FeeType.* import com.hfut.schedule.logic.network.ServiceCreator.CommunitySreviceCreator import com.hfut.schedule.logic.network.ServiceCreator.JwglappServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.Jxglstu.JxglstuHTMLServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.Jxglstu.JxglstuJSONServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.Jxglstu.JxglstuSurveyServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.LePaoYunServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.Login.LoginServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.NewsServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.One.OneServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.OneGotoServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.SearchEleServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.XuanquServiceCreator import com.hfut.schedule.logic.network.ServiceCreator.ZJGDBillServiceCreator import com.hfut.schedule.logic.network.api.CommunityService import com.hfut.schedule.logic.network.api.FWDTService import com.hfut.schedule.logic.network.api.JwglappService import com.hfut.schedule.logic.network.api.JxglstuService import com.hfut.schedule.logic.network.api.LePaoYunService import com.hfut.schedule.logic.network.api.LoginService import com.hfut.schedule.logic.network.api.NewsService import com.hfut.schedule.logic.network.api.OneService import com.hfut.schedule.logic.network.api.XuanquService import com.hfut.schedule.logic.network.api.ZJGDBillService import com.hfut.schedule.logic.utils.SharePrefs.Save import com.hfut.schedule.logic.network.api.ServerService import com.hfut.schedule.logic.network.ServiceCreator.ServerServiceCreator import com.hfut.schedule.logic.utils.SharePrefs.SaveInt import com.hfut.schedule.ui.Activity.success.cube.Settings.Items.getUserInfo import com.hfut.schedule.ui.Activity.success.search.Search.Transfer.CampusId import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response class LoginSuccessViewModelFactory(private val webVpn: Boolean) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(LoginSuccessViewModel::class.java)) { return LoginSuccessViewModel(webVpn) as T } throw IllegalArgumentException("Unknown ViewModel class") } } class LoginSuccessViewModel(webVpn : Boolean) : ViewModel() { private val JxglstuJSON = JxglstuJSONServiceCreator.create(JxglstuService::class.java,webVpn) private val JxglstuHTML = JxglstuHTMLServiceCreator.create(JxglstuService::class.java,webVpn) private val OneGoto = OneGotoServiceCreator.create(LoginService::class.java) private val One = OneServiceCreator.create(OneService::class.java) private val ZJGDBill = ZJGDBillServiceCreator.create(ZJGDBillService::class.java) private val Xuanqu = XuanquServiceCreator.create(XuanquService::class.java) private val LePaoYun = LePaoYunServiceCreator.create(LePaoYunService::class.java) private val searchEle = SearchEleServiceCreator.create(FWDTService::class.java) private val CommunityLogin = LoginServiceCreator.create(CommunityService::class.java) private val JwglappLogin = JwglappServiceCreator.create(JwglappService::class.java) private val Community = CommunitySreviceCreator.create(CommunityService::class.java) private val Jwglapp = JwglappServiceCreator.create(JwglappService::class.java) private val News = NewsServiceCreator.create(NewsService::class.java) private val JxglstuSurvey = JxglstuSurveyServiceCreator.create(JxglstuService::class.java,webVpn) private val server = ServerServiceCreator.create(ServerService::class.java) var studentId = MutableLiveData<Int>(prefs.getInt("STUDENTID",0)) var lessonIds = MutableLiveData<List<Int>>() var token = MutableLiveData<String>() var webVpn = webVpn //val newFocus = MutableLiveData<String>() fun getData() { val call = server.getData() call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("newFocus",response?.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } @RequiresApi(Build.VERSION_CODES.O) fun postUser() { val data = getUserInfo() val call = server.postUse( dateTime = data.dateTime, deviceName = data.deviceName ?: "空", appVersion = data.appVersionName, systemVersion = data.systemVersion, studentID = data.studentID ?: "空", user = data.name ?: "空") call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } @RequiresApi(Build.VERSION_CODES.O) fun feedBack(info : String,contact : String?) { val data = getUserInfo() val time = data.dateTime val version = data.appVersionName val name = data.name val call = server.feedBack( dateTime = time, appVersion = version, user = name ?: "空", info = info, contact = contact) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val verifyData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun verify(cookie: String) { val call = JxglstuJSON.verify(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { if (response.isSuccessful) { verifyData.value = response.code().toString() } else { verifyData.value = response.code().toString() Log.e("Error", "Response code: ${response.code()}") } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val selectCourseData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun getSelectCourse(cookie: String) { val call = prefs.getString("Username","2023XXXXXX")?.let { JxglstuJSON.getSelectCourse( it.substring(2,4), studentId.value.toString(), cookie) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { if (response.isSuccessful) { selectCourseData.value = response.body()?.string() } else { Log.e("Error", "Response code: ${response.code()}") } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val selectCourseInfoData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun getSelectCourseInfo(cookie: String,id : Int) { val call = JxglstuJSON.getSelectCourseInfo(id,cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { selectCourseInfoData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val stdCountData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun getSCount(cookie: String,id : Int) { val call = JxglstuJSON.getCount(id,cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { stdCountData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val requestIdData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun getRequestID(cookie: String,lessonId : String,courseId : String,type : String) { val call = JxglstuJSON.getRequestID(studentId.value.toString(),lessonId,courseId,cookie,type) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { requestIdData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val selectedData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun getSelectedCourse(cookie: String,courseId : String) { val call = JxglstuJSON.getSelectedCourse(studentId.value.toString(),courseId,cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { selectedData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val selectResultData = MutableLiveData<String?>() @SuppressLint("SuspiciousIndentation") fun postSelect(cookie: String,requestId : String) { val call = JxglstuJSON.postSelect(studentId.value.toString(), requestId,cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { selectResultData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val transferData = MutableLiveData<String?>() fun getTransfer(cookie: String,campus: CampusId) { val campusId = when(campus) { CampusId.XUANCHENG -> 3 CampusId.HEFEI -> 1 } val call = studentId.value?.let { JxglstuJSON.getTransfer(cookie,true, campusId, it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { transferData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val myApplyData = MutableLiveData<String?>() fun getMyApply(cookie: String,campus: CampusId) { val campusId = when(campus) { CampusId.XUANCHENG -> 3 CampusId.HEFEI -> 1 } val call = studentId.value?.let { JxglstuJSON.getMyTransfer(cookie, campusId, it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { myApplyData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val NewsData = MutableLiveData<String?>() fun searchNews(title : String) { val call = News.searchNews(1,title) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { NewsData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun GotoCommunity(cookie : String) { val call = CommunityLogin.LoginCommunity(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val LoginCommunityData = MutableLiveData<String?>() fun LoginCommunity(ticket : String) { val call = Community.Login(ticket) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { LoginCommunityData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getGrade(cookie: String,semester: Int?) { val call = JxglstuJSON.getGrade(cookie,studentId.value.toString(), semester) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("grade", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun Jxglstulogin(cookie : String) { val call = JxglstuJSON.jxglstulogin(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getStudentId(cookie : String) { val call = JxglstuJSON.getStudentId(cookie) //Log.d("web",webVpn.toString()) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { if (response.headers()["Location"].toString().contains("/eams5-student/for-std/course-table/info/")) { studentId.value = response.headers()["Location"].toString() .substringAfter("/eams5-student/for-std/course-table/info/").toInt() SaveInt("STUDENTID",studentId.value ?: 0) } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getLessonIds(cookie : String, bizTypeId : String,studentid : String) { //bizTypeId为年级数,例如23 //dataId为学生ID //semesterId为学期Id,例如23-24第一学期为234 val call = prefs.getString("semesterId","234") ?.let { JxglstuJSON.getLessonIds(cookie,bizTypeId, it,studentid) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val json = response.body()?.string() if (json != null) { val id = Gson().fromJson(json, lessonResponse::class.java) Save("courses",json) lessonIds.value = id.lessonIds } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val datumData = MutableLiveData<String?>() fun getDatum(cookie : String,lessonid: JsonObject) { val lessonIdsArray = JsonArray() lessonIds.value?.forEach {lessonIdsArray.add(JsonPrimitive(it))} val call = JxglstuJSON.getDatum(cookie,lessonid) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val body = response.body()?.string() datumData.value = body Save("json", body) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getInfo(cookie : String) { val call = JxglstuHTML.getInfo(cookie,studentId.value.toString()) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("info", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val ProgramData = MutableLiveData<String?>() fun getProgram(cookie: String) { val call = JxglstuJSON.getProgram(cookie,studentId.value.toString()) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val body = response.body()?.string() Save("program", body) ProgramData.value = body } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val ProgramCompletionData = MutableLiveData<String?>() fun getProgramCompletion(cookie: String) { val call = JxglstuJSON.getProgramCompletion(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val body = response.body()?.string() ProgramCompletionData.value = body } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val courseData = MutableLiveData<String?>() val courseRsponseData = MutableLiveData<String?>() fun searchCourse(cookie: String, className : String?,courseName : String?, semester : Int) { val call = JxglstuJSON.searchCourse(cookie,studentId.value.toString(),semester,className,"1,20",courseName) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { courseData.value = response?.code().toString() courseRsponseData.value = response?.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val surveyListData = MutableLiveData<String?>() fun getSurveyList(cookie: String, semester : Int) { val call = JxglstuJSON.getSurveyList(cookie,studentId.value.toString(),semester) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { surveyListData.value = response?.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val surveyData = MutableLiveData<String?>() fun getSurvey(cookie: String, id : String) { val call = JxglstuJSON.getSurveyInfo(cookie,id) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { surveyData.value = response?.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getSurveyToken(cookie: String, id : String) { val call = JxglstuJSON.getSurveyToken(cookie,id,"/for-std/lesson-survey/semester-index/${studentId.value}") call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { // Log.d("cookies",response?.headers().toString()) Save("SurveyCookie",response?.headers().toString().substringAfter("Set-Cookie:").substringBefore(";")) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val surveyPostData = MutableLiveData<String?>() fun postSurvey(cookie : String,json: JsonObject){ val call = JxglstuJSON.postSurvey(cookie,json) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { surveyPostData.value = response?.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } //val photo = MutableLiveData<ByteArray>() fun getPhoto(cookie : String){ val call = JxglstuJSON.getPhoto(cookie,studentId.value.toString()) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { //保存图片 // 将响应体转换为字节数组 try { val bytes = response.body()?.bytes() // 将字节数组转换为Base64编码的字符串 val base64String = Base64.encodeToString(bytes, Base64.DEFAULT) // 保存编码后的字符串 Save("photo",base64String) } catch (e : Exception) { } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun OneGoto(cookie : String) {// 创建一个Call对象,用于发送异步请求 val call = OneGoto.OneGoto(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun OneGotoCard(cookie : String) { val call = OneGoto.OneGotoCard(cookie) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {} override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val BillsData = MutableLiveData<String>() fun CardGet(auth : String,page : Int) {// 创建一个Call对象,用于发送异步请求 val size = prefs.getString("CardRequest","15") size?.let { Log.d("size", it) } val call = size?.let { ZJGDBill.Cardget(auth,page, it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { BillsData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val CardData = MutableLiveData<String?>() fun getyue(auth : String) { val call = ZJGDBill.getYue(auth) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val body = response.body()?.string() CardData.value = body Save("cardyue",body ) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val infoValue = MutableLiveData<String?>() fun getFee(auth: String,type : FeeType,level : String? = null,room : String? = null) { val feeitemid = when(type) { WEB -> "281" ELECTRIC -> "261" } val levels = when(type) { WEB -> "0" ELECTRIC -> null } val rooms = when(type) { WEB -> null ELECTRIC -> room } val call = ZJGDBill.getFee(auth, IEC = "IEC", typeId = feeitemid, room = rooms, level = levels) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val responseBody = response?.body()?.string() when(type) { WEB -> infoValue.value = responseBody ELECTRIC -> ElectricData.value = responseBody } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val orderIdData = MutableLiveData<String?>() fun payStep1(auth: String,json: String,pay : Int) { val call = ZJGDBill.pay( auth = auth, pay = pay, flag = "choose", paystep = 0, json = json, typeId = 261, isWX = null, orderid = null, password = <PASSWORD>, paytype = null, paytypeid = null, cardId = null ) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { orderIdData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val uuIdData = MutableLiveData<String?>() fun payStep2(auth: String,orderId : String) { val call = ZJGDBill.pay( auth = auth, pay = null, flag = null, paystep = 2, json = null, typeId = 261, isWX = null, orderid = orderId, password = <PASSWORD>, paytype = "CARDTSM", paytypeid = 101, cardId = null ) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { uuIdData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val payResultData = MutableLiveData<String?>() fun payStep3(auth: String,orderId : String,password : String,uuid : String) { val call = ZJGDBill.pay( auth = auth, pay = null, flag = null, paystep = 2, json = null, typeId = 261, isWX = 0, orderid = orderId, password = <PASSWORD>, paytype = "<PASSWORD>", paytypeid = 101, cardId = uuid ) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { payResultData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun changeLimit(auth: String,json: JsonObject) { val call = ZJGDBill.changeLimit(auth,json) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("changeResult", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } var RangeData = MutableLiveData<String>() fun searchDate(auth : String, timeFrom : String, timeTo : String) { val call = ZJGDBill.searchDate(auth,timeFrom,timeTo) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { RangeData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val SearchBillsData = MutableLiveData<String>() fun searchBills(auth : String, info: String,page : Int) { val size = prefs.getString("CardRequest","15") size?.let { Log.d("size", it) } val call = size?.let { ZJGDBill.searchBills(auth,info,page, it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { SearchBillsData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } var MonthData = MutableLiveData<String?>() fun getMonthBills(auth : String, dateStr: String) { val call = ZJGDBill.getMonthYue(auth,dateStr) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { MonthData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getToken() { val codehttp = prefs.getString("code", "") var code = codehttp if (code != null) { code = code.substringAfter("=") } if (code != null) { code = code.substringBefore("]") } val http = codehttp?.substringAfter("[")?.substringBefore("]") val call = http?.let { code?.let { it1 -> One.getToken(it, it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val json = response.body()?.string() val data = Gson().fromJson(json, getTokenResponse::class.java) if (data.msg == "success") { token.value = data.data.access_token Save("bearer", data.data.access_token) } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val ElectricData = MutableLiveData<String?>() fun searchEle(jsondata : String) { val call = searchEle.searchEle(jsondata,"synjones.onecard.query.elec.roominfo",true) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { ElectricData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { ElectricData.value = "查询失败,是否连接了hfut-wlan?" t.printStackTrace() } }) } fun getBorrowBooks(token : String) { val call = One.getBorrowBooks(token) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val json = response.body()?.string() if (json.toString().contains("success")) { val data = Gson().fromJson(json, BorrowBooksResponse::class.java) val borrow = data.data.toString() Save("borrow",borrow) } else Save("borrow","未获取") } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun getSubBooks(token : String) { val call = One.getSubBooks(token) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val json = response.body()?.string() if (json.toString().contains("success")) { val data = Gson().fromJson(json, SubBooksResponse::class.java) val sub = data.data.toString() Save("sub", sub) } else Save("borrow","0") } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun searchEmptyRoom(building_code : String,token : String) { val call = One.searchEmptyRoom(building_code, "Bearer $token") call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("emptyjson", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val PayData = MutableLiveData<String?>() fun getPay() { val call = prefs.getString("Username","")?.let { One.getPay(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { PayData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val XuanquData = MutableLiveData<String>() fun SearchXuanqu(code : String) { val call = Xuanqu.SearchXuanqu(code) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { XuanquData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } fun LePaoYunHome(Yuntoken : String) { val call = LePaoYun.getLePaoYunHome(Yuntoken) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("LePaoYun", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } val FailRateData = MutableLiveData<String>() fun SearchFailRate(CommuityTOKEN : String,name: String,page : String) { val size = prefs.getString("FailRateRequest","15") //size?.let { Log.d("size", it) } val call = CommuityTOKEN?.let { size?.let { it1 -> Community.getFailRate(it,name,page, it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { FailRateData.value = response.body()?.string() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val ExamData = MutableLiveData<String?>() val ExamCodeData = MutableLiveData<Int>() fun Exam(CommuityTOKEN: String) { val call = CommuityTOKEN?.let { Community.getExam(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val responses = response.body()?.string() Save("Exam", responses) ExamData.value = responses ExamCodeData.value = response.code() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { ExamData.value = "错误" t.printStackTrace() } }) } } val examCode = MutableLiveData<Int>() fun getExamJXGLSTU(cookie: String) { val call = JxglstuJSON.getExam(cookie,studentId.value.toString()) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val code = response?.code() if(code == 200) { Save("examJXGLSTU", response.body()?.string()) } examCode.value = response?.code() } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } var GradeData = MutableLiveData<String?>() fun getGrade(CommuityTOKEN: String,year : String,term : String) { val call = CommuityTOKEN?.let { Community.getGrade(it,year,term) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val responses = response.body()?.string() Save("Grade",responses ) GradeData.value = responses } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { GradeData.value = "错误" t.printStackTrace() } }) } } fun getAvgGrade(CommuityTOKEN: String) { val call = CommuityTOKEN?.let { Community.getAvgGrade(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val responses = response.body()?.string() Save("Avg",responses ) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } fun getAllAvgGrade(CommuityTOKEN: String) { val call = CommuityTOKEN?.let { Community.getAllAvgGrade(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val responses = response.body()?.string() Save("AvgAll",responses ) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } val libraryData = MutableLiveData<String>() fun SearchBooks(CommuityTOKEN: String,name: String) { val size = prefs.getString("BookRequest","15") // size?.let { Log.d("size", it) } val call = CommuityTOKEN?.let { size?.let { it1 -> Community.searchBooks(it,name,"1", it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { libraryData.value = response.body()?.string() Save("Library", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { libraryData.value = "错误" t.printStackTrace() } }) } } fun GetCourse(CommuityTOKEN : String) { val call = CommuityTOKEN?.let { Community.getCourse(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("Course", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } fun GetBorrowed(CommuityTOKEN: String,page : String) { val size = prefs.getString("BookRequest","15") val call = CommuityTOKEN?.let { size?.let { it1 -> Community.getBorrowedBook(it,page, it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save(LibraryItems.BORROWED.name, response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } fun GetHistory(CommuityTOKEN: String,page : String) { val size = prefs.getString("BookRequest","15") val call = CommuityTOKEN?.let { size?.let { it1 -> Community.getHistoyBook(it,page, it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save(LibraryItems.HISTORY.name, response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } fun getOverDueBook(CommuityTOKEN: String,page : String) { val size = prefs.getString("BookRequest","15") val call = CommuityTOKEN?.let { size?.let { it1 -> Community.getOverDueBook(it,page, it1) } } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save(LibraryItems.OVERDUE.name, response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } fun getToday(CommuityTOKEN : String) { val call = CommuityTOKEN?.let { Community.getToday(it) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { Save("TodayNotice", response.body()?.string()) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } var lessonIdsNext = MutableLiveData<List<Int>>() fun getLessonIdsNext(cookie : String, bizTypeId : String,studentid : String) { //bizTypeId为年级数,例如23 //dataId为学生ID //semesterId为学期Id,例如23-24第一学期为234 val call = (prefs.getString("semesterId","234")?.toInt()?.plus(20)).toString() ?.let { JxglstuJSON.getLessonIds(cookie,bizTypeId, it,studentid) } if (call != null) { call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val json = response.body()?.string() if (json != null) { val id = Gson().fromJson(json, lessonResponse::class.java) Save("coursesNext",json) lessonIdsNext.value = id.lessonIds } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } } // val datumDataNext = MutableLiveData<String?>() fun getDatumNext(cookie : String,lessonid: JsonObject) { val lessonIdsArray = JsonArray() lessonIds.value?.forEach {lessonIdsArray.add(JsonPrimitive(it))} val call = JxglstuJSON.getDatum(cookie,lessonid) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { val body = response.body()?.string() // datumDataNext.value = body Save("jsonNext", body) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { t.printStackTrace() } }) } }
0
Kotlin
1
3
dd9406af7bdc0a5f3fa5b5b97fb1dd44aa9665e0
45,609
HFUT-Schedule
Apache License 2.0
library/src/main/java/top/zibin/luban/InputStreamAdapter.kt
ZJYZJY
288,158,029
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Markdown": 3, "Proguard": 2, "Java": 10, "XML": 15, "Kotlin": 9}
package top.zibin.luban import java.io.IOException import java.io.InputStream /** * Automatically close the previous InputStream when opening a new InputStream, * and finally need to manually call [.close] to release the resource. */ abstract class InputStreamAdapter : InputStreamProvider { private var inputStream: InputStream? = null @Throws(IOException::class) override fun open(): InputStream? { close() inputStream = openInternal() return inputStream } @Throws(IOException::class) abstract fun openInternal(): InputStream? override fun close() { try { inputStream?.close() } catch (ignore: IOException) { } finally { inputStream = null } } }
1
null
1
1
c3446ca8a7cc266d3273d51f7aa4aa88e33c5709
768
Luban
Apache License 2.0
kotlintest-extensions/kotlintest-extensions-koin/src/test/kotlin/com/sksamuel/kt/koin/KoinModule.kt
KyongSik-Yoon
165,618,517
true
{"Kotlin": 1467439, "Java": 5525, "Shell": 125}
package com.sksamuel.kt.koin import org.koin.dsl.module class GenericRepository { fun foo() = "Bar" } class GenericService( val repository: GenericRepository ) { fun foo() = repository.foo() } val koinModule = module { single { GenericService(get()) } single { GenericRepository() } }
0
Kotlin
0
1
211019bb3b3904e976203b91a1d79f5baa689ae5
305
kotlintest
Apache License 2.0
compiler/testData/diagnostics/tests/controlFlowAnalysis/initializationInLambda.kt
JakeWharton
99,388,807
true
null
// !DIAGNOSTICS: -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE fun ignoreIt(f: () -> Unit) {} fun exec(f: () -> Unit) = f() fun foo() { var x: Int ignoreIt() { // Ok x = 42 } // Error! <!UNINITIALIZED_VARIABLE!>x<!>.hashCode() } fun bar() { val x: Int exec { x = 13 } } fun bar2() { val x: Int fun foo() { x = 3 } foo() } class My(val cond: Boolean) { val y: Int init { val x: Int if (cond) { exec { } x = 1 } else { x = 2 } y = x } constructor(): this(false) { val x: Int x = 2 exec { x.hashCode() } } } class Your { val y = if (true) { val xx: Int exec { xx = 42 } 24 } else 0 } val z = if (true) { val xx: Int exec { xx = 24 } 42 } else 0
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
966
kotlin
Apache License 2.0
src/main/kotlin/org/jetbrains/plugins/feature/suggester/suggesters/UnwrapSuggester.kt
JetBrains
10,263,181
false
null
package training.featuresSuggester.suggesters import com.intellij.psi.PsiElement import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import training.featuresSuggester.* import training.featuresSuggester.actions.Action import training.featuresSuggester.actions.BeforeEditorTextRemovedAction class UnwrapSuggester : AbstractFeatureSuggester() { override val id: String = "Unwrap" override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("unwrap.name") override val message = FeatureSuggesterBundle.message("unwrap.message") override val suggestingActionId = "Unwrap" override val suggestingDocUrl = "https://www.jetbrains.com/help/idea/working-with-source-code.html#unwrap_remove_statement" override val minSuggestingIntervalDays = 14 override val languages = listOf("JAVA", "kotlin", "ECMAScript 6") private object State { var surroundingStatementStartOffset: Int = -1 var closeBraceOffset: Int = -1 var lastChangeTimeMillis: Long = 0L val isInitial: Boolean get() = surroundingStatementStartOffset == -1 && closeBraceOffset == -1 fun isOutOfDate(newChangeTimeMillis: Long): Boolean { return newChangeTimeMillis - lastChangeTimeMillis > MAX_TIME_MILLIS_BETWEEN_ACTIONS } fun reset() { surroundingStatementStartOffset = -1 closeBraceOffset = -1 lastChangeTimeMillis = 0L } } private val surroundingStatementStartRegex = Regex("""[ \n]*(if|for|while)[ \n]*\(.*\)[ \n]*\{[ \n]*""") override fun getSuggestion(action: Action): Suggestion { val language = action.language ?: return NoSuggestion val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion if (action is BeforeEditorTextRemovedAction) { val text = action.textFragment.text when { text == "}" -> return langSupport.handleCloseBraceDeleted(action) text.matches(surroundingStatementStartRegex) -> { return langSupport.handleStatementStartDeleted(action) } else -> State.reset() } } return NoSuggestion } private fun SuggesterSupport.handleCloseBraceDeleted(action: BeforeEditorTextRemovedAction): Suggestion { when { State.isInitial -> handleCloseBraceDeletedFirst(action) State.closeBraceOffset != -1 -> { try { if (State.checkCloseBraceDeleted(action)) return createSuggestion() } finally { State.reset() } } else -> State.reset() } return NoSuggestion } private fun SuggesterSupport.handleStatementStartDeleted(action: BeforeEditorTextRemovedAction): Suggestion { when { State.isInitial -> handleStatementStartDeletedFirst(action) State.surroundingStatementStartOffset != -1 -> { try { if (State.checkStatementStartDeleted(action)) return createSuggestion() } finally { State.reset() } } else -> State.reset() } return NoSuggestion } private fun SuggesterSupport.handleCloseBraceDeletedFirst(action: BeforeEditorTextRemovedAction) { val curElement = action.psiFile?.findElementAt(action.caretOffset) ?: return val codeBlock = curElement.parent if (!isCodeBlock(codeBlock)) return val statements = getStatements(codeBlock) if (statements.isNotEmpty()) { val statement = getParentStatementOfBlock(codeBlock) ?: return if (isSurroundingStatement(statement)) { State.surroundingStatementStartOffset = statement.startOffset State.lastChangeTimeMillis = action.timeMillis } } } private fun State.checkStatementStartDeleted(action: BeforeEditorTextRemovedAction): Boolean { return !isOutOfDate(action.timeMillis) && surroundingStatementStartOffset == action.textFragment.contentStartOffset } private fun SuggesterSupport.handleStatementStartDeletedFirst(action: BeforeEditorTextRemovedAction) { val textFragment = action.textFragment val curElement = action.psiFile?.findElementAt(textFragment.contentStartOffset) ?: return val curStatement = curElement.parent if (isSurroundingStatement(curStatement)) { val codeBlock = getCodeBlock(curStatement) ?: return val statements = getStatements(codeBlock) if (statements.isNotEmpty()) { State.closeBraceOffset = curStatement.endOffset - textFragment.text.length - 1 State.lastChangeTimeMillis = action.timeMillis } } } private fun State.checkCloseBraceDeleted(action: BeforeEditorTextRemovedAction): Boolean { return !isOutOfDate(action.timeMillis) && action.caretOffset == closeBraceOffset } private val TextFragment.contentStartOffset: Int get() { val countOfStartDelimiters = text.indexOfFirst { it != ' ' && it != '\n' } return startOffset + countOfStartDelimiters } private fun SuggesterSupport.isSurroundingStatement(psiElement: PsiElement): Boolean { return isIfStatement(psiElement) || isForStatement(psiElement) || isWhileStatement(psiElement) } companion object { const val MAX_TIME_MILLIS_BETWEEN_ACTIONS: Long = 7000L } }
284
null
5162
7
266934e25a8c277e3706ed5bcd00f6bf891b2426
5,196
intellij-feature-suggester
Apache License 2.0
app/src/main/kotlin/com/simplemobiletools/gallery/models/Directory.kt
rex07
129,520,377
true
{"Kotlin": 312746}
package com.simplemobiletools.gallery.models import com.simplemobiletools.commons.extensions.formatDate import com.simplemobiletools.commons.extensions.formatSize import com.simplemobiletools.commons.helpers.* import java.io.Serializable data class Directory(val path: String, val tmb: String, val name: String, var mediaCnt: Int, val modified: Long, val taken: Long, val size: Long, val isOnSDCard: Boolean) : Serializable, Comparable<Directory> { companion object { private val serialVersionUID = -6553345863555455L var sorting: Int = 0 } override fun compareTo(other: Directory): Int { var result: Int when { sorting and SORT_BY_NAME != 0 -> result = AlphanumericComparator().compare(name.toLowerCase(), other.name.toLowerCase()) sorting and SORT_BY_PATH != 0 -> result = AlphanumericComparator().compare(path.toLowerCase(), other.path.toLowerCase()) sorting and SORT_BY_SIZE != 0 -> result = when { size == other.size -> 0 size > other.size -> 1 else -> -1 } sorting and SORT_BY_DATE_MODIFIED != 0 -> result = when { modified == other.modified -> 0 modified > other.modified -> 1 else -> -1 } else -> result = when { taken == other.taken -> 0 taken > other.taken -> 1 else -> -1 } } if (sorting and SORT_DESCENDING != 0) { result *= -1 } return result } fun getBubbleText() = when { sorting and SORT_BY_NAME != 0 -> name sorting and SORT_BY_PATH != 0 -> path sorting and SORT_BY_SIZE != 0 -> size.formatSize() sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate() else -> taken.formatDate() } }
1
Kotlin
0
1
e1818d30e436b0b188b541a02407b3bae314fc31
1,915
Simple-Gallery
Apache License 2.0
models/src/main/java/com/vimeo/networking2/LiveStreamsQuota.kt
vimeo
41,306,732
false
null
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.annotations.Internal /** * Live Stream Quota DTO. * * @param maximum The maximum amount of streams that the user can create. * @param remaining The amount of remaining live streams that the user can create this month. */ @Internal @JsonClass(generateAdapter = true) data class LiveStreamsQuota( @Internal @Json(name = "maximum") val maximum: Int? = null, @Internal @Json(name = "remaining") val remaining: Int? = null )
21
Kotlin
52
123
e4f31d4fa144756d576101b3a82120657e9e8a51
580
vimeo-networking-java
MIT License
app/src/test/java/id/fathonyfath/pokedex/utils/PokemonDataHelperKtTest.kt
fathonyfath
111,093,240
false
null
package id.devfest.pokedex.utils import org.junit.Assert.assertEquals import org.junit.Test class PokemonDataHelperKtTest { @Test fun getIdFromURI_isCorrect() { assertEquals(1, "https://pokeapi.co/api/v2/pokemon-species/1/".getIdFromURI()) assertEquals(-1, "https://pokeapi.co/api/v2/pokemon".getIdFromURI()) } @Test fun removeDash_isCorrect() { assertEquals("pokemon", "pokemon".removeDash()) assertEquals("pokemon name", "pokemon-name".removeDash()) assertEquals("some pokemon name", "some-pokemon-name".removeDash()) } @Test fun capitaizeFirstLetter_isCorrect() { assertEquals("Bulbasaur", "bulbasaur".capitalizeFirstLetter()) assertEquals("Some pokemon", "some pokemon".capitalizeFirstLetter()) } }
0
Kotlin
3
3
b1c522cccf920b6a2ed82db2902e09e66e009555
799
pokedex-android
MIT License
core/src/main/kotlin/io/timemates/backend/users/usecases/EditUserUseCase.kt
timemates
575,534,781
false
{"Kotlin": 449272, "Dockerfile": 859}
package io.timemates.backend.users.usecases import io.timemates.backend.common.markers.UseCase import io.timemates.backend.features.authorization.AuthorizedContext import io.timemates.backend.users.repositories.UsersRepository import io.timemates.backend.users.types.User import io.timemates.backend.users.types.UsersScope import io.timemates.backend.users.types.value.userId class EditUserUseCase( private val usersRepository: UsersRepository, ) : UseCase { context(AuthorizedContext<UsersScope.Write>) suspend fun execute( patch: User.Patch, ): Result { usersRepository.edit(userId, patch) return Result.Success } sealed interface Result { data object Success : Result } }
20
Kotlin
0
8
5f7fb229cfecad044bc40a6cb65341253f7a026c
737
backend
MIT License
compiler/testData/diagnostics/tests/j+k/kt2619.kt
BradOselo
367,097,840
true
null
//FILE: foo.kt fun main() { val c: Type <!NON_EXHAUSTIVE_WHEN!>when<!> (<!UNINITIALIZED_VARIABLE!>c<!>) { } } //FILE: Type.java public enum Type { TYPE, NO_TYPE; }
1
null
1
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
189
kotlin
Apache License 2.0
oreui/src/commonMain/kotlin/vip/cdms/orecompose/utils/FormBuilder.kt
Cdm2883
796,016,358
false
{"Kotlin": 104805, "HTML": 344, "CSS": 103}
package vip.cdms.orecompose.utils
0
Kotlin
0
7
45318c5265940b97d0e5d0784378403aaca735e5
35
OreCompose
Apache License 2.0
shared/src/commonMain/kotlin/ui/screen/demo/ThemeColorDemo.kt
sdercolin
708,470,210
false
null
package ui.screen.demo import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.darkColors 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.Companion.Center import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.model.ScreenModel import cafe.adriel.voyager.core.model.rememberScreenModel import ui.model.Screen import ui.style.appDarkColors import ui.style.appLightColors object ThemeColorDemoScreen : Screen { override val title: String get() = "Theme Color Demo" @Composable override fun Content() = ThemeDemo() } class ThemeColorDemoScreenModel : ScreenModel { enum class Theme { System, Light, Dark, Default, } var theme by mutableStateOf(Theme.Dark) } @Composable private fun Screen.ThemeDemo() { val model = rememberScreenModel { ThemeColorDemoScreenModel() } val isDarkMode = isSystemInDarkTheme() val colors = remember(model.theme) { when (model.theme) { ThemeColorDemoScreenModel.Theme.System -> if (isDarkMode) { appDarkColors } else { appLightColors } ThemeColorDemoScreenModel.Theme.Light -> appLightColors ThemeColorDemoScreenModel.Theme.Dark -> appDarkColors ThemeColorDemoScreenModel.Theme.Default -> darkColors() } } MaterialTheme(colors = colors) { ThemeDemoContent( theme = model.theme, setTheme = { model.theme = it }, ) } } @Composable private fun ThemeDemoContent( theme: ThemeColorDemoScreenModel.Theme, setTheme: (ThemeColorDemoScreenModel.Theme) -> Unit, ) { Surface { Column(Modifier.fillMaxSize(), horizontalAlignment = CenterHorizontally) { Text( "Surface", modifier = Modifier.padding(20.dp), ) Column( Modifier.padding(20.dp) .fillMaxWidth() .weight(1f) .background(color = MaterialTheme.colors.background) .border(1.dp, color = Color.White) .border(1.dp, color = Color.Black), horizontalAlignment = CenterHorizontally, ) { Text( "Background", modifier = Modifier.padding(20.dp), color = MaterialTheme.colors.onBackground, ) Row( Modifier.padding(20.dp) .fillMaxWidth() .weight(1f), horizontalArrangement = Arrangement.SpaceEvenly, ) { Column( Modifier.fillMaxHeight(), horizontalAlignment = CenterHorizontally, verticalArrangement = Arrangement.Center, ) { Box { Row { Box(Modifier.size(100.dp).background(color = MaterialTheme.colors.primary)) Box(Modifier.size(100.dp).background(color = MaterialTheme.colors.primaryVariant)) } Text( "Primary", modifier = Modifier.align(Center), color = MaterialTheme.colors.onPrimary, ) } Box { Row { Box(Modifier.size(100.dp).background(color = MaterialTheme.colors.secondary)) Box(Modifier.size(100.dp).background(color = MaterialTheme.colors.secondaryVariant)) } Text( "Secondary", modifier = Modifier.align(Center), color = MaterialTheme.colors.onSecondary, ) } Box(Modifier.size(200.dp, 100.dp).background(color = MaterialTheme.colors.error)) { Text( "Error", modifier = Modifier.align(Center), color = MaterialTheme.colors.onError, ) } } Column( Modifier.fillMaxHeight().width(IntrinsicSize.Max), verticalArrangement = Arrangement.Center, ) { ThemeColorDemoScreenModel.Theme.values().forEach { Button( modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors( backgroundColor = if (it == theme) { MaterialTheme.colors.secondary } else { MaterialTheme.colors.primary }, ), onClick = { setTheme(it) }, ) { Text(it.name) } } } } } } } }
0
null
1
9
8ed61865b56192b1e484f2e36ddc0a33ec79e8e5
6,773
recstar
Apache License 2.0
app/src/main/java/com/cmgcode/minimoods/MiniMoodsApplication.kt
CampbellMG
327,529,105
false
null
package com.cmgcode.minimoods import android.app.Application import com.cmgcode.minimoods.dependencies.AppContainer import com.cmgcode.minimoods.dependencies.AppModule class MiniMoodsApplication : Application() { override fun onCreate() { super.onCreate() module = AppContainer(applicationContext) } companion object { lateinit var module: AppModule } }
4
Kotlin
1
9
24cc9e2631f59b955b9d7f3991557d262dacde9d
398
MiniMoods
MIT License
application-interface/src/main/kotlin/com/mechanica/engine/input/KeyID.kt
DominicDolan
210,876,716
false
{"Kotlin": 435430}
package com.mechanica.engine.input interface KeyID { val id: Int val label: String }
7
Kotlin
1
0
67f7613de56e94a4086a02a503b53df57f6ad92c
93
Mechanica
MIT License
compiler/testData/diagnostics/testsWithStdLib/reified/reifiedNothingSubstitution.fir.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// LANGUAGE: +NullableNothingInReifiedPosition // DIAGNOSTICS: -UNUSED_PARAMETER -UNREACHABLE_CODE -UNUSED_VARIABLE -DEPRECATION inline fun<reified T> foo(block: () -> T): String = block().toString() inline fun <reified T: Any> javaClass(): Class<T> = T::class.java fun box() { val a = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION, UNSUPPORTED!>arrayOf<!>(null!!) val b = <!UNSUPPORTED("Array<Nothing?> isn't supported in JVM")!>Array<!><Nothing?>(5) { null!! } val c = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>foo<!>() { null!! } val d = foo<Any> { null!! } val e = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>foo<!> { "1" <!CAST_NEVER_SUCCEEDS!>as<!> Nothing } val e1 = foo { "1" <!CAST_NEVER_SUCCEEDS!>as<!> Nothing? } val f = javaClass<<!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>Nothing<!>>() }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
813
kotlin
Apache License 2.0
dsl/jpql/src/test/kotlin/com/linecorp/kotlinjdsl/dsl/jpql/expression/SubstringDslTest.kt
line
442,633,985
false
{"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023}
package com.linecorp.kotlinjdsl.dsl.jpql.expression import com.linecorp.kotlinjdsl.dsl.jpql.queryPart import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expression import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expressions import org.assertj.core.api.WithAssertions import org.junit.jupiter.api.Test class SubstringDslTest : WithAssertions { private val string1 = "string1" private val int1 = 1 private val int2 = 2 private val stringExpression1 = Expressions.value("string1") private val intExpression1 = Expressions.value(1) private val intExpression2 = Expressions.value(2) @Test fun `substring() with a string and an int`() { // when val expression = queryPart { substring(string1, int1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = Expressions.value(string1), start = Expressions.value(int1), ) assertThat(actual).isEqualTo(expected) } @Test fun `substring() with a string and ints`() { // when val expression = queryPart { substring(string1, int1, int2) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = Expressions.value(string1), start = Expressions.value(int1), length = Expressions.value(int2), ) assertThat(actual).isEqualTo(expected) } @Test fun `substring() with a string expression and an int`() { // when val expression = queryPart { substring(stringExpression1, int1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = stringExpression1, start = Expressions.value(int1), ) assertThat(actual).isEqualTo(expected) } @Test fun `substring() with a string expression and ints`() { // when val expression = queryPart { substring(stringExpression1, int1, int2) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = stringExpression1, start = Expressions.value(int1), length = Expressions.value(int2), ) assertThat(actual).isEqualTo(expected) } @Test fun `substring() with a string expression and an int expression`() { // when val expression = queryPart { substring(stringExpression1, intExpression1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = stringExpression1, start = intExpression1, ) assertThat(actual).isEqualTo(expected) } @Test fun `substring() with a string expression and int expressions`() { // when val expression = queryPart { substring(stringExpression1, intExpression1, intExpression2) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.substring( value = stringExpression1, start = intExpression1, length = intExpression2, ) assertThat(actual).isEqualTo(expected) } }
4
Kotlin
86
705
3a58ff84b1c91bbefd428634f74a94a18c9b76fd
3,655
kotlin-jdsl
Apache License 2.0
05_FirstStepsInKotlinwithSpringBoot/rest_spring_boot_and_kotlin_neptum/src/test/kotlin/com/neptum/integrationtests/swagger/SwaggerIntegrationTest.kt
matheus-adps91
623,150,696
false
null
package com.neptum.integrationtests.swagger import com.neptum.integrationtests.testcontainers.AbstractIntegrationTest import com.neptum.integrationtests.ConfigsTest import io.restassured.RestAssured.given import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) class SwaggerIntegrationTest() : AbstractIntegrationTest() { @Test fun showDisplaySwaggerUiPage() { val content = given() .basePath("/swagger-ui/index.html") .port(ConfigsTest.SERVER_PORT) .`when`() .get() .then() .statusCode(200) .extract() .body() .asString() assertTrue(content.contains("Swagger UI")) } }
0
Kotlin
0
0
e2e97c6062c36fa4c657a075e3d95d699fd3ffac
776
rest-spring-boot-and-kotlin-neptum
Apache License 2.0
app/src/main/java/lab4/lab/com/lab4/db/Note.kt
mishatron
131,904,586
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 11, "XML": 18, "Java": 2}
package lab4.lab.com.lab4.db /** * Created by mishatron on 02.05.2018. */ data class Note(var id:Int, var text:String)
1
null
1
1
41136274370ab7a4441d6ca5d696e004df13ec53
121
lab4_android_viewpager_sqlite
MIT License
api/src/main/java/com/ftinc/giphy/api/model/Image.kt
52inc
138,968,440
false
{"Gradle": 8, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "INI": 3, "Proguard": 2, "Kotlin": 23, "XML": 22, "Java": 2}
package com.ftinc.giphy.api.model data class Image( val url: String, val width: Int, val height: Int, val size: Int?, val mp4: String?, val mp4_size: Int?, val webp: String?, val webp_size: Int? )
1
null
1
1
a07b804bb133c9706cad35fcc79811c9020a3b05
263
android-giphy
Apache License 2.0
app/src/main/java/com/doubean/ford/data/db/AppDatabase.kt
Bumblebee202111
453,416,432
false
null
package com.doubean.ford.data.db import android.content.Context import androidx.room.Database import androidx.room.Room.databaseBuilder import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.sqlite.db.SupportSQLiteDatabase import com.doubean.ford.data.vo.* import com.doubean.ford.util.AppExecutors import com.doubean.ford.util.Constants /** * The Room database for this app */ @Database( entities = [Group::class, Post::class, GroupFollow::class, GroupSearchResult::class, GroupPostsResult::class, GroupTagPostsResult::class, PostComment::class, PostCommentsResult::class, PostTopComments::class, RecommendedGroupsResult::class, RecommendedGroupResult::class], version = 1, exportSchema = false ) @TypeConverters( Converters::class ) abstract class AppDatabase : RoomDatabase() { abstract fun groupDao(): GroupDao abstract fun groupFollowsAndSavesDao(): GroupFollowsAndSavesDao companion object { @Volatile private var instance: AppDatabase? = null @JvmStatic fun getInstance(context: Context): AppDatabase? { if (instance == null) { synchronized(AppDatabase::class.java) { instance = buildDatabase(context) } } return instance } private val sRoomDatabaseCallback: Callback = object : Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) AppExecutors().diskIO().execute { prepopulate() } } } private fun buildDatabase(context: Context): AppDatabase { return databaseBuilder(context, AppDatabase::class.java, Constants.DATABASE_NAME) .addCallback(sRoomDatabaseCallback) .build() } private fun prepopulate() {} } }
0
Kotlin
0
5
3da5362ca15342d1fc7151dbb7e1d85381d35878
1,846
doubean
Apache License 2.0
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Divider.kt
RikkaW
389,105,112
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.Composable import androidx.ui.core.Modifier import androidx.compose.foundation.Box import androidx.compose.foundation.background import androidx.compose.ui.graphics.Color import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredHeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * A divider is a thin line that groups content in lists and layouts * * @param color color of the divider line * @param thickness thickness of the divider line, 1 dp is used by default * @param startIndent start offset of this line, no offset by default */ @Composable fun Divider( modifier: Modifier = Modifier, color: Color = MaterialTheme.colors.onSurface.copy(alpha = DividerAlpha), thickness: Dp = 1.dp, startIndent: Dp = 0.dp ) { val indentMod = if (startIndent.value != 0f) { Modifier.padding(start = startIndent) } else { Modifier } Box( modifier.then(indentMod) .fillMaxWidth() .preferredHeight(thickness) .background(color = color) ) } private const val DividerAlpha = 0.12f
29
null
950
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
1,873
androidx
Apache License 2.0
app/src/main/java/com/ml/shivay_couchbase/docqa/data/DataModels.kt
shivay-couchbase
874,673,406
false
null
package com.ml.couchbase.docqa.data data class Chunk( var chunkId: Long = 0, var docId: String = 0.toString(), var docFileName: String = "", var chunkData: String = "", var chunkEmbedding: FloatArray = floatArrayOf() ) data class Document( var docId: Long = 0, var docText: String = "", var docFileName: String = "", var docAddedTime: Long = 0, ) data class RetrievedContext(val fileName: String, val context: String) data class QueryResult(val response: String, val context: List<RetrievedContext>)
0
null
0
1
cccd12efdc63ac2f7a53294d20383e55f693f0b8
541
couchbase-lite-workshop
Apache License 2.0
app/src/main/java/com/gmail/uia059466/simplemath/forgit/games/HelpUtils.kt
serhiq
288,129,326
false
null
package com.gmail.uia059466.simplemath.forgit.games import com.gmail.uia059466.simplemath.forgit.R import com.gmail.uia059466.simplemath.forgit.utils.StringWrapper class HelpUtils{ companion object{ fun helpSayNext(add: Int): HelpMessage { val id= when (add) { 2 -> R.string.help_say_next_2 else -> R.string.help_say_next } val str= StringWrapper(id, listOf(add.toString())) return HelpMessage(text = str) } fun helpAddVerbal(): HelpMessage { val id=R.string.help_add_verbal val str= StringWrapper(id, emptyList()) return HelpMessage(text = str) } fun helpAddVerbalPermute(): HelpMessage { val id=R.string.help_add_verbal_permute val str= StringWrapper(id, emptyList()) return HelpMessage(text = str) } } }
1
null
1
1
2227c8afab91e30a333a260bd99c9e8f0e55d4ff
822
Simple-math
Apache License 2.0
android/versioned-abis/expoview-abi48_0_0/src/main/java/abi48_0_0/host/exp/exponent/modules/internal/DevMenuModule.kt
kojoYeboah53i
462,599,485
false
null
package abi44_0_0.host.exp.exponent.modules.internal import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import abi44_0_0.com.facebook.react.bridge.LifecycleEventListener import abi44_0_0.com.facebook.react.bridge.ReactApplicationContext import abi44_0_0.com.facebook.react.bridge.ReactContextBaseJavaModule import abi44_0_0.com.facebook.react.bridge.UiThreadUtil import abi44_0_0.com.facebook.react.devsupport.DevInternalSettings import abi44_0_0.com.facebook.react.devsupport.DevSupportManagerImpl import abi44_0_0.com.facebook.react.devsupport.HMRClient import expo.modules.manifests.core.Manifest import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.exponent.experience.ExperienceActivity import host.exp.exponent.experience.ReactNativeActivity import host.exp.exponent.kernel.DevMenuManager import host.exp.exponent.kernel.DevMenuModuleInterface import host.exp.exponent.kernel.KernelConstants import host.exp.expoview.R import java.util.* import javax.inject.Inject class DevMenuModule(reactContext: ReactApplicationContext, val experienceProperties: Map<String, Any?>, val manifest: Manifest?) : ReactContextBaseJavaModule(reactContext), LifecycleEventListener, DevMenuModuleInterface { @Inject internal lateinit var devMenuManager: DevMenuManager init { NativeModuleDepsProvider.instance.inject(DevMenuModule::class.java, this) reactContext.addLifecycleEventListener(this) } //region publics override fun getName(): String = "ExpoDevMenu" //endregion publics //region DevMenuModuleInterface /** * Returns manifestUrl of the experience which can be used as its ID. */ override fun getManifestUrl(): String { val manifestUrl = experienceProperties[KernelConstants.MANIFEST_URL_KEY] as String? return manifestUrl ?: "" } /** * Returns a [Bundle] containing initialProps that will be used to render the dev menu for related experience. */ override fun getInitialProps(): Bundle { val bundle = Bundle() val taskBundle = Bundle() taskBundle.putString("manifestUrl", getManifestUrl()) taskBundle.putString("manifestString", manifest?.toString()) bundle.putBundle("task", taskBundle) bundle.putString("uuid", UUID.randomUUID().toString()) return bundle } /** * Returns a [Bundle] with all available dev menu options for related experience. */ override fun getMenuItems(): Bundle { val devSupportManager = getDevSupportManager() val devSettings = devSupportManager?.devSettings val items = Bundle() val inspectorMap = Bundle() val debuggerMap = Bundle() val hmrMap = Bundle() val perfMap = Bundle() if (devSettings != null && devSupportManager.devSupportEnabled) { inspectorMap.putString("label", getString(if (devSettings.isElementInspectorEnabled) R.string.devmenu_hide_element_inspector else R.string.devmenu_show_element_inspector)) inspectorMap.putBoolean("isEnabled", true) } else { inspectorMap.putString("label", getString(R.string.devmenu_element_inspector_unavailable)) inspectorMap.putBoolean("isEnabled", false) } items.putBundle("dev-inspector", inspectorMap) if (devSettings != null && devSupportManager.devSupportEnabled) { debuggerMap.putString("label", getString(if (devSettings.isRemoteJSDebugEnabled) R.string.devmenu_stop_remote_debugging else R.string.devmenu_start_remote_debugging)) debuggerMap.putBoolean("isEnabled", devSupportManager.devSupportEnabled) } else { debuggerMap.putString("label", getString(R.string.devmenu_remote_debugger_unavailable)) debuggerMap.putBoolean("isEnabled", false) } items.putBundle("dev-remote-debug", debuggerMap) if (devSettings != null && devSupportManager.devSupportEnabled && devSettings is DevInternalSettings) { hmrMap.putString("label", getString(if (devSettings.isHotModuleReplacementEnabled) R.string.devmenu_disable_fast_refresh else R.string.devmenu_enable_fast_refresh)) hmrMap.putBoolean("isEnabled", true) } else { hmrMap.putString("label", getString(R.string.devmenu_fast_refresh_unavailable)) hmrMap.putString("detail", getString(R.string.devmenu_fast_refresh_unavailable_details)) hmrMap.putBoolean("isEnabled", false) } items.putBundle("dev-hmr", hmrMap) if (devSettings != null && devSupportManager.devSupportEnabled) { perfMap.putString("label", getString(if (devSettings.isFpsDebugEnabled) R.string.devmenu_hide_performance_monitor else R.string.devmenu_show_performance_monitor)) perfMap.putBoolean("isEnabled", true) } else { perfMap.putString("label", getString(R.string.devmenu_performance_monitor_unavailable)) perfMap.putBoolean("isEnabled", false) } items.putBundle("dev-perf-monitor", perfMap) return items } /** * Handles selecting dev menu options returned by [getMenuItems]. */ override fun selectItemWithKey(itemKey: String) { val devSupportManager = getDevSupportManager() val devSettings = devSupportManager?.devSettings as DevInternalSettings? if (devSupportManager == null || devSettings == null) { return } UiThreadUtil.runOnUiThread { when (itemKey) { "dev-remote-debug" -> { devSettings.isRemoteJSDebugEnabled = !devSettings.isRemoteJSDebugEnabled devSupportManager.handleReloadJS() } "dev-hmr" -> { val nextEnabled = !devSettings.isHotModuleReplacementEnabled val hmrClient: HMRClient? = reactApplicationContext?.getJSModule(HMRClient::class.java) devSettings.isHotModuleReplacementEnabled = nextEnabled if (nextEnabled) hmrClient?.enable() else hmrClient?.disable() } "dev-inspector" -> devSupportManager.toggleElementInspector() "dev-perf-monitor" -> { if (!devSettings.isFpsDebugEnabled) { // Request overlay permission if needed when "Show Perf Monitor" option is selected requestOverlaysPermission() } devSupportManager.setFpsDebugEnabled(!devSettings.isFpsDebugEnabled) } } } } /** * Reloads JavaScript bundle without reloading the manifest. */ override fun reloadApp() { getDevSupportManager()?.handleReloadJS() } /** * Returns boolean value determining whether this app supports developer tools. */ override fun isDevSupportEnabled(): Boolean { return manifest != null && manifest.isUsingDeveloperTool() } //endregion DevMenuModuleInterface //region LifecycleEventListener override fun onHostResume() { val activity = currentActivity if (activity is ExperienceActivity) { devMenuManager.registerDevMenuModuleForActivity(this, activity) } } override fun onHostPause() {} override fun onHostDestroy() {} //endregion LifecycleEventListener //region internals /** * Returns versioned instance of [DevSupportManagerImpl], * or null if no activity is currently attached to react context. */ private fun getDevSupportManager(): DevSupportManagerImpl? { val activity = currentActivity as? ReactNativeActivity? return activity?.devSupportManager?.get() as? DevSupportManagerImpl? } /** * Requests for the permission that allows the app to draw overlays on other apps. * Such permission is required for example to enable performance monitor. */ private fun requestOverlaysPermission() { val context = currentActivity ?: return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Get permission to show debug overlay in dev builds. if (!Settings.canDrawOverlays(context)) { val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.packageName) ) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } } } } /** * Helper for getting localized [String] from `strings.xml` file. */ private fun getString(ref: Int): String { return reactApplicationContext.resources.getString(ref) } //endregion internals }
668
null
5226
4
75d1b44ed4c4bbd05d7ec109757a017628c43415
8,298
expo
MIT License
app/src/main/java/com/andrii/movieapp/models/Movie.kt
andrii-zubenko
726,233,305
false
{"Kotlin": 81440}
package com.andrii.movieapp.models import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import com.squareup.moshi.Json import kotlinx.parcelize.Parcelize @Parcelize @Entity data class Movie( @Json(name = "poster_path") val posterPath: String?, @PrimaryKey val id: Long?, @Json(name = "backdrop_path") val backdropPath: String?, val title: String?, @Json(name = "vote_average") val voteAverage: Double?, val overview: String?, @Json(name = "release_date") val releaseDate: String?, var watchedStatus: String = WatchedStatus.NOT_WATCHED.statusString ) : Parcelable { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Movie return id == other.id } override fun hashCode(): Int { return id.hashCode() } }
0
Kotlin
0
0
4c95f5d17affef492bbb7055848f99a6db3f6917
933
MovieApp
MIT License
src/main/kotlin/de/bettinggame/adapter/BaseController.kt
lcmatrix
85,833,270
false
{"XSLT": 83147, "Kotlin": 46258, "HTML": 28434, "Dockerfile": 269, "CSS": 192}
package de.bettinggame.adapter import de.bettinggame.domain.NewsRepository import de.bettinggame.ui.Navigation import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.RequestMapping interface AbstractController { /** * Returns navigation items */ @ModelAttribute("nonRestrictedNavigation") fun getNonRestrictedNavigation(): List<Navigation> = Navigation.getNonRestrictedNavigation() @ModelAttribute("userRestrictedNavigation") fun getUserRestrictedNavigation(): List<Navigation> = Navigation.getUserRestrictedNavigation() @ModelAttribute("adminRestrictedNavigation") fun getAdminRestrictedNavigation(): List<Navigation> = Navigation.getAdminRestrictedNavigation() } /** * Controller for index/startpage. */ @Controller class MainController(private val newsRepository: NewsRepository) : AbstractController { @RequestMapping("/login") fun login() = "login" @RequestMapping("/index") fun index() = "index" @RequestMapping("/") fun root(model: Model): String { val authentication: Authentication? = SecurityContextHolder.getContext().authentication if (authentication != null && authentication.isAuthenticated) { val news = newsRepository.findAllByOrderByPublishDateDesc() model.addAttribute(news) return "news/news" } return "index" } }
16
XSLT
1
1
436c8d580436cc06105e9afb7f5833eafd3e619f
1,642
betting-game
Apache License 2.0
src/backend/paas/project/biz-project/src/main/kotlin/com/heapoverflow/project/jmx/api/ProjectJmxApi.kt
panfairy
577,309,391
false
null
package com.heapoverflow.project.jmx.api import org.slf4j.LoggerFactory import org.springframework.jmx.export.MBeanExporter import org.springframework.stereotype.Component import javax.management.ObjectName @Component class ProjectJmxApi constructor( private val mBeanExporter: MBeanExporter, ) { private val apis = HashMap<String, APIPerformanceBean>() fun execute(api: String, elapse: Long, success: Boolean) { try { getBean(api).execute(elapse, success) } catch (ignored: Throwable) { logger.warn("Fail to record the api performance of api [$api]", ignored) } } private fun getBean(api: String): APIPerformanceBean { var bean = apis[api] if (bean == null) { synchronized(this) { bean = apis[api] if (bean == null) { bean = APIPerformanceBean() val name = "com.heapoverflow.project:type=apiPerformance,name=$api" logger.info("Register [$api] api performance mbean") mBeanExporter.registerManagedResource(bean!!, ObjectName(name)) apis[api] = bean!! } } } return bean!! } companion object { private val logger = LoggerFactory.getLogger(ProjectJmxApi::class.java) const val PROJECT_LIST = "project_list" const val PROJECT_CREATE = "project_create" const val PROJECT_UPDATE = "project_update" } }
0
Kotlin
0
0
75b45eee784fdbc92441856dfde289bad3ec91b5
1,517
ho-base
MIT License
app/src/main/java/me/yimu/doucalendar/Logger.kt
yimun
104,193,995
false
null
package me.yimu.doucalendar import android.os.Environment import com.elvishew.xlog.LogConfiguration import com.elvishew.xlog.LogLevel import com.elvishew.xlog.XLog import com.elvishew.xlog.flattener.PatternFlattener import com.elvishew.xlog.printer.AndroidPrinter import com.elvishew.xlog.printer.file.FilePrinter import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator import java.io.File /** * Created by linwei on 2017/9/25. */ object Logger { init { val androidPrinter = AndroidPrinter() // Printer that print the log using android.util.Log val filePrinter = FilePrinter.Builder(getLogFolderPath()) // Specify the path to save log file .fileNameGenerator(DateFileNameGenerator()) // Default: ChangelessFileNameGenerator("log") .backupStrategy(NeverBackupStrategy()) // Default: FileSizeBackupStrategy(1024 * 1024) .logFlattener(PatternFlattener("{d yyyy-MM-dd HH:mm:ss.SSS} {l}/{t}: {m}")) .build() val level = if (BuildConfig.DEBUG) LogLevel.ALL else LogLevel.NONE XLog.init(level, LogConfiguration.Builder().build(), androidPrinter, filePrinter) } fun getLogFolderPath(): String { val path = File(Environment.getExternalStorageDirectory().path, "xlog") if (!path.exists()) { path.mkdir() } return path.path } fun d(tag: String, msg: String) { XLog.tag(tag).d(msg, msg) } }
0
Kotlin
1
2
0e51904367b8ce7ddb46814a0a2e76e138a5dc64
1,573
DouCalendar
MIT License
boat-spring-boot-core/src/main/kotlin/xyz/srclab/spring/boot/task/TaskDelegate.kt
srclab-projects
232,048,928
false
null
package xyz.srclab.spring.boot.task import java.util.concurrent.Executor /** * An task delegate for execution operation. */ interface TaskDelegate { fun execute(executor: Executor, task: Runnable) }
0
Kotlin
0
2
661236cf81d2af015aba0a4155f7b30ccbec9520
207
boat-spring-boot
Apache License 2.0
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Callable.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.solve.stdlib.primitive import it.unibo.tuprolog.core.Struct import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.primitive.TypeTester object Callable : TypeTester<ExecutionContext>("callable") { override fun testType(term: Term): Boolean = term is Struct }
92
null
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
349
2p-kt
Apache License 2.0
src/main/kotlin/no/nb/bikube/core/controller/CoreController.kt
NationalLibraryOfNorway
694,135,748
false
{"Kotlin": 99637, "Dockerfile": 109}
package no.nb.bikube.core.controller import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import io.swagger.v3.oas.annotations.tags.Tag import no.nb.bikube.core.enum.CatalogueName import no.nb.bikube.core.enum.MaterialType import no.nb.bikube.core.enum.materialTypeToCatalogueName import no.nb.bikube.core.exception.AxiellCollectionsException import no.nb.bikube.core.exception.AxiellTitleNotFound import no.nb.bikube.core.exception.BadRequestBodyException import no.nb.bikube.core.exception.NotSupportedException import no.nb.bikube.core.model.CatalogueRecord import no.nb.bikube.core.model.Item import no.nb.bikube.core.model.Title import no.nb.bikube.newspaper.service.AxiellService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Flux import reactor.core.publisher.Mono @RestController @Tag(name = "Catalogue objects", description = "Endpoints related to catalog data for all text material") @RequestMapping("") class CoreController ( private val axiellService: AxiellService ){ @GetMapping("/item", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Get single item from catalogue") @ApiResponses(value = [ ApiResponse(responseCode = "200", description = "OK"), ApiResponse(responseCode = "500", description = "Server error") ]) @Throws(AxiellCollectionsException::class, AxiellTitleNotFound::class, NotSupportedException::class) fun getSingleItem( @RequestParam catalogueId: String, @RequestParam materialType: MaterialType, ): ResponseEntity<Mono<Item>> { return when(materialTypeToCatalogueName(materialType)) { CatalogueName.COLLECTIONS -> ResponseEntity.ok(axiellService.getSingleItem(catalogueId)) else -> throw NotSupportedException("Material type $materialType is not supported.") } } @GetMapping("/title", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Get single title from catalogue") @ApiResponses(value = [ ApiResponse(responseCode = "200", description = "OK"), ApiResponse(responseCode = "500", description = "Server error") ]) @Throws(AxiellCollectionsException::class, AxiellTitleNotFound::class, NotSupportedException::class) fun getSingleTitle( @RequestParam catalogueId: String, @RequestParam materialType: MaterialType, ): ResponseEntity<Mono<Title>> { return when(materialTypeToCatalogueName(materialType)) { CatalogueName.COLLECTIONS -> ResponseEntity.ok(axiellService.getSingleTitle(catalogueId)) else -> throw NotSupportedException("Material type $materialType is not supported.") } } @GetMapping("/search", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Search catalogue titles") @ApiResponses(value = [ ApiResponse(responseCode = "200", description = "OK"), ApiResponse(responseCode = "400", description = "Bad request"), ApiResponse(responseCode = "500", description = "Server error") ]) fun search( @RequestParam searchTerm: String, @RequestParam materialType: MaterialType ): ResponseEntity<Flux<CatalogueRecord>> { if (searchTerm.isEmpty()) throw BadRequestBodyException("Search term cannot be empty.") return when(materialTypeToCatalogueName(materialType)) { CatalogueName.COLLECTIONS -> ResponseEntity.ok(axiellService.searchTitleByName(searchTerm)) else -> throw NotSupportedException("Material type $materialType is not supported.") } } }
4
Kotlin
0
2
b197cdcaebbc7e63e6ecc756517a10011a263e62
3,998
bikube
Apache License 2.0
shared/src/iosMain/kotlin/com/juagri/shared/data/local/database/DriverFactory.kt
juagrideveloper
699,804,299
false
{"Kotlin": 1302992, "Swift": 6001, "Shell": 615}
package com.juagri.shared.data.local.database import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.native.NativeSqliteDriver import com.juagri.shared.JUDatabase actual class DriverFactory { actual fun createDriver(): SqlDriver { return NativeSqliteDriver(JUDatabase.Schema, "JUDatabase.db") } }
0
Kotlin
0
0
dfb433421930bbf970fae303f5e496698f9d9e09
335
juagriapp
Apache License 2.0
src/commonMain/kotlin/wizard/files/GradleBat.kt
terrakok
618,540,934
false
null
package wizard.files import wizard.ProjectFile class GradleBat : ProjectFile { override val path = "gradlew.bat" override val content = """ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega """ }
13
null
29
439
d61bd739f0443940441eec1986c5b58fa40f5f89
2,981
Compose-Multiplatform-Wizard
MIT License
app/src/main/java/com/rfb/projetoapitmdb/data/remote/TMDB.kt
rubensfbr
768,066,787
false
{"Kotlin": 46148}
package com.rfb.projetoapitmdb.data.remote import com.rfb.projetoapitmdb.data.dto.details.DetailsDTO import com.rfb.projetoapitmdb.data.dto.popularMovies.PopularMoviesDTO import com.rfb.projetoapitmdb.data.dto.search.SearchDTO import com.rfb.projetoapitmdb.data.dto.topRatedMovies.TopRatedMoviesDTO import com.rfb.projetoapitmdb.data.dto.upcomingMovies.UpcomingMoviesDTO import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface TMDB { @GET("movie/popular?language=pt-BR") suspend fun getPolularMovies(@Query("page") page: Int): Response<PopularMoviesDTO> @GET("movie/upcoming?language=pt-BR") suspend fun getUpcomingMovies(@Query("page") page: Int): Response<UpcomingMoviesDTO> @GET("movie/top_rated?language=pt-BR") suspend fun getTopRatedMovies(@Query("page") page: Int): Response<TopRatedMoviesDTO> @GET("movie/{movie_id}?language=pt-BR") suspend fun getDetails(@Path("movie_id") id: Int): Response<DetailsDTO> @GET("search/movie") suspend fun getSearch(@Query("query") query: String, @Query("language") language: String, @Query("page") page: Int): Response<SearchDTO> }
0
Kotlin
0
0
20f8c81f634bdf417f669e1119239ef78bad7e89
1,233
ProjetoApiTMDB
Apache License 2.0
src/commonMain/kotlin/com/adyen/model/balanceplatform/AddressRequirement.kt
tjerkw
733,432,442
false
{"Kotlin": 5043126, "Makefile": 6356}
/** * Configuration API * * The Configuration API enables you to create a platform where you can onboard your users as account holders and create balance accounts, cards, and business accounts. ## Authentication Your Adyen contact will provide your API credential and an API key. To connect to the API, add an `X-API-Key` header with the API key as the value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` Alternatively, you can use the username and password to connect to the API using basic authentication. For example: ``` curl -H \"Content-Type: application/json\" \\ -U \"[email protected]_BALANCE_PLATFORM\":\"YOUR_WS_PASSWORD\" \\ ... ``` ## Versioning The Configuration API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders ``` ## Going live When going live, your Adyen contact will provide your API credential for the live environment. You can then use the API key or the username and password to send requests to `https://balanceplatform-api-live.adyen.com/bcl/v2`. * * The version of the OpenAPI document: 2 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.adyen.model.balanceplatform import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * * * @param type **addressRequirement** * @param description Specifies the required address related fields for a particular route. * @param requiredAddressFields List of address fields. */ @Serializable data class AddressRequirement ( /* **addressRequirement** */ @SerialName(value = "type") @Required val type: AddressRequirement.Type = Type.AddressRequirement, /* Specifies the required address related fields for a particular route. */ @SerialName(value = "description") val description: kotlin.String? = null, /* List of address fields. */ @SerialName(value = "requiredAddressFields") val requiredAddressFields: kotlin.collections.List<AddressRequirement.RequiredAddressFields>? = null ) { /** * **addressRequirement** * * Values: AddressRequirement */ @Serializable enum class Type(val value: kotlin.String) { @SerialName(value = "addressRequirement") AddressRequirement("addressRequirement"); } /** * List of address fields. * * Values: City,Country,Line1,PostalCode,StateOrProvince */ @Serializable enum class RequiredAddressFields(val value: kotlin.String) { @SerialName(value = "city") City("city"), @SerialName(value = "country") Country("country"), @SerialName(value = "line1") Line1("line1"), @SerialName(value = "postalCode") PostalCode("postalCode"), @SerialName(value = "stateOrProvince") StateOrProvince("stateOrProvince"); } }
0
Kotlin
0
0
2da5aea5519b2dfa84454fe1665e9699edc87507
3,261
adyen-kotlin-multiplatform-api-library
MIT License
app/src/main/java/eu/yeger/koffee/ui/user/creation/UserCreationViewModel.kt
koffee-project
257,901,759
false
null
package eu.yeger.koffee.ui.user.creation import androidx.lifecycle.MutableLiveData import eu.yeger.koffee.repository.AdminRepository import eu.yeger.koffee.repository.UserRepository import eu.yeger.koffee.ui.CoroutineViewModel import eu.yeger.koffee.ui.DataAction import eu.yeger.koffee.utility.nullIfBlank import eu.yeger.koffee.utility.sourcedLiveData /** * [CoroutineViewModel] for creating users. * * @property adminRepository [AdminRepository] for accessing authentication tokens. * @property userRepository [UserRepository] for creating the user. * @property userId Bidirectional [MutableLiveData](https://developer.android.com/reference/androidx/lifecycle/MutableLiveData) for binding the user id. * @property userName Bidirectional [MutableLiveData](https://developer.android.com/reference/androidx/lifecycle/MutableLiveData) for binding the user name. * @property userPassword Bidirectional [MutableLiveData](https://developer.android.com/reference/androidx/lifecycle/MutableLiveData) for binding the user password. * @property isAdmin Bidirectional [MutableLiveData](https://developer.android.com/reference/androidx/lifecycle/MutableLiveData) for binding the admin status. * @property canCreateUser Indicates that creating a user is possible with the current input values. * @property userCreatedAction [DataAction] that is activated when the user has been created. Contains the user's id. * * @author <NAME> */ class UserCreationViewModel( private val adminRepository: AdminRepository, private val userRepository: UserRepository ) : CoroutineViewModel() { val userId = MutableLiveData("") val userName = MutableLiveData("") val userPassword = MutableLiveData("") val isAdmin = MutableLiveData(false) val canCreateUser = sourcedLiveData(userName, userPassword, isAdmin) { userName.value.isNullOrBlank().not() && (isAdmin.value!!.not() || userPassword.value.isNullOrBlank().not() && userPassword.value!!.length >= 8) } val userCreatedAction = DataAction<String>() /** * Creates a user with the current id, name, password and admin status. */ fun createUser() { onViewModelScope { val jwt = adminRepository.getJWT()!! val userId = userRepository.createUser( userId = userId.value?.nullIfBlank(), userName = userName.value!!, password = userPassword.value.nullIfBlank(), isAdmin = isAdmin.value!!, jwt = jwt ) userCreatedAction.activateWith(userId) } } }
0
Kotlin
0
1
8fd30631154ea3b9f568297152250322dd6d2f58
2,658
koffee-app
Apache License 2.0
Search/src/main/kotlin/Graph.kt
Hieu-Luu
804,079,368
false
{"Kotlin": 20809}
package org.example.search.algorith import java.util.LinkedList import java.util.Queue class Graph(private val vertices: Int) { private val adjacencyList: MutableList<MutableList<Int>> = MutableList(vertices) { mutableListOf() } fun addEdge(v: Int, w: Int) { adjacencyList[v].add(w) adjacencyList[w].add(v) println("adjacencyList[$v] ${adjacencyList[v]}") println("adjacencyList[$w] ${adjacencyList[w]}") } fun shortestPath(start: Int, end: Int): List<Int> { val queue: Queue<Int> = LinkedList() val visited = BooleanArray(vertices) val parent = IntArray(vertices) { -1 } // Lưu trữ đỉnh cha để truy vết đường đi ngắn nhất queue.add(start) visited[start] = true while (queue.isNotEmpty()) { val currentVertex = queue.poll() for (neighbor in adjacencyList[currentVertex]) { if (!visited[neighbor]) { visited[neighbor] = true queue.add(neighbor) parent[neighbor] = currentVertex } } } parent.forEachIndexed { index, i -> println("parent[$index] $i") } // Truy vết đường đi ngắn nhất từ end đến start val shortestPath = mutableListOf<Int>() var current = end while (current != -1) { shortestPath.add(current) current = parent[current] } return shortestPath.reversed() } fun bfs(startingVertex: Int) { val visited = BooleanArray(vertices) val queue: Queue<Int> = LinkedList() visited[startingVertex] = true queue.add(startingVertex) while (queue.isNotEmpty()) { println("queue $queue") val currentVertex = queue.poll() println("$currentVertex ") for (neighbor in adjacencyList[currentVertex]) { if (!visited[neighbor]) { visited[neighbor] = true queue.add(neighbor) } } } } fun dfs(startingVertex: Int) { val visited = BooleanArray(vertices) dfsRecursive(startingVertex, visited) } fun dfsRecursive(vertex: Int, visited: BooleanArray) { visited[vertex] = true print("$vertex -> ") adjacencyList[vertex].forEach { if (!visited[it]) { dfsRecursive(it, visited) } } } }
0
Kotlin
0
0
202399897d3dacecfe0abb91adea4253bd5461b2
2,506
algorithms
Apache License 2.0
app-1/src/test/kotlin/com/lg5/app1/ModuleOneTest.kt
lg-training
787,013,329
false
{"Kotlin": 793}
package com.lg5.app1 import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class ModuleOneTest { lateinit var sut: ModuleOne @BeforeEach fun setUp() { sut = ModuleOne("1") } @Test fun getMasp() { sut.masp.forEach { t, u -> println("$t $u"); } assertFalse(sut.masp.isEmpty()) } }
0
Kotlin
0
0
40290541d601cf03a23a9e2cab2d209a85e26631
408
multimodule-gradle-kts
MIT License
core-starter/src/main/kotlin/com/labijie/application/HttpFormUrlCodec.kt
hongque-pro
309,874,586
false
null
package com.labijie.application import org.springframework.util.LinkedMultiValueMap import org.springframework.util.MultiValueMap import org.springframework.util.StringUtils import java.net.URLDecoder import java.net.URLEncoder import java.nio.charset.Charset object HttpFormUrlCodec { fun encode(formData: Map<String, Any?>, charset: Charset = Charsets.UTF_8, allowNullValue: Boolean = false) : String { val builder = StringBuilder() formData.forEach { (name, value) -> if(value != null || allowNullValue) { builder.appendNameValue(name, value ?: "", charset) } } return builder.toString() } private fun StringBuilder.appendNameValue( name: String, value: Any, charset: Charset ) { if (this.isNotEmpty()) { this.append('&') } this.append(URLEncoder.encode(name, charset.name())) val stringValue = value.toString() if (stringValue.isNotBlank()) { this.append('=') this.append(URLEncoder.encode(stringValue, charset.name())) } } fun encode(formData: MultiValueMap<String, Any>, charset: Charset = Charsets.UTF_8) : String { val builder = StringBuilder() formData.forEach { (name, values) -> values.forEach { value -> builder.appendNameValue(name, value, charset) } } return builder.toString() } fun decode(content:ByteArray, charset:Charset = Charsets.UTF_8): MultiValueMap<String, String> { val contentString = content.toString(charset) return decode(contentString, charset) } fun decode(content:String, charset:Charset = Charsets.UTF_8): MultiValueMap<String, String> { val pairs = StringUtils.tokenizeToStringArray(content, "&") val result = LinkedMultiValueMap<String, String>(pairs.size) for (pair in pairs) { val idx = pair.indexOf('=') if (idx == -1) { result.add(URLDecoder.decode(pair, charset.name()), null) } else { val name = URLDecoder.decode(pair.substring(0, idx), charset.name()) val value = URLDecoder.decode(pair.substring(idx + 1), charset.name()) result.add(name, value) } } return result } }
0
null
0
8
f2f709ee8fff5b6d416bc35c5d7e234a4781b096
2,382
application-framework
Apache License 2.0
src/main/kotlin/net/integr/rendering/uisystem/MovableBox.kt
Integr-0
786,886,635
false
{"Kotlin": 199433, "Java": 65495}
/* * Copyright © 2024 Integr * * 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 net.integr.rendering.uisystem import net.integr.Helix import net.integr.Variables import net.integr.rendering.RenderingEngine import net.integr.rendering.uisystem.base.HelixUiElement import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.Drawable import net.minecraft.client.sound.PositionedSoundInstance import net.minecraft.sound.SoundEvents import net.minecraft.util.math.MathHelper import org.lwjgl.glfw.GLFW @Suppress("MemberVisibilityCanBePrivate") class MovableBox(var xPos: Int, var yPos: Int, var xSize: Int, var ySize: Int, var text: String) : Drawable, HelixUiElement { var dragging = false var dragOffsetX = 0.0 var dragOffsetY = 0.0 override fun render(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { val color = Variables.guiBack val textColor = Variables.guiColor if (dragging) { xPos = MathHelper.clamp((mouseX-dragOffsetX).toInt(), 5, context.scaledWindowWidth-xSize-5) yPos = MathHelper.clamp((mouseY-dragOffsetY).toInt(), 5, context.scaledWindowHeight-ySize-5) } val x1 = xPos val x2 = xPos + xSize val y1 = yPos val y2 = yPos + ySize RenderingEngine.TwoDimensional.fillRound(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat(), color, textColor, context, 0.05f, 9f) context.drawText(Helix.MC.textRenderer, text, x1 + xSize / 2 - Helix.MC.textRenderer.getWidth(text) / 2 - 4, y1 + ySize / 2 - 4, textColor, false) } override fun renderTooltip(context: DrawContext, mouseX: Int, mouseY: Int, delta: Float) { // Do Nothing } override fun onClick(mouseX: Double, mouseY: Double, button: Int) { if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { val x1 = xPos val x2 = xPos + xSize val y1 = yPos val y2 = yPos + ySize if (mouseX.toInt() in (x1 + 1)..<x2 && mouseY > y1 && mouseY < y2) { dragging = true dragOffsetX = mouseX - xPos dragOffsetY = mouseY - yPos Helix.MC.soundManager.play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)) } } } override fun onRelease(mouseX: Double, mouseY: Double, button: Int) { if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT) { if (dragging) { dragging = false } } } override fun update(xPos: Int, yPos: Int): MovableBox { this.xPos = xPos this.yPos = yPos return this } }
0
Kotlin
0
1
cd0389b340f24661e117f033cd56f452d2efb28d
3,178
Helix
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppssubjectaccessrequestworker/gateways/DocumentStorageGateway.kt
ministryofjustice
748,250,175
false
{"Kotlin": 65078, "Dockerfile": 1161}
package uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.gateways import org.json.JSONObject import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.core.io.ByteArrayResource import org.springframework.http.HttpStatus import org.springframework.http.client.MultipartBodyBuilder import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.config.HmppsSubjectAccessRequestWorkerExceptionHandler import java.io.ByteArrayOutputStream import java.util.* @Component class DocumentStorageGateway( @Autowired val hmppsAuthGateway: HmppsAuthGateway, @Value("\${services.document-storage.base-url}") hmppsDocumentApiUrl: String, ) { private val webClient: WebClient = WebClient.builder().baseUrl(hmppsDocumentApiUrl).build() private val log = LoggerFactory.getLogger(this::class.java) fun storeDocument(documentId: UUID, docBody: ByteArrayOutputStream): String? { log.info("Storing document with UUID $documentId") val token = hmppsAuthGateway.getClientToken() val multipartBodyBuilder = MultipartBodyBuilder() val contentsAsResource: ByteArrayResource = object : ByteArrayResource(docBody.toByteArray()) { override fun getFilename(): String { return "report.pdf" } } val response = webClient.post().uri("/documents/SUBJECT_ACCESS_REQUEST_REPORT/$documentId") .header("Authorization", "Bearer $token") .header("Service-Name", "DPS-Subject-Access-Requests") .bodyValue( multipartBodyBuilder.apply { part("file", contentsAsResource) part("metadata", 1) }.build(), ) .retrieve() // Don't treat 401 responses as errors: .onStatus( { status -> status === HttpStatus.BAD_REQUEST }, { clientResponse -> throw Exception(clientResponse.bodyToMono(HmppsSubjectAccessRequestWorkerExceptionHandler::class.java).toString()) }, ) .bodyToMono(String::class.java) .block() return response } fun retrieveDocument(documentId: UUID): JSONObject? { val token = hmppsAuthGateway.getClientToken() val response = webClient.get().uri("/documents/" + { documentId.toString() }).header("Authorization", "Bearer $token").retrieve().bodyToMono(JSONObject::class.java).block() return response } }
0
Kotlin
0
0
16175eb28a6398b48bc5e2c04329e92f66600853
2,500
hmpps-subject-access-request-worker
MIT License
src/tr/mangasiginagi/src/eu/kanade/tachiyomi/extension/tr/mangasiginagi/MangaSiginagi.kt
komikku-app
720,497,299
false
{"Kotlin": 6775539, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.tr.mangasiginagi import eu.kanade.tachiyomi.multisrc.mangathemesia.MangaThemesia import java.text.SimpleDateFormat import java.util.Locale class MangaSiginagi : MangaThemesia( "Manga Siginagi", "https://mangasiginagi.com", "tr", dateFormat = SimpleDateFormat("MMMM d, yyy", Locale("tr")), )
22
Kotlin
8
97
7fc1d11ee314376fe0daa87755a7590a03bc11c0
347
komikku-extensions
Apache License 2.0
material_design/MaterialTest/app/src/main/java/com/workaholiclab/materialtest/FruitActivity.kt
Workaholic-Lab
298,015,933
false
{"Kotlin": 418971, "C++": 159092, "Makefile": 31044, "Java": 4576, "HTML": 2236, "QMake": 753, "C": 263}
package com.workaholiclab.materialtest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_fruit.* import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_main.toolBar class FruitActivity : AppCompatActivity() { companion object{ const val FRUIT_NAME ="fruit_name" const val FRUIT_IMAGE_ID="fruit_image_id" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fruit) val fruitName=intent.getStringExtra(FRUIT_NAME) ?:"" val fruitImageId = intent.getIntExtra(FRUIT_IMAGE_ID,0) setSupportActionBar(toolBar) supportActionBar?.setDisplayHomeAsUpEnabled(true) collapsingToolbar.title=fruitName Glide.with(this).load(fruitImageId).into(fruitImageView) fruitContentText.text=generateFruitContent(fruitName) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ android.R.id.home->{ finish() return true } } return super.onOptionsItemSelected(item) } private fun generateFruitContent(fruitName: String)=fruitName.repeat(500) }
0
Kotlin
0
1
55220c5c71cbce5b398c4b6c0aacacaa5e94c4e4
1,393
Android-Kotlin-startup
Apache License 2.0
app/src/main/java/com/tommannson/familycooking/domain/DomainModule.kt
TomMannson
742,552,338
false
{"Kotlin": 261582}
package com.tommannson.familycooking.domain import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @InstallIn(SingletonComponent::class) @Module abstract class DomainModule { @Binds internal abstract fun loadImage(impl: DefaultLoadImageUseCase): LoadImageUseCase @Binds internal abstract fun textRecognitionUseCase(impl: DefaultTextRecognitionUseCase): TextRecognitionUseCase }
0
Kotlin
0
0
aac2d58a56f67e8849ed328bb0b0da690bdb5442
460
CookMe
MIT License
crm/src/test/kotlin/it/polito/crm/IntegrationTest.kt
gianlucavinci98
874,249,564
false
{"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302}
package org.example.crm.integrationTest.controllers import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.util.TestPropertyValues import org.springframework.context.ApplicationContextInitializer import org.springframework.context.ConfigurableApplicationContext import org.springframework.test.context.ContextConfiguration import org.testcontainers.containers.PostgreSQLContainer @SpringBootTest @ContextConfiguration(initializers = [IntegrationTest.Initializer::class]) abstract class IntegrationTest { companion object { private val db = PostgreSQLContainer("postgres:latest").apply { withDatabaseName("crm") withUsername("crm") withPassword("crm") setPortBindings(listOf("12341:5432")) } } internal class Initializer : ApplicationContextInitializer<ConfigurableApplicationContext> { override fun initialize(applicationContext: ConfigurableApplicationContext) { db.start() TestPropertyValues.of( "spring.datasource.url=${db.jdbcUrl}", "spring.datasource.username=${db.username}", "spring.datasource.password=${<PASSWORD>}" ).applyTo( applicationContext.environment ) } } }
0
Kotlin
0
0
ccad8f0a41e77e03935e548b4f03969fc051a61f
1,327
wa2-project-job-placement
MIT License
compiler/testData/codegen/boxInline/special/inlineChain.kt
JakeWharton
99,388,807
false
null
// FILE: 1.kt class My inline fun <T, R> T.perform(job: (T)-> R) : R { return job(this) } inline fun My.someWork(job: (String) -> Any): Unit { this.perform { job("OK") } } inline fun My.doWork (closure : (param : String) -> Unit) : Unit { this.someWork(closure) } inline fun My.doPerform (closure : (param : My) -> Int) : Int { return perform(closure) } // FILE: 2.kt fun test1(): String { val inlineX = My() var d = ""; inlineX.doWork({ z: String -> d = z; z}) return d } fun test2(): Int { val inlineX = My() return inlineX.perform({ z: My -> 11}) } fun box(): String { if (test1() != "OK") return "test1: ${test1()}" if (test2() != 11) return "test1: ${test2()}" return "OK" }
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
755
kotlin
Apache License 2.0
Android-Kotlin/sulmun2/sulmun2/app/src/main/java/com/example/sulmun2/horror2detail/horrordetail17.kt
dkekdmf
469,109,428
false
{"Jupyter Notebook": 237657, "Python": 61277, "Kotlin": 61159, "C": 27870, "JavaScript": 7802, "EJS": 6927, "HTML": 2245, "CSS": 111}
package com.example.sulmun2.horror2detail import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.sulmun2.R class horrordetail17 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.horrordetail17) }}
4
Jupyter Notebook
0
1
445ac449acd6f1bf9f3b49d37f4df4739b8feca8
348
Jaehoon
MIT License
common/src/main/java/com/microsoft/identity/common/internal/activebrokerdiscovery/BrokerDiscoveryClient.kt
AzureAD
109,141,516
false
null
// Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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.microsoft.identity.common.internal.activebrokerdiscovery import android.content.Context import android.os.Bundle import com.microsoft.identity.common.exception.BrokerCommunicationException import com.microsoft.identity.common.internal.broker.BrokerData import com.microsoft.identity.common.internal.broker.BrokerValidator import com.microsoft.identity.common.internal.broker.PackageHelper import com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle import com.microsoft.identity.common.internal.broker.ipc.ContentProviderStrategy import com.microsoft.identity.common.internal.broker.ipc.IIpcStrategy import com.microsoft.identity.common.internal.cache.IClientActiveBrokerCache import com.microsoft.identity.common.java.exception.ClientException import com.microsoft.identity.common.java.exception.ClientException.ONLY_SUPPORTS_ACCOUNT_MANAGER_ERROR_CODE import com.microsoft.identity.common.java.interfaces.IPlatformComponents import com.microsoft.identity.common.java.logging.Logger import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.util.concurrent.TimeUnit /** * A class for figuring out which Broker app the caller should communicate with. * * This class will try pinging each installed apps provided in [brokerCandidates], which will * essentially trigger Broker Discovery on that side (and subsequently returned result). * * If none of the installed app supports the Broker Discovery protocol, this class will fall back * to the legacy AccountManager method. * * @param brokerCandidates list of (Broker hosting) candidate apps to perform discovery with. * @param getActiveBrokerFromAccountManager a function which returns a validated [BrokerData] * based on Android's AccountManager API * @param ipcStrategy An [IIpcStrategy] to aggregate data with. * @param cache A local cache for storing active broker discovery results. * @param isPackageInstalled a function to determine if any given broker app is installed. * @param isValidBroker a function to determine if the installed broker app contains a matching signature hash. **/ class BrokerDiscoveryClient(private val brokerCandidates: Set<BrokerData>, private val getActiveBrokerFromAccountManager: () -> BrokerData?, private val ipcStrategy: IIpcStrategy, private val cache: IClientActiveBrokerCache, private val isPackageInstalled: (BrokerData) -> Boolean, private val isValidBroker: (BrokerData) -> Boolean) : IBrokerDiscoveryClient { companion object { val TAG = BrokerDiscoveryClient::class.simpleName @OptIn(ExperimentalCoroutinesApi::class) val dispatcher = Dispatchers.IO.limitedParallelism(10) const val ACTIVE_BROKER_PACKAGE_NAME_BUNDLE_KEY = "ACTIVE_BROKER_PACKAGE_NAME_BUNDLE_KEY" const val ACTIVE_BROKER_SIGNING_CERTIFICATE_THUMBPRINT_BUNDLE_KEY = "ACTIVE_BROKER_SIGNING_CERTIFICATE_THUMBPRINT_BUNDLE_KEY" const val ERROR_BUNDLE_KEY = "ERROR_BUNDLE_KEY" /** * Per-process Thread-safe, coroutine-safe Mutex of this class. * This is to prevent the IPC mechanism from being unnecessarily triggered due to race condition. * * The object here must be both coroutine-safe and thread-safe. **/ private val classLevelLock = Mutex() /** * Performs an IPC operation to get a result from the provided [brokerCandidates]. * * @param brokerCandidates the candidate(s) to query from. * @param ipcStrategy the ipc mechanism to query with. * @param isPackageInstalled a method which returns true if the provided [BrokerData] is installed. * @param shouldStopQueryForAWhile a method which, if invoked, will force [BrokerDiscoveryClient] * to skip the IPC discovery process for a while. **/ internal suspend fun queryFromBroker(brokerCandidates: Set<BrokerData>, ipcStrategy: IIpcStrategy, isPackageInstalled: (BrokerData) -> Boolean, isValidBroker: (BrokerData) -> Boolean ): BrokerData? { return coroutineScope { val installedCandidates = brokerCandidates.filter(isPackageInstalled).filter(isValidBroker) val deferredResults = installedCandidates.map { candidate -> async(dispatcher) { return@async makeRequest(candidate, ipcStrategy) } } return@coroutineScope deferredResults.awaitAll().filterNotNull().firstOrNull() } } private fun makeRequest(candidate: BrokerData, ipcStrategy: IIpcStrategy): BrokerData? { val methodTag = "$TAG:makeRequest" val operationBundle = BrokerOperationBundle( BrokerOperationBundle.Operation.BROKER_DISCOVERY_FROM_SDK, candidate.packageName, Bundle() ) return try { val result = ipcStrategy.communicateToBroker(operationBundle) extractResult(result) } catch (t: Throwable) { if (t is BrokerCommunicationException && BrokerCommunicationException.Category.OPERATION_NOT_SUPPORTED_ON_SERVER_SIDE == t.category) { Logger.info(methodTag, "Tried broker discovery on ${candidate}. It doesn't support the IPC mechanism.") } else if (t is ClientException && ONLY_SUPPORTS_ACCOUNT_MANAGER_ERROR_CODE == t.errorCode){ Logger.info(methodTag, "Tried broker discovery on ${candidate}. " + "The Broker side indicates that only AccountManager is supported.") } else { Logger.error(methodTag, "Tried broker discovery on ${candidate}, get an error", t) } null } } /** * Extract the result returned via the IPC operation **/ @Throws(NoSuchElementException::class) private fun extractResult(bundle: Bundle?): BrokerData? { if (bundle == null) { return null } val errorData = bundle.getSerializable(ERROR_BUNDLE_KEY) if (errorData != null) { throw errorData as Throwable } val pkgName = bundle.getString(ACTIVE_BROKER_PACKAGE_NAME_BUNDLE_KEY)?: throw NoSuchElementException("ACTIVE_BROKER_PACKAGE_NAME_BUNDLE_KEY must not be null") val signatureHash = bundle.getString(ACTIVE_BROKER_SIGNING_CERTIFICATE_THUMBPRINT_BUNDLE_KEY)?: throw NoSuchElementException("ACTIVE_BROKER_SIGNING_CERTIFICATE_THUMBPRINT_BUNDLE_KEY must not be null") return BrokerData(pkgName, signatureHash) } } constructor(context: Context, components: IPlatformComponents, cache: IClientActiveBrokerCache): this( brokerCandidates = BrokerData.getKnownBrokerApps(), getActiveBrokerFromAccountManager = { AccountManagerBrokerDiscoveryUtil(context).getActiveBrokerFromAccountManager() }, ipcStrategy = ContentProviderStrategy(context, components), cache = cache, isPackageInstalled = { brokerData -> PackageHelper(context). isPackageInstalledAndEnabled(brokerData.packageName) }, isValidBroker = { brokerData -> BrokerValidator(context).isSignedByKnownKeys(brokerData) }) override fun getActiveBroker(shouldSkipCache: Boolean): BrokerData? { return runBlocking { return@runBlocking getActiveBrokerAsync(shouldSkipCache) } } private suspend fun getActiveBrokerAsync(shouldSkipCache:Boolean): BrokerData?{ val methodTag = "$TAG:getActiveBrokerAsync" classLevelLock.withLock { if (!shouldSkipCache) { if (cache.shouldUseAccountManager()) { return getActiveBrokerFromAccountManager() } cache.getCachedActiveBroker()?.let { if (!isPackageInstalled(it)) { Logger.info( methodTag, "There is a cached broker: $it, but the app is no longer installed." ) cache.clearCachedActiveBroker() return@let } if (!isValidBroker(it)) { Logger.info( methodTag, "Clearing cache as the installed app does not have a matching signature hash." ) cache.clearCachedActiveBroker() return@let } if(!ipcStrategy.isSupportedByTargetedBroker(it.packageName)){ Logger.info( methodTag, "Clearing cache as the installed app does not provide any IPC mechanism to communicate to. (e.g. the broker code isn't shipped with this apk)" ) cache.clearCachedActiveBroker() return@let } Logger.info(methodTag, "Returning cached broker: $it") return it } } val brokerData = queryFromBroker( brokerCandidates = brokerCandidates, ipcStrategy = ipcStrategy, isPackageInstalled = isPackageInstalled, isValidBroker = isValidBroker ) if (brokerData != null) { cache.setCachedActiveBroker(brokerData) return brokerData } Logger.info( methodTag, "Will skip broker discovery via IPC and fall back to AccountManager " + "for the next 60 minutes." ) cache.clearCachedActiveBroker() cache.setShouldUseAccountManagerForTheNextMilliseconds( TimeUnit.MINUTES.toMillis( 60 ) ) val accountManagerResult = getActiveBrokerFromAccountManager() Logger.info( methodTag, "Tried getting active broker from account manager, " + "get ${accountManagerResult?.packageName}." ) return accountManagerResult } } }
77
null
46
41
944252ace420a3ebfc0fc0d126ca47084e084a8f
12,393
microsoft-authentication-library-common-for-android
MIT License
app/src/main/java/com/agobikk/cookeatenjoy/data/converters/ConvertFoodInformationEntity.kt
AGOBIKK
483,512,081
false
null
package com.agobikk.cookeatenjoy.data.converters import com.agobikk.cookeatenjoy.data.local.entities.ExtendedIngredientEntity import com.agobikk.cookeatenjoy.data.local.entities.FoodInformationEntity import com.agobikk.cookeatenjoy.models.FoodInformation interface ConvertFoodInformationEntity { fun convertFoodInformationEntity(value: FoodInformation, ingredient:List<ExtendedIngredientEntity>): FoodInformationEntity }
0
Kotlin
0
0
663238d46b9a7308608a5d14b953f0691a91fe95
426
CookEatEnjoy
Apache License 2.0
residingtab/src/main/java/com/orsteg/residingtab/RevealViewPager.kt
goody-h
166,485,252
false
null
package com.orsteg.residingtab import android.app.Activity import android.content.Context import android.os.Build import android.os.Bundle import android.os.Parcelable import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.View import android.view.WindowManager import java.util.* import kotlin.collections.ArrayList import kotlin.concurrent.schedule /** * Copyright 2019 Orsteg Inc * * 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. */ class RevealViewPager : ViewPager { private val activity: Activity? = run { if (context is Activity) context as Activity? else null } private val window = activity?.window // Touch event variables private val mTouchable: ArrayList<View> = ArrayList() private var mTouchOverrideView: View? = null //private var mTouchOverrideTime: Long = -1 // Reveal transformation variables private var mRevealPosition: Int = -1 private var appBar: View? = null private var resideForeground: View? = null private val mForegrounds: ArrayList<View> = ArrayList() private var actionBtn: View? = null private var mResideTab: View? = null private var visibilityChangeListener: OnResideTabVisibilityChangeListener? = null // State variables holding current states of full screen and translucence private var mState: Int = ViewPager.SCROLL_STATE_IDLE private var isFullScreen: Boolean? = null private var isTranslucentNav: Boolean? = null private var mCurrent = -1 private var shouldTransform = false private var isStateSaved: Boolean? = null // Init the reveal transformer here private var mTransformer = RevealTransformer() init { // bind the reveal transformer to the ViewPager addOnPageChangeListener(mTransformer) // Intercept touch events and deliver to other view layers beneath it when in reveal state setOnTouchListener { _, event -> //val time = event.downTime //check if this is a new touch session //if (time <= mTouchOverrideTime) clearTouchOverride() //mTouchOverrideTime = time // deliver touch events only when in IDLE state and on reveal position if (currentItem == mRevealPosition && mState == ViewPager.SCROLL_STATE_IDLE) { // Offset the vertical position of the touch event // due to a displacement of the ViewPager caused by the AppBar collapsing. event.offsetLocation(0f, appBar?.top?.toFloat()?:0f) // check if any view has a hold on touch events if (mTouchOverrideView != null) { mTouchOverrideView?.dispatchTouchEvent(event) } else { // Keep sending the touch event layer by layer until a view consumes it for (touchable in mTouchable) { if (touchable.dispatchTouchEvent(event)) break } } //mTouchOverrideView != null } false } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) /** * This method sets the residing tab view and its reveal position. * Its sets the reside view's touch response index to 1 * * @param view The residing view * @param revealPosition the index of the residing view's reveal tab */ fun setResidingView(view: View, revealPosition: Int) { touchables.remove(mResideTab) addTouchableViewLayer(view, 1) mResideTab = view setRevealPosition(revealPosition) } /** * Sets the position of the revealing item fragment. */ fun setRevealPosition(position: Int) { mRevealPosition = position } /** * A view that has been declared as a touchable layer can call this method to retain all touch * events during a touch action, preventing the ViewPager from intercepting it. * When the view is done it should call [clearTouchOverride] to return control to the ViewPager fun overrideTouch(view: View) { if (mTouchable.contains(view)) mTouchOverrideView = view } fun clearTouchOverride() { mTouchOverrideView = null } */ /** * Used to set views that can receive touch events behind the view pager * @param view The view to receive the touch event * @param layerIndex Touch events are delivered in ascending order from index 0 till a view * completely consumes the event */ fun addTouchableViewLayer(view: View, layerIndex: Int = mTouchable.size) { var index = resolveIndex(layerIndex) if (!mTouchable.contains(view)) { mTouchable.add(index, view) } else if(mTouchable.indexOf(view) != index){ mTouchable.remove(view) index = resolveIndex(index) mTouchable.add(index, view) } } fun removeTouchableViewLayer(view: View): Boolean { return mTouchable.remove(view) } fun removeTouchableViewLayerIndex(index: Int) { if (index >= 0 && index < mTouchable.size) mTouchable.removeAt(index) } /** * Attaches a lister for the reside view state changes */ fun setOnResideTabVisibilityChangeListener(listener: OnResideTabVisibilityChangeListener?) { visibilityChangeListener = listener } private fun resolveIndex(index: Int) :Int { if (mTouchable.size == 0 || index < 0) return 0 if (index > mTouchable.size) return mTouchable.size return index } /** * This method binds Views that will be transformed during page transitions. Call this method to set * all the transformation views at once, else call the individual binding methods for each view. * * @param appBar this should be the AppBarLayout in the layout. * This is the view that would be translated upwards during the residing tab reveal * * @param resideTabForeground This view is always placed above the residing tab, * but is drawn behind the ViewPager. It slides into position as the reveal begins * * @param actBtn This is the material design FloatingActionButton or any view serving the same purpose. */ fun bindTransformedViews(appBar: View?, resideTabForeground: View?, actBtn: View?) { if (appBar != null) bindAppBar(appBar) if (resideTabForeground != null) bindForeground(resideTabForeground) if (actBtn != null) bindActionButton(actBtn) } // Individual methods for binding views that would be transformed during state changes fun bindAppBar(appBar: View?) { this.appBar = appBar } fun bindForeground(fore: View?) { touchables.remove(this.resideForeground) this.resideForeground = fore if (fore != null) addTouchableViewLayer(fore, 0) } fun bindActionButton(actBtn: View?) { this.actionBtn = actBtn } /** * A foreground is taken as any view that slides into position together with the reveal tab * * @param touchIndex determines the order they receive touch events. */ fun addForeground(foreground: View, touchIndex: Int? = null) { if (!mForegrounds.contains(foreground)) mForegrounds.add(foreground) if(touchIndex != null)addTouchableViewLayer(foreground, touchIndex) } /**This method should not be called before any call to [ViewPager.setCurrentItem] is made during * layout initialization. * A call to [ViewPager.setCurrentItem] after calling this method during app Initialization, * introduces a subtle transformation error. * * @param inState . Pass the savedInstanceState bundle from [Activity.onCreate] to this method * @param firstInit . Set to false if the index of the residing tab, [mRevealPosition], = 0 * and you do not want to initialise layout at that position. It disables initial transformations. * Default value is set to false. Set true if initial transformation is required */ fun initTransformer(inState: Bundle?, firstInit: Boolean = false) { var current = inState?.getInt("RevealTransformer.mCurrent", -2)?:0 isStateSaved = current != -2 if (mCurrent != -1 && inState == null) current = mCurrent if ((inState == null && current == mRevealPosition && firstInit) || (inState != null && current == mRevealPosition)) { mCurrent = current mTransformer.reside() } } /** * Method should be called in the [Activity.onSaveInstanceState] method to save the current state * of the UI */ fun saveState(outState: Bundle?){ outState?.apply { putInt("RevealTransformer.mCurrent", mCurrent) } } /** * This method is called to get the current visibility state of the residing view */ fun getIsResidingViewVisible() : Boolean = isTranslucentNav == true /** * Call this method in the Activity class either in [Activity.onResume] or [Activity.onWindowFocusChanged] * in order to make sure windowUIVisibility is always in the correct state. */ fun updateUIVisibility() { mTransformer.setUIVisibility() } override fun onRestoreInstanceState(state: Parcelable?) { super.onRestoreInstanceState(state) // check if user saved view state in activity or not then initialise transformer if (isStateSaved == null || isStateSaved == false) initTransformer(null, true) } /** * The page transform class that handles transformation of the appbar, resideForeground, * action button and state of translucence and full screen. **/ inner class RevealTransformer : ViewPager.OnPageChangeListener { init { // Set a ui visibility listener to reset the status bar when in full screen // mode, after a 2s delay. window?.decorView?.setOnSystemUiVisibilityChangeListener { Timer().schedule(2000){ activity?.runOnUiThread { setUIVisibility() } } } } // Initialises first transformation for the reside view fun reside() { setFullScreen() setTranslucentNav() Thread { // get the width of the screen val w = width // get an instance of the bottom value of the appBar var h = (appBar?.bottom ?: 0) // Loop till view is drawn or transformation is not necessary while ((h == 0 && appBar != null && appBar?.visibility == VISIBLE) || (w == 0 && visibility == VISIBLE)) h = (appBar?.bottom ?: 0) activity?.runOnUiThread { // Translate the appBar up as the resideReveal slides into view appBar?.translationY = -h - h / 8f // Translate the resideForeground together with the resideReveal resideForeground?.translationX = 0f for (foreground in mForegrounds) { foreground.translationX = 0f } // Translate the actionButton away as the resideReveal slides into view actionBtn?.translationX = w.toFloat() } }.start() mCurrent = currentItem } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { // going right offset changes from zero to one // get an instance of the width of the screen val w = width // get an instance of the bottom value of the appBar val h = (appBar?.bottom ?: 0) if (position == mRevealPosition && shouldTransform) { // Translate the appBar up as the resideReveal slides into view var y = (positionOffset * h) - h if (y == -h.toFloat()) y = -h - h / 8f appBar?.translationY = y // Translate the resideForeground together with the resideReveal resideForeground?.translationX = -w * positionOffset for (foreground in mForegrounds) { foreground.translationX = -w * positionOffset } // Translate the actionButton away as the resideReveal slides into view actionBtn?.translationX = w * (1 - positionOffset) // Set translucence based on the position of the resideReveal if (positionOffset < 1) setTranslucentNav() else exitTranslucentNav() // Set full screen based on the position of resideReveal if (positionOffset > 0) exitFullScreen() else setFullScreen() } else if (position == mRevealPosition - 1 && shouldTransform) { // going right offset changes from zero to one // Translate the appBar up as the resideReveal slides into view appBar?.translationY = -(positionOffset * h) // Translate the resideForeground together with the resideReveal resideForeground?.translationX = w * (1 - positionOffset) for (foreground in mForegrounds) { foreground.translationX = w * (1 - positionOffset) } // Translate the actionButton away as the resideReveal slides into view actionBtn?.translationX = -w * positionOffset // Set translucence based on the position of the resideReveal if (positionOffset > 0) setTranslucentNav() else exitTranslucentNav() // Set full screen based on the position of resideReveal if (positionOffset < 1) exitFullScreen() else setFullScreen() } else { if (appBar?.translationY != 0f || resideForeground?.translationX == 0f) { if (appBar?.translationY != 0f)exitTranslucentNav() // Reset translation of the appBar appBar?.translationY = 0f // Reset translation of the actionButton actionBtn?.translationX = 0f // hide the resideForeground to the left or the right of the screen if (position > mRevealPosition) { resideForeground?.translationX = (-w).toFloat() for (foreground in mForegrounds) { foreground.translationX = (-w).toFloat() } } else { resideForeground?.translationX = (w).toFloat() for (foreground in mForegrounds) { foreground.translationX = (w).toFloat() } } } } } override fun onPageSelected(position: Int) { // check if page scroll state is settling from/to the resideReveal position shouldTransform = (mCurrent == mRevealPosition || position == mRevealPosition) when (position) { mRevealPosition -> { actionBtn?.visibility = View.INVISIBLE } else -> { actionBtn?.visibility = View.VISIBLE } } mCurrent = position } override fun onPageScrollStateChanged(state: Int) { if (state == ViewPager.SCROLL_STATE_DRAGGING || state == ViewPager.SCROLL_STATE_IDLE) { shouldTransform = true } mState = state } // Methods for setting the UI Visibility private fun exitTranslucentNav() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (isTranslucentNav == null || isTranslucentNav == true) { window?.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) isTranslucentNav = false visibilityChangeListener?.onChanged(false) } } } private fun setTranslucentNav() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (isTranslucentNav == null || isTranslucentNav == false) { window?.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) isTranslucentNav = true visibilityChangeListener?.onChanged(true) } } } private fun setFullScreen() { if (isFullScreen == null || isFullScreen == false && !isFullScreen()) { window?.decorView?.systemUiVisibility = FULLSCREEN isFullScreen = true } } private fun exitFullScreen() { if (isFullScreen == null || isFullScreen == true) { window?.decorView?.systemUiVisibility = NOT_FULLSCREEN isFullScreen = false } } private fun isFullScreen() = window?.decorView?.systemUiVisibility == FULLSCREEN fun setUIVisibility() { if (isFullScreen == true && !isFullScreen()) { window?.decorView?.systemUiVisibility = FULLSCREEN } } } companion object { val FULLSCREEN = View.SYSTEM_UI_FLAG_LAYOUT_STABLE + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + View.SYSTEM_UI_FLAG_FULLSCREEN val NOT_FULLSCREEN = View.SYSTEM_UI_FLAG_LAYOUT_STABLE + View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION } /** * Interface for listening to when the residing view becomes visible and when it looses visibility */ interface OnResideTabVisibilityChangeListener { fun onChanged(isVisible: Boolean) } }
0
Kotlin
2
9
c463df87610bca6ca874fccfce1477f955d10766
18,903
ResidingTab
Apache License 2.0
app/src/main/java/com/hypersoft/admobads/ui/fragments/sample/FragmentBanner.kt
hypersoftdev
616,294,144
false
{"Kotlin": 117351}
package com.hypersoft.admobads.ui.fragments.sample import com.hypersoft.admobads.R import com.hypersoft.admobads.databinding.FragmentBannerBinding import com.hypersoft.admobads.adsconfig.AdmobBanner import com.hypersoft.admobads.adsconfig.callbacks.BannerCallBack import com.hypersoft.admobads.adsconfig.enums.BannerType import com.hypersoft.admobads.helpers.firebase.RemoteConstants import com.hypersoft.admobads.helpers.observers.SingleLiveEvent import com.hypersoft.admobads.ui.fragments.base.BaseFragment class FragmentBanner : BaseFragment<FragmentBannerBinding>(R.layout.fragment_banner) { private val admobBanner by lazy { AdmobBanner() } private val adsObserver = SingleLiveEvent<Boolean>() private var isCollapsibleOpen = false private var isBackPressed = false override fun onViewCreatedOneTime() { loadAds() } override fun onViewCreatedEverytime() { initObserver() } private fun initObserver(){ adsObserver.observe(this){ if (it){ onBack() } } } override fun navIconBackPressed() { onBackPressed() } override fun onBackPressed() { if (isAdded){ try { if (!isBackPressed){ isBackPressed = true if (isCollapsibleOpen){ admobBanner.bannerOnDestroy() binding.adsBannerPlaceHolder.removeAllViews() }else{ onBack() } } }catch (ex:Exception){ isBackPressed = false } } } private fun onBack(){ popFrom(R.id.fragmentBanner) } private fun loadAds(){ admobBanner.loadBannerAds( activity, binding.adsBannerPlaceHolder, getResString(R.string.admob_banner_ids), RemoteConstants.rcvBannerAd, diComponent.sharedPreferenceUtils.isAppPurchased, diComponent.internetManager.isInternetConnected, BannerType.COLLAPSIBLE_BOTTOM, object : BannerCallBack { override fun onAdFailedToLoad(adError: String) {} override fun onAdLoaded() {} override fun onAdImpression() {} override fun onPreloaded() {} override fun onAdClicked() {} override fun onAdClosed() { isCollapsibleOpen = false if (isBackPressed){ adsObserver.value = true } } override fun onAdOpened() { isCollapsibleOpen = true } } ) } override fun onPause() { admobBanner.bannerOnPause() super.onPause() } override fun onResume() { admobBanner.bannerOnResume() super.onResume() } override fun onDestroy() { admobBanner.bannerOnDestroy() super.onDestroy() } }
1
Kotlin
5
2
9531cc5b3698fc4ca74745f8352abea9d05fb7cf
3,076
Admob-Ads
Apache License 2.0
desktop/src/main/kotlin/ui/screen/StartupScreen.kt
kotpot
696,232,990
false
null
package org.kotpot.cosmos.desktop.ui.screen import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.* import org.kotpot.cosmos.desktop.di.appModule import org.kotpot.cosmos.desktop.global.GlobalRouteManager import org.kotpot.cosmos.desktop.ui.theme.Monorale import org.kotpot.cosmos.shared.di.initKoin private suspend fun waitInit() = withContext(Dispatchers.IO) { initKoin(appDeclaration = { modules(appModule) }) // init theme config // init client config // init user delay(2000) } @Composable fun Startup() { LaunchedEffect(true) { waitInit() GlobalRouteManager.animeToSetup() } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Row { Text( text = "cosmos", style = TextStyle( fontFamily = Monorale, fontSize = 64.sp, lineHeight = 64.sp, fontWeight = FontWeight.SemiBold, baselineShift = BaselineShift(0.25f) ), color = MaterialTheme.colorScheme.onSurface, ) Image( painter = painterResource("image/title_logo.svg"), contentDescription = null, modifier = Modifier.padding(start = 16.dp).height(80.dp).width(54.dp) ) } } }
0
null
2
8
b4c10a7d04477d7f1d3a0b8824fb27240c4e526e
2,047
cosmos-client
MIT License
app/src/main/java/com/example/bagstore/Model/Data/LoginResponse.kt
pixel-Alireza
634,630,481
false
null
package ir.dunijet.dunibazaar.model.data data class LoginResponse( val expiresAt: Int, val message: String, val success: Boolean, val token: String )
0
null
0
4
08e55ac89f51448ec8a654de3b393b9fb8d79add
166
Bag-Store
MIT License
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/types/ContentFiles.kt
slatekit
55,942,000
false
null
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: <NAME> * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.types /** * Represents string content type/format information. * * Use cases: * 1. Provide type info on a string * 2. Provide intent that the string should be treated as file vs content ( See Content.kt ) * 3. Provide a way for consumers to infer the intent of the string. * e.g. the API server can determine that if a service returns a Doc instead of a string, * then the Doc should be sent back as a File instead of a string */ object ContentFiles { @JvmStatic val empty = ContentFile("", byteArrayOf(),"", ContentTypes.Plain) @JvmStatic fun text(name: String, content: String): ContentFile = ContentFile(name, content.toByteArray(), content, ContentTypes.Plain) @JvmStatic fun html(name: String, content: String): ContentFile = ContentFile(name, content.toByteArray(), content, ContentTypes.Html) @JvmStatic fun json(name: String, content: String): ContentFile = ContentFile(name, content.toByteArray(), content, ContentTypes.Json) @JvmStatic fun csv(name: String, content: String): ContentFile = ContentFile(name, content.toByteArray(), content, ContentTypes.Csv) @JvmStatic fun other(name: String, content: String, tpe: ContentType): ContentFile = ContentFile(name, content.toByteArray(), content, tpe) }
6
Kotlin
12
107
f8ae048bc7d19704a2558e1d02374e98782e7b47
1,695
slatekit
Apache License 2.0
app/src/main/java/hiendao/moviefinder/presentation/main/favorite/FavoriteScreen.kt
HienDao14
826,173,311
false
{"Kotlin": 469154}
package hiendao.moviefinder.presentation.main.favorite import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.pulltorefresh.PullToRefreshContainer import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import hiendao.moviefinder.presentation.state.FavoriteScreenState import hiendao.moviefinder.presentation.uiEvent.FavoriteScreenEvent import hiendao.moviefinder.util.NavRoute import hiendao.moviefinder.util.shared_components.CustomImage import kotlinx.coroutines.delay import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun FavoriteScreen( modifier: Modifier = Modifier, navHostController: NavHostController, favoriteScreenState: FavoriteScreenState, onEvent: (FavoriteScreenEvent) -> Unit ) { val refreshScope = rememberCoroutineScope() var isRefreshing by remember { mutableStateOf(false) } fun refresh() = refreshScope.launch { isRefreshing = true //function refresh onEvent(FavoriteScreenEvent.Refresh("Favorite")) delay(3000) isRefreshing = false } val refreshState = rememberPullToRefreshState() val movies = favoriteScreenState.movieFavorite val credits = favoriteScreenState.creditFavorite val listSeries = favoriteScreenState.seriesFavorite LaunchedEffect(key1 = true) { onEvent(FavoriteScreenEvent.Refresh("Favorite")) } Box( modifier = Modifier .fillMaxSize() .nestedScroll(refreshState.nestedScrollConnection) ) { Column( modifier = modifier .fillMaxWidth() .padding(top = 100.dp, start = 10.dp, end = 10.dp) .verticalScroll(state = rememberScrollState()) ) { if (movies.isNotEmpty()) { Text( text = "Favorite Movies", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp) ) Spacer(modifier = Modifier.height(16.dp)) LazyRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp) ) { items(movies.size) { index -> val movie = movies[index] CustomImage(imageUrl = movie.posterPath, width = 120.dp, height = 180.dp) { navHostController.navigate("${NavRoute.DETAIL_SCREEN}?movieId=${movie.id}") } if (index >= movies.size - 1 && !favoriteScreenState.isLoading) { onEvent(FavoriteScreenEvent.OnPaginate("Movie")) } } } Spacer(modifier = Modifier.height(10.dp)) } if (listSeries.isNotEmpty()) { Text( text = "Favorite Tv Series", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp) ) Spacer(modifier = Modifier.height(16.dp)) LazyRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp) ) { items(listSeries.size) { index -> val series = listSeries[index] CustomImage(imageUrl = series.posterPath, width = 120.dp, height = 180.dp) { navHostController.navigate("${NavRoute.DETAIL_SCREEN}?seriesId=${series.id}") } if (index >= movies.size - 1 && !favoriteScreenState.isLoading) { onEvent(FavoriteScreenEvent.OnPaginate("Tv Series")) } } } Spacer(modifier = Modifier.height(10.dp)) } if (credits.isNotEmpty()) { Text( text = "Favorite Credits", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp) ) Spacer(modifier = Modifier.height(16.dp)) LazyRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp) ) { items(credits.size) { index -> val credit = credits[index] CustomImage( imageUrl = credit.profilePath, width = 120.dp, height = 180.dp ) { navHostController.navigate("${NavRoute.CREDIT_SCREEN}?creditId=${credit.id}") } if (index >= credits.size - 1 && !favoriteScreenState.isLoading) { onEvent(FavoriteScreenEvent.OnPaginate("Credit")) } } } Spacer(modifier = Modifier.height(30.dp)) } } if (refreshState.isRefreshing) { LaunchedEffect(true) { refresh() } } LaunchedEffect(isRefreshing) { if (isRefreshing) { refreshState.startRefresh() } else { refreshState.endRefresh() } } PullToRefreshContainer(state = refreshState, modifier = Modifier.align(Alignment.TopCenter)) } }
0
Kotlin
1
0
7f3f66b7a169ece9b34c7488455654c08353ee2d
7,278
Movie-Discover
MIT License
DriverDataUI/src/main/java/com/drivequant/drivekit/ui/extension/TripExtension.kt
DriveQuantPublic
216,339,559
false
{"Kotlin": 1643694, "Java": 8753}
package com.drivequant.drivekit.ui.extension import android.app.Activity import android.content.Context import android.graphics.Typeface.BOLD import android.graphics.drawable.Drawable import android.text.Spannable import com.drivequant.drivekit.common.ui.DriveKitUI import com.drivequant.drivekit.common.ui.component.triplist.DKTripListItem import com.drivequant.drivekit.common.ui.component.triplist.TripData import com.drivequant.drivekit.common.ui.extension.ceilDuration import com.drivequant.drivekit.common.ui.extension.formatDateWithPattern import com.drivequant.drivekit.common.ui.extension.resSpans import com.drivequant.drivekit.common.ui.utils.DKDatePattern import com.drivequant.drivekit.common.ui.utils.DKSpannable import com.drivequant.drivekit.databaseutils.entity.Trip import com.drivequant.drivekit.ui.DriverDataUI import com.drivequant.drivekit.ui.tripdetail.activity.TripDetailActivity import java.text.SimpleDateFormat import java.util.Date import java.util.Locale fun List<Trip>.computeSafetyScoreAverage(): Double { val scoredTrips = this.filter { it.safety?.safetyScore != null && it.safety?.safetyScore!! <= 10.0 } return if (this.isEmpty() || scoredTrips.isEmpty()){ 11.0 } else { val sumScore = scoredTrips.mapNotNull { it.safety?.safetyScore }.sum() sumScore.div(scoredTrips.size) } } fun List<Trip>.computeEcoDrivingScoreAverage(): Double { val scoredTrips = this.filter { it.ecoDriving?.score != null && it.ecoDriving?.score!! <= 10.0 } return if (this.isEmpty() || scoredTrips.isEmpty()) { 11.0 } else { val sumScore = scoredTrips.mapNotNull { it.ecoDriving?.score }.sum() sumScore.div(scoredTrips.size) } } fun List<Trip>.computeDistractionScoreAverage(): Double { return if (this.isEmpty()) { 11.0 } else { val sumScore = this.mapNotNull { it.driverDistraction?.score }.sum() sumScore.div(this.size) } } fun List<Trip>.computeSpeedingScoreAverage(): Double { return if (this.isEmpty()) { 11.0 } else { val sumScore = this.mapNotNull { it.speedingStatistics?.score }.sum() sumScore.div(this.size) } } fun List<Trip>.computeActiveDays(): Int { val sdf = SimpleDateFormat(DKDatePattern.STANDARD_DATE.getPattern(), Locale.getDefault()) return this.distinctBy { it.endDate.formatDateWithPattern(sdf) }.size } fun List<Trip>.computeTotalDistance(): Double { val iterator = this.listIterator() var totalDistance: Double = 0.toDouble() for (currentTrip in iterator) { currentTrip.tripStatistics?.distance.let { if (it != null) { totalDistance += it } } } return totalDistance } fun List<Trip>.computeTotalDuration(): Double { val iterator = this.listIterator() var totalDuration: Double = 0.toDouble() for (currentTrip in iterator) { currentTrip.tripStatistics?.duration.let { if (it != null) { totalDuration += it } } } return totalDuration } fun List<Trip>.computeCeilDuration(): Double { val iterator = this.listIterator() var totalDuration: Double = 0.toDouble() for (currentTrip in iterator) { totalDuration += currentTrip.computeCeilDuration().toInt() } return totalDuration } fun Trip.computeCeilDuration(): Double { this.tripStatistics?.duration?.let { return it.ceilDuration() } ?: run { return 0.0 } } fun Trip.getOrComputeStartDate(): Date? { if (this.startDate != null) { return this.startDate } else { this.tripStatistics?.duration?.let { return Date(this.endDate.time - (it * 1000).toLong()) } } return null } fun Trip.computeRoadContext(): Int { var biggestDistance = 0.0 var majorRoadContext = 0 for (i in this.safetyContexts.indices) { if (this.safetyContexts[i].distance > biggestDistance) { biggestDistance = this.safetyContexts[i].distance majorRoadContext = this.safetyContexts[i].contextId } } return if (majorRoadContext == 0) 1 else majorRoadContext } internal fun Trip.toDKTripItem() = object : DKTripListItem { val trip = this@toDKTripItem override fun getChildObject() = trip override fun getItinId(): String = trip.itinId override fun getDuration(): Double? = trip.tripStatistics?.duration override fun getDistance(): Double? = trip.tripStatistics?.distance override fun getStartDate(): Date? = trip.startDate override fun getEndDate(): Date = trip.endDate override fun getDepartureCity(): String = trip.departureCity override fun getDepartureAddress(): String = trip.departureAddress override fun getArrivalCity(): String = trip.arrivalCity override fun getArrivalAddress(): String = trip.arrivalAddress override fun isScored(tripData: TripData): Boolean = when (tripData) { TripData.SAFETY, TripData.ECO_DRIVING -> !trip.unscored TripData.DISTRACTION -> !trip.unscored && trip.driverDistraction != null TripData.SPEEDING -> !trip.unscored && trip.speedingStatistics != null TripData.DISTANCE, TripData.DURATION -> true } override fun getScore(tripData: TripData): Double? = when (tripData) { TripData.SAFETY -> trip.safety?.safetyScore TripData.ECO_DRIVING -> trip.ecoDriving?.score TripData.DISTRACTION -> trip.driverDistraction?.score TripData.SPEEDING -> trip.speedingStatistics?.score TripData.DISTANCE -> trip.tripStatistics?.distance TripData.DURATION -> trip.tripStatistics?.duration } override fun getTransportationModeResource(context: Context): Drawable? = trip.declaredTransportationMode?.transportationMode?.image(context) ?: run { trip.transportationMode.image(context) } override fun isAlternative(): Boolean = trip.transportationMode.isAlternative() override fun infoText(context: Context): Spannable? { DriverDataUI.customTripInfo?.let { return it.infoText(context, trip) } ?: run { return if (trip.tripAdvices.size > 1) { DKSpannable().append("${trip.tripAdvices.size}", context.resSpans { color(DriveKitUI.colors.fontColorOnSecondaryColor()) typeface(BOLD) size(com.drivequant.drivekit.common.ui.R.dimen.dk_text_very_small) }).toSpannable() } else { null } } } override fun infoImageResource(): Int? { return DriverDataUI.customTripInfo?.infoImageResource(trip) ?: run { val count = trip.tripAdvices.size if (count > 1) { return com.drivequant.drivekit.common.ui.R.drawable.dk_common_trip_info_count } else if (count == 1) { val theme = trip.tripAdvices.first().theme if (theme == "SAFETY") { return com.drivequant.drivekit.common.ui.R.drawable.dk_common_safety_advice } else if (theme == "ECODRIVING") { return com.drivequant.drivekit.common.ui.R.drawable.dk_common_eco_advice } } return null } } override fun infoClickAction(context: Context) { return DriverDataUI.customTripInfo?.infoClickAction(context, trip) ?: run { TripDetailActivity.launchActivity( context as Activity, trip.itinId, openAdvice = true ) } } override fun hasInfoActionConfigured(): Boolean = DriverDataUI.customTripInfo?.hasInfoActionConfigured(trip) ?: false override fun isInfoDisplayable(): Boolean = (DriverDataUI.customTripInfo?.isInfoDisplayable(trip) ?: !trip.tripAdvices.isNullOrEmpty()) && !trip.transportationMode.isAlternative() } internal fun List<Trip>.toDKTripList(): List<DKTripListItem> = this.map { it.toDKTripItem() }
1
Kotlin
3
9
e7956263157c49aae8d6f993a558ea77d9658ee6
8,147
drivekit-ui-android
Apache License 2.0
common/kotlinx-coroutines-core-common/src/CoroutineDispatcher.kt
objcode
159,731,828
true
{"Kotlin": 1762279, "CSS": 8215, "Shell": 3255, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Java": 356, "Prolog": 299}
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.experimental import kotlin.coroutines.experimental.* /** * Base class that shall be extended by all coroutine dispatcher implementations. * * The following standard implementations are provided by `kotlinx.coroutines` as properties on * [Dispatchers] objects: * * * [Dispatchers.Default] -- is used by all standard builder if no dispatcher nor any other [ContinuationInterceptor] * is specified in their context. It uses a common pool of shared background threads. * This is an appropriate choice for compute-intensive coroutines that consume CPU resources. * * [Dispatchers.IO] -- uses a shared pool of on-demand created threads and is designed for offloading of IO-intensive _blocking_ * operations (like file I/O and blocking socket I/O). * * [Dispatchers.Unconfined] -- starts coroutine execution in the current call-frame until the first suspension. * On first suspension the coroutine builder function returns. * The coroutine resumes in whatever thread that is used by the * corresponding suspending function, without confining it to any specific thread or pool. * **Unconfined dispatcher should not be normally used in code**. * * Private thread pools can be created with [newSingleThreadContext] and [newFixedThreadPoolContext]. * * An arbitrary [Executor][java.util.concurrent.Executor] can be converted to dispatcher with [asCoroutineDispatcher] extension function. * * This class ensures that debugging facilities in [newCoroutineContext] function work properly. */ public abstract class CoroutineDispatcher : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { /** * Returns `true` if execution shall be dispatched onto another thread. * The default behaviour for most dispatchers is to return `true`. * * UI dispatchers _should not_ override `isDispatchNeeded`, but leave a default implementation that * returns `true`. To understand the rationale beyond this recommendation, consider the following code: * * ```kotlin * fun asyncUpdateUI() = async(MainThread) { * // do something here that updates something in UI * } * ``` * * When you invoke `asyncUpdateUI` in some background thread, it immediately continues to the next * line, while UI update happens asynchronously in the UI thread. However, if you invoke * it in the UI thread itself, it updates UI _synchronously_ if your `isDispatchNeeded` is * overridden with a thread check. Checking if we are already in the UI thread seems more * efficient (and it might indeed save a few CPU cycles), but this subtle and context-sensitive * difference in behavior makes the resulting async code harder to debug. * * Basically, the choice here is between "JS-style" asynchronous approach (async actions * are always postponed to be executed later in the even dispatch thread) and "C#-style" approach * (async actions are executed in the invoker thread until the first suspension point). * While, C# approach seems to be more efficient, it ends up with recommendations like * "use `yield` if you need to ....". This is error-prone. JS-style approach is more consistent * and does not require programmers to think about whether they need to yield or not. * * However, coroutine builders like [launch][CoroutineScope.launch] and [async][CoroutineScope.async] accept an optional [CoroutineStart] * parameter that allows one to optionally choose C#-style [CoroutineStart.UNDISPATCHED] behaviour * whenever it is needed for efficiency. * * **Note: This is an experimental api.** Execution semantics of coroutines may change in the future when this function returns `false`. */ @ExperimentalCoroutinesApi public open fun isDispatchNeeded(context: CoroutineContext): Boolean = true /** * Dispatches execution of a runnable [block] onto another thread in the given [context]. */ public abstract fun dispatch(context: CoroutineContext, block: Runnable) /** * Dispatches execution of a runnable [block] onto another thread in the given [context] * with a hint for dispatcher that current dispatch is triggered by [yield] call, so execution of this * continuation may be delayed in favor of already dispatched coroutines. * * **Implementation note** though yield marker may be passed as a part of [context], this * is a separate method for performance reasons * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public open fun dispatchYield(context: CoroutineContext, block: Runnable) = dispatch(context, block) /** * Returns continuation that wraps the original [continuation], thus intercepting all resumptions. */ public final override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = DispatchedContinuation(this, continuation) /** * @suppress **Error**: Operator '+' on two CoroutineDispatcher objects is meaningless. * CoroutineDispatcher is a coroutine context element and `+` is a set-sum operator for coroutine contexts. * The dispatcher to the right of `+` just replaces the dispatcher the left of `+`. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated( message = "Operator '+' on two CoroutineDispatcher objects is meaningless. " + "CoroutineDispatcher is a coroutine context element and `+` is a set-sum operator for coroutine contexts. " + "The dispatcher to the right of `+` just replaces the dispatcher the left of `+`.", level = DeprecationLevel.ERROR ) public operator fun plus(other: CoroutineDispatcher) = other // for nicer debugging override fun toString(): String = "$classSimpleName@$hexAddress" }
1
Kotlin
2
5
46741db4b0c2863475d5cc6fc75eafadd8e6199d
6,049
kotlinx.coroutines
Apache License 2.0
src/main/kotlin/org/jetbrains/teamcity/rest/models/agent/AgentPools.kt
JetBrains
321,975,548
false
{"Kotlin": 638039}
/** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package org.jetbrains.teamcity.rest.models import com.google.gson.annotations.SerializedName import org.jetbrains.teamcity.rest.base.* import org.jetbrains.teamcity.rest.infrastructure.ApiClient import org.jetbrains.teamcity.rest.infrastructure.RequestConfig import java.time.LocalDateTime /** Represents a paginated list of AgentPool entities. * @param count * @param href * @param nextHref * @param prevHref * @param agentPool */ data class AgentPools( @SerializedName("count") override val count: Int? = null, @SerializedName("href") override val href: String? = null, @SerializedName("nextHref") override val nextHref: String? = null, @SerializedName("prevHref") override val prevHref: String? = null, @SerializedName("agentPool") val agentPool: List<AgentPool>? = null ) : PaginatedEntity<AgentPool>() { @Transient private val classModelName: String = "agentPools" override fun items(): List<AgentPool> { if (agentPool == null) return emptyList() return agentPool } override fun requestNextPage(apiClient: ApiClient, requestConfig: RequestConfig): AgentPools { val response = apiClient.request<AgentPools>(requestConfig) return ApiClient.processResponse(response) } }
0
Kotlin
1
1
0e29bfb12d0d17c481c295d8ec89815a4a9fb0c2
1,444
teamcity-rest-auto-kotlin-client
Apache License 2.0
core/src/main/kotlin/com/oxviewer/core/source/Search.kt
0xViewer
127,707,384
false
null
/* * Copyright 2018 Hippo Seven * * 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.oxviewer.core.source /** * Query pattern determines how users could configure [query parameters][Parameters]. */ class Pattern(builder: Builder) { val options = builder.options.toList() class Builder { val options = mutableListOf<Option>() /** * Adds a query option to this query pattern builder. */ fun add(option: Option): Builder { options.add(option) return this } fun build(): Pattern { // Check duplicate key val map = mutableMapOf<String, Option>() for (option in options) { if (map.containsKey(option.key)) { throw IllegalStateException("Two options with a same key: ${option.key}. " + "One option is ${map[option.key]}, the other option is $option.") } map[option.key] = option } return Pattern(this) } } } /** * Query parameters are generated by user with [query pattern][Pattern]. */ class Parameters(private val values: Map<String, Any>) { /** * Returns the boolean value with the key. */ fun boolean(key: String): Boolean = values[key] as Boolean /** * Returns the string value with the key. */ fun string(key: String): String = values[key] as String } /** * Abstract options of [query pattern][Parameters]. * Options are user-configurable. Users may assign actual values to them. * Each option holds a key, a name, a default value and a suggestion. * * @param key the identify of the option, duplicate key in one * [query parameters][Parameters] is illegal. * @param name the display name of the option * @param suggestion the suggestion about how the option looks */ sealed class Option(open val key: String, open val name: String, open val suggestion: String?) /** * True-or-false options. * * @see Parameters.boolean */ data class Switch constructor( override val key: String, override val name: String, val default: Boolean, override val suggestion: String? ) : Option(key, name, suggestion) /** * Custom text options. * * @see Parameters.string */ data class Text constructor( override val key: String, override val name: String, val default: String, override val suggestion: String? ) : Option(key, name, suggestion) // TODO more options // TODO option group?
0
Kotlin
0
1
af449253143eb8594a5aeabe7396d4fc980fb9c4
2,916
0xviewer-core
Apache License 2.0
bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/config/TaskConfigProperties.kt
eclipse-tractusx
526,621,398
false
{"Kotlin": 1676770, "Smarty": 17727, "Dockerfile": 4173, "Java": 2019, "Shell": 1136, "Batchfile": 1123}
/******************************************************************************* * Copyright (c) 2021,2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.eclipse.tractusx.bpdm.orchestrator.config import org.springframework.boot.context.properties.ConfigurationProperties import java.time.Duration @ConfigurationProperties(prefix = "bpdm.task") data class TaskConfigProperties( // Duration after which a task is removed from the Orchestrator after creation val taskTimeout: Duration = Duration.ofHours(3 * 24), // Duration for which a reservation is valid and results are accepted val taskReservationTimeout: Duration = Duration.ofHours(24) )
73
Kotlin
6
5
53f6fdcb82ca0398864d924c65e2f818ad843097
1,423
bpdm
Apache License 2.0
src/com/price_of_command/pc_CampaignEventListener.kt
atlanticaccent
409,181,802
false
null
package com.price_of_command import com.fs.starfarer.api.Global import com.fs.starfarer.api.campaign.BaseCampaignEventListener import com.fs.starfarer.api.characters.PersonAPI import com.fs.starfarer.api.combat.EngagementResultAPI import com.fs.starfarer.api.fleet.FleetMemberAPI import com.fs.starfarer.api.impl.campaign.BattleAutoresolverPluginImpl import com.price_of_command.conditions.* object pc_CampaignEventListener : BaseCampaignEventListener(false) { private const val RESTORE_FLEET_ASSIGNMENTS = "pc_restore_fleet_assignments" private const val FLEET_ASSIGNMENT_TO_RESTORE = "pc_fleet_assignments_to_restore" var restoreFleetAssignments: Boolean get() = Global.getSector().memoryWithoutUpdate.escape()[RESTORE_FLEET_ASSIGNMENTS] as? Boolean ?: true set(value) { Global.getSector().memoryWithoutUpdate.escape()[RESTORE_FLEET_ASSIGNMENTS] = value } @Suppress("UNCHECKED_CAST") var fleetAssignment: Map<FleetMemberAPI, PersonAPI>? get() = Global.getSector().memoryWithoutUpdate.escape()[FLEET_ASSIGNMENT_TO_RESTORE] as? Map<FleetMemberAPI, PersonAPI> set(value) { Global.getSector().memoryWithoutUpdate.escape()[FLEET_ASSIGNMENT_TO_RESTORE] = value } override fun reportPlayerEngagement(resultAPI: EngagementResultAPI) { val (result, opposition) = if (resultAPI.didPlayerWin()) { resultAPI.winnerResult to resultAPI.loserResult.fleet.nameWithFactionKeepCase } else { resultAPI.loserResult to resultAPI.winnerResult.fleet.nameWithFactionKeepCase } val captainedShips = if (result is BattleAutoresolverPluginImpl.EngagementResultForFleetImpl) { result.deployed } else { result.allEverDeployedCopy.map { it.member } }.filter { it.captain.run { playerOfficers().containsPerson(this) && !isPlayer } } var appliedConditions = emptyList<Condition>() for (deployed in captainedShips) { val officer = deployed.captain val significantDamage = result.destroyed.contains(deployed) || result.disabled.contains(deployed) || deployed.status.hullFraction <= 0.2 val condition = if (significantDamage) { ConditionManager.addPreconditionOverride(true) { (it is Injury && it.target == officer).andThenOrNull { it.precondition().noop { Outcome.Applied(it) } } } Injury(officer, ConditionManager.now, emptyList()) } else { Fatigue(officer, ConditionManager.now) } val outcome = condition.tryInflictAppend("Combat with $opposition") if (outcome is Outcome.Applied<*>) { when (outcome.condition) { is Fatigue -> logger().debug("Fatigued officer ${officer.nameString}") is Injury -> logger().debug("Failed to fatigue officer ${officer.nameString}, injured them instead") is GraveInjury -> logger().debug("Failed to fatigue or injure officer ${officer.nameString}, gravely injuring them instead") is Wound -> logger().debug("Did not fatigue ${officer.nameString}, applied some kind of wound instead ${outcome.condition}") else -> { logger().debug("${officer.nameString} was not fatigued or injured when trying to fatigue. This is probably a bug") logger().debug(outcome.condition) } } } else if (outcome is Outcome.Terminal) { logger().debug(outcome) } if (outcome is Outcome.Applied<*> || outcome is Outcome.Terminal) { appliedConditions = appliedConditions.plus(condition) } } tryRestoreFleetAssignments() } fun tryRestoreFleetAssignments() { val fleetAssignment = fleetAssignment if (restoreFleetAssignments && fleetAssignment != null) { playerFleet().fleetData.membersInPriorityOrder.forEach { val officer = fleetAssignment[it] if (officer != null && !officer.hasTag(PoC_OFFICER_DEAD)) { it.captain = officer if (it.captain.isPlayer) { it.isFlagship = true } } else { it.captain = null } } } } }
0
Kotlin
0
0
a3944e87456d324ef645de79e988fb1c43013fc8
4,629
officer-expansion
The Unlicense
api-core/src/commonMain/kotlin/su/pank/yamusic/account/model/UserSettings.kt
pank-su
717,339,473
false
{"Kotlin": 82681}
package su.pank.yamusic.account.model import kotlinx.datetime.Instant import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonNames @Serializable data class UserSettings( var uid: Int? = null, var lastFmScrobblingEnabled: Boolean, var facebookScrobblingEnabled: Boolean, var shuffleEnabled: Boolean, var addNewTrackOnPlaylistTop: Boolean, var volumePercents: Int, var userMusicVisibility: Visibility, var userSocialVisibility: Visibility, var modified: Instant? = null, var theme: Theme, var promosDisabled: Boolean, var autoPlayRadio: Boolean, var syncQueueEnabled: Boolean, var childModEnabled: Boolean?, var adsDisabled: Boolean? ) { // suspend fun <T> update(property: KMutableProperty1<UserSettings, T>, newValue: T): UserSettings { // return update(hashMapOf(property to newValue)) // } // // suspend fun update(propertyToValues: HashMap<KMutableProperty1<UserSettings, *>, *>): UserSettings { // val normalHashMap = hashMapOf<String, String>( // // ) // propertyToValues.forEach { // normalHashMap[it.key.name] = it.value!!.toString().lowercase() // } // // return client!!.requestForm<UserSettings>("account", "settings", body = normalHashMap) // } } @Serializable enum class Theme { @SerialName("white") White, @SerialName("black") Black } @OptIn(ExperimentalSerializationApi::class) @Serializable enum class Visibility { @JsonNames("PUBLIC", "public") PUBLIC, @JsonNames("PRIVATE", "private") PRIVATE }
4
Kotlin
0
4
3c80dad225f8bbfee32b1279feb52aaa70224ec4
1,698
yandex-music-api
MIT License
fearless-utils/src/main/java/jp/co/soramitsu/fearless_utils/encrypt/keypair/Keypair.kt
novasamatech
429,839,517
false
{"Kotlin": 642383, "Rust": 10890, "Java": 4260}
package jp.co.soramitsu.fearless_utils.encrypt.keypair interface Keypair { val privateKey: ByteArray val publicKey: ByteArray } class BaseKeypair( override val privateKey: ByteArray, override val publicKey: ByteArray ) : Keypair
4
Kotlin
5
5
c15e6567c62527611e25009e54b9896415799847
247
substrate-sdk-android
Apache License 2.0
app/src/main/java/com/ufpb/meuguia/model/Attraction.kt
Israelpsilva8246
844,104,278
false
{"Kotlin": 102658}
package com.ufpb.meuguia.model data class Attraction( val id: String, val name: String, val description: String, val map_link: String, val city: String, val state: String, val image_link: String, val fonte: String, val segmentations: List<TurismSegmentation>, val attractionTypes: AttractionType, val moreInfoLinkList: List<MoreInfoLink> )
0
Kotlin
0
0
67ef335c4f98dbc2aaf21fe40a14eacbe9391175
384
app-meu-guiaPB
MIT License
app/src/main/java/com/ufpb/meuguia/model/Attraction.kt
Israelpsilva8246
844,104,278
false
{"Kotlin": 102658}
package com.ufpb.meuguia.model data class Attraction( val id: String, val name: String, val description: String, val map_link: String, val city: String, val state: String, val image_link: String, val fonte: String, val segmentations: List<TurismSegmentation>, val attractionTypes: AttractionType, val moreInfoLinkList: List<MoreInfoLink> )
0
Kotlin
0
0
67ef335c4f98dbc2aaf21fe40a14eacbe9391175
384
app-meu-guiaPB
MIT License
src/test/kotlin/ui/frames/RequestsTabFrame.kt
prabint
569,996,326
false
{"Kotlin": 106093}
package ui.frames import com.intellij.remoterobot.RemoteRobot import com.intellij.remoterobot.data.RemoteComponent import com.intellij.remoterobot.fixtures.CommonContainerFixture import com.intellij.remoterobot.fixtures.DefaultXpath import com.intellij.remoterobot.fixtures.FixtureName import com.intellij.remoterobot.fixtures.JTableFixture import com.intellij.remoterobot.search.locators.byXpath import java.time.Duration fun RemoteRobot.requestsTabFrame(function: RequestsTabFrame.() -> Unit) { find(RequestsTabFrame::class.java, Duration.ofSeconds(10)).apply(function) } @FixtureName("Requests Tab Frame") @DefaultXpath("title API Request Editor", "//div[@title='API Request Editor' and @class='MyDialog']") class RequestsTabFrame( remoteRobot: RemoteRobot, remoteComponent: RemoteComponent ) : CommonContainerFixture(remoteRobot, remoteComponent) { val tab get() = jLabel("Requests") val requestsList get() = jList(byXpath("//div[@accessiblename='Requests list']")) val addNewRequestButton get() = button(byXpath("//div[@accessiblename='Add new request']")) val cloneRequestButton get() = button(byXpath("//div[@accessiblename='Clone request']")) val nameField get() = textField(byXpath("//div[@accessiblename='Request name']")) val searchField get() = textField(byXpath("//div[@accessiblename='Search field']")) val executeButton get() = button(byXpath("//div[@accessiblename='Execute api']")) val methodField get() = comboBox(byXpath("//div[@accessiblename='Request method']")) val urlField get() = textField(byXpath("//div[@accessiblename='Request url']")) val headerTable get() = remoteRobot.find(JTableFixture::class.java, byXpath("//div[@accessiblename='Request header table']")) val headerTableAddRowButton get() = button(byXpath("//div[@accessiblename='Add header row']")) val formatBodyButton get() = button(byXpath("//div[@accessiblename='Format body']")) val bodyField get() = textField(byXpath("//div[@accessiblename='Request body']")) val outputLabel get() = jLabel(byXpath("//div[@accessiblename='Request output label']")) val outputField get() = textArea(byXpath("//div[@accessiblename='Request output']")) }
1
Kotlin
1
4
351f86f158e38144ea2d561e82bf069765ab629b
2,337
api-bank
MIT License
sample/src/main/java/me/panpf/adapter/sample/vm/ListStatus.kt
jjzhoujun
239,247,760
true
{"Java": 205214, "Kotlin": 8596}
package me.panpf.adapter.sample.vm import androidx.lifecycle.MutableLiveData import androidx.paging.PagedList sealed class ListStatus class Initialize : ListStatus() class InitializeSuccess : ListStatus() class InitializError : ListStatus() class LoadMore : ListStatus() class LoadMoreSuccess : ListStatus() class LoadMoreError : ListStatus() class Empty : ListStatus() class End : ListStatus() class EndAtFront : ListStatus() class ListBoundaryCallback<Value>(private val listBoundaryLiveData: MutableLiveData<ListStatus>) : PagedList.BoundaryCallback<Value>() { override fun onZeroItemsLoaded() { super.onZeroItemsLoaded() listBoundaryLiveData.value = Empty() } override fun onItemAtEndLoaded(itemAtEnd: Value) { super.onItemAtEndLoaded(itemAtEnd) listBoundaryLiveData.value = End() } override fun onItemAtFrontLoaded(itemAtFront: Value) { super.onItemAtFrontLoaded(itemAtFront) listBoundaryLiveData.value = EndAtFront() } }
0
null
0
0
cd6995a8b903c88a52b2f9be8de7cd276636d6d6
1,005
assembly-adapter
Apache License 2.0
library/src/main/java/com/omega_r/bind/model/binders/LongClickBinder.kt
Omega-R
321,930,245
false
null
package com.omega_r.bind.model.binders import android.view.View import androidx.annotation.IdRes import com.omega_r.bind.model.BindModel open class LongClickBinder<M>( override val id: Int, private val block: (M) -> Boolean ) : Binder<View, M, Any>() { override fun bind(itemView: View, item: M) { itemView.setOnLongClickListener { block(item) } } } fun <M> BindModel.Builder<M>.bindLongClick(@IdRes id: Int, block: (M) -> Boolean) = bindBinder(LongClickBinder(id, block))
0
Kotlin
0
0
fd7a8c1a97e7dfadaa6fd2cc349e57f3b58b9a06
521
OmegaBind
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/NfcSlash.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.NfcSlash: ImageVector get() { if (_nfcSlash != null) { return _nfcSlash!! } _nfcSlash = Builder(name = "NfcSlash", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(23.0f, 20.88f) lineTo(23.0f, 4.5f) curveToRelative(0.0f, -1.93f, -1.57f, -3.5f, -3.5f, -3.5f) lineTo(4.5f, 1.0f) curveToRelative(-0.4f, 0.0f, -0.8f, 0.07f, -1.18f, 0.2f) lineTo(2.16f, 0.04f) lineTo(0.04f, 2.16f) lineTo(21.84f, 23.96f) lineToRelative(2.12f, -2.12f) lineToRelative(-0.96f, -0.96f) close() moveTo(19.5f, 4.0f) curveToRelative(0.28f, 0.0f, 0.5f, 0.22f, 0.5f, 0.5f) verticalLineToRelative(13.38f) lineToRelative(-2.0f, -2.0f) lineTo(18.0f, 6.0f) horizontalLineToRelative(-2.55f) lineToRelative(-3.0f, 3.0f) horizontalLineToRelative(2.55f) verticalLineToRelative(3.88f) lineToRelative(-4.63f, -4.63f) lineToRelative(2.25f, -2.25f) horizontalLineToRelative(-4.5f) lineToRelative(-2.0f, -2.0f) horizontalLineToRelative(13.38f) close() moveTo(9.0f, 13.95f) verticalLineToRelative(1.05f) horizontalLineToRelative(1.05f) lineToRelative(3.0f, 3.0f) lineTo(6.0f, 18.0f) verticalLineToRelative(-7.05f) lineToRelative(3.0f, 3.0f) close() moveTo(15.05f, 20.0f) lineToRelative(3.0f, 3.0f) lineTo(1.0f, 23.0f) lineTo(1.0f, 5.95f) lineToRelative(3.0f, 3.0f) verticalLineToRelative(11.05f) lineTo(15.05f, 20.0f) close() } } .build() return _nfcSlash!! } private var _nfcSlash: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,002
icons
MIT License
github-crawler-core/src/main/kotlin/com/societegenerale/githubcrawler/output/CIdroidReadyJsonFileOutput.kt
societe-generale
136,929,288
false
null
package com.societegenerale.githubcrawler.output import com.societegenerale.githubcrawler.model.Repository import org.slf4j.LoggerFactory import java.io.BufferedWriter import java.io.File import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.OpenOption import java.nio.file.Paths import java.nio.file.StandardOpenOption import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.* /** * This is a specific output, when targeting to pipe the crawler output into CI-droid. CI-droid exposes a "bulk-actions API" that accepts an action to perform on a list of resources (that can be on many repositories). * * When using this output, we try to generate the list of resources, in a format as close as possible as the one expected by CI-droid, so that we don't need any re-processing and can directly copy-paste the content in the list of the resources in the json payload we're posting on the API. */ class CIdroidReadyJsonFileOutput (val indicatorsToOutput: List<String>, val withTags: Boolean=false) : GitHubCrawlerOutput { val log = LoggerFactory.getLogger(this.javaClass) private val finalOutputFileName: String init { val now = LocalDateTime.now() val formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss") finalOutputFileName = "CIdroidReadyContent_" + now.format(formatter) + ".json" val writer = openFileWithOptions(StandardOpenOption.CREATE_NEW,StandardOpenOption.WRITE) //initiating the Json array writer.write("[\n"); writer.close() } @Throws(IOException::class) override fun output(analyzedRepository: Repository) { openFileWithOptions(StandardOpenOption.WRITE, StandardOpenOption.APPEND).use { val sb=StringBuilder() for((branch,actualIndicators) in analyzedRepository.indicators ){ sb.append("{") sb.append("\"repoFullName\": \"").append(analyzedRepository.fullName).append("\",") //we take the first indicator value, assuming it's a path to a file sb.append("\"filePathOnRepo\": \"").append(actualIndicators.get(indicatorsToOutput[0])).append("\",") appendOtherIndicatorsIfAny(sb, actualIndicators) if(withTags){ sb.append("\"tags\": \"").append(analyzedRepository.tags).append("\",") } sb.append("\"branchName\": \"").append(branch.name).append("\"") sb.append("},") sb.append(System.lineSeparator()) } it.write(sb.toString()) } } private fun appendOtherIndicatorsIfAny(sb: StringBuilder, actualIndicators: Map<String, Any>) { if (indicatorsToOutput.size > 1) { //if there are others, we output them but they probably won't be processed given their name for (i in 1..indicatorsToOutput.size - 1) { sb.append("\"otherIndicator$i\": \"").append(actualIndicators.get(indicatorsToOutput[i])).append("\",") } } } @Throws(IOException::class) override fun finalizeOutput(){ val content = Scanner(File(finalOutputFileName)).useDelimiter("\\Z").next() //removing the last character which is a "," from the json val withoutLastCharacter = content.substring(0, content.length - 1) val writer = openFileWithOptions(StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING) writer.write(withoutLastCharacter) //closing the Json array writer.write("\n]"); writer.close() } @Suppress("SpreadOperator") //no performance impact given the number of values (a couple, max).. private fun openFileWithOptions(vararg options : OpenOption) : BufferedWriter { return Files.newBufferedWriter(Paths.get(finalOutputFileName), StandardCharsets.UTF_8, *options) } }
6
null
9
97
f25da66c6c64f2c167671f49129ff59c6ef74760
4,017
github-crawler
Apache License 2.0
comet-core/src/main/kotlin/ren/natsuyuk1/comet/service/RateLimitService.kt
StarWishsama
173,288,057
false
null
package ren.natsuyuk1.comet.service import io.ktor.http.* import kotlinx.serialization.Serializable import ren.natsuyuk1.comet.api.config.provider.PersistDataFile import ren.natsuyuk1.comet.utils.file.dataDirectory import java.io.File @Serializable enum class RateLimitAPI { GITHUB, GITLAB } object RateLimitData : PersistDataFile<RateLimitData.Data>( File(dataDirectory, "rate_limit.json"), Data.serializer(), Data() ) { @Serializable data class Data( val rateLimitData: MutableMap<RateLimitAPI, Long> = mutableMapOf() ) } object RateLimitService { fun checkRate(apiType: RateLimitAPI, headers: Headers) { when (apiType) { RateLimitAPI.GITHUB -> { val remaining = headers["x-ratelimit-remaining"] ?: return if (remaining.toIntOrNull() != null && remaining.toInt() > 1) { return } else { val nextReset = headers["x-ratelimit-reset"] ?: return if (nextReset.toLongOrNull() == null) { return } RateLimitData.data.rateLimitData[apiType] = nextReset.toLong() } } RateLimitAPI.GITLAB -> { val remaining = headers["ratelimit-remaining"] ?: return if (remaining.toIntOrNull() != null && remaining.toInt() > 1) { return } else { val nextReset = headers["ratelimit-reset"] ?: return if (nextReset.toLongOrNull() == null) { return } RateLimitData.data.rateLimitData[apiType] = nextReset.toLong() } } } } fun isRateLimit(apiType: RateLimitAPI): Boolean { return RateLimitData.data.rateLimitData.containsKey(apiType) && RateLimitData.data.rateLimitData[apiType]!! > System.currentTimeMillis() // ktlint-disable max-line-length } }
19
Kotlin
20
193
19ed20ec4003a37be3bc2dfc6b55a9e2548f0542
2,029
Comet-Bot
MIT License
compiler/testData/codegen/box/ranges/forIntRange.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND_FIR: JVM_IR // KJS_WITH_FULL_RUNTIME // WITH_RUNTIME fun box() : String { val a = arrayOfNulls<String>(3) a[0] = "a" a[1] = "b" a[2] = "c" var result = 0 for(i in a.indices) { result += i } if (result != 3) return "FAIL" return "OK" }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
297
kotlin
Apache License 2.0
src/main/kotlin/com/terraformation/backend/documentproducer/model/EditHistoryModel.kt
terraware
323,722,525
false
{"Kotlin": 5843459, "HTML": 133192, "Python": 46250, "FreeMarker": 21464, "PLpgSQL": 20103, "Makefile": 746, "Dockerfile": 667, "JavaScript": 380}
package com.terraformation.backend.documentproducer.model import com.terraformation.backend.db.default_schema.UserId import java.time.Instant data class EditHistoryModel( val createdBy: UserId, val createdTime: Instant, )
13
Kotlin
1
10
ca95570ed954e9032b6c083b1bf0805c5845e25a
232
terraware-server
Apache License 2.0
src/main/java/io/github/ackeecz/danger/commitlint/checkers/SubjectLengthRuleChecker.kt
AckeeCZ
276,617,694
false
null
package io.github.ackeecz.danger.commitlint.checkers import io.github.ackeecz.danger.commitlint.Commit internal class SubjectLengthRuleChecker : RuleChecker() { override fun check(commits: List<Commit>) { commits.filter { it.message.subject != null } .forEach { commit -> if (commit.message.subject?.length ?: 0 >= SUBJECT_LIMIT_SIZE) { warnings[commit.sha] = "Please limit commit subject line to $SUBJECT_LIMIT_SIZE characters." } } } companion object { const val SUBJECT_LIMIT_SIZE = 50 } }
0
Kotlin
0
3
5b5242058aac330d893769726e853f39bce306ac
604
danger-kotlin-commit-lint
Apache License 2.0
client/src/commonMain/kotlin/com/github/mustafaozhan/ccc/client/viewmodel/calculator/CalculatorSEED.kt
CurrencyConverterCalculator
102,633,334
false
null
package com.github.mustafaozhan.ccc.client.viewmodel.calculator import com.github.mustafaozhan.ccc.client.base.BaseData import com.github.mustafaozhan.ccc.client.base.BaseEffect import com.github.mustafaozhan.ccc.client.base.BaseEvent import com.github.mustafaozhan.ccc.client.base.BaseState import com.github.mustafaozhan.ccc.client.model.Currency import com.github.mustafaozhan.ccc.client.model.RateState import com.github.mustafaozhan.ccc.common.model.Rates import com.github.mustafaozhan.parsermob.ParserMob import kotlinx.coroutines.flow.MutableStateFlow // State data class CalculatorState( val input: String = "", val base: String = "", val currencyList: List<Currency> = listOf(), val output: String = "", val symbol: String = "", val loading: Boolean = true, val rateState: RateState = RateState.None, ) : BaseState() // Event interface CalculatorEvent : BaseEvent { fun onKeyPress(key: String) fun onItemClick(currency: Currency) fun onItemLongClick(currency: Currency): Boolean fun onBarClick() fun onSettingsClicked() fun onBaseChange(base: String) } // Effect sealed class CalculatorEffect : BaseEffect() { object Error : CalculatorEffect() object FewCurrency : CalculatorEffect() object OpenBar : CalculatorEffect() object MaximumInput : CalculatorEffect() object OpenSettings : CalculatorEffect() data class ShowRate(val text: String, val name: String) : CalculatorEffect() } // Data data class CalculatorData( var parser: ParserMob = ParserMob(), var rates: Rates? = null ) : BaseData() { companion object { internal const val MAXIMUM_OUTPUT = 18 internal const val MAXIMUM_INPUT = 44 internal const val CHAR_DOT = '.' internal const val PRECISION = 9 internal const val KEY_DEL = "DEL" internal const val KEY_AC = "AC" } } // Extension @Suppress("LongParameterList") fun MutableStateFlow<CalculatorState>.update( input: String = value.input, base: String = value.base, currencyList: List<Currency> = value.currencyList, output: String = value.output, symbol: String = value.symbol, loading: Boolean = value.loading, rateState: RateState = value.rateState ) { value = value.copy( input = input, base = base, currencyList = currencyList, output = output, symbol = symbol, loading = loading, rateState = rateState ) }
13
null
19
159
f7bf710bbed7a67dfb3c1c24e0de096abbc6888c
2,470
CCC
Apache License 2.0
app/src/main/java/com/mincor/kodiexample/providers/ProviderUtils.kt
Rasalexman
141,794,793
false
null
package com.mincor.kodiexample.providers import android.content.Context import coil.ImageLoader import coil.util.CoilUtils import com.mincor.kodiexample.common.Consts import com.mincor.kodiexample.providers.network.api.IMovieApi import com.mincor.kodiexample.providers.network.createWebServiceApi import com.rasalexman.kodi.annotations.BindProvider import com.rasalexman.kodi.annotations.BindSingle import okhttp3.Cache import okhttp3.OkHttpClient object ProviderUtils { @BindSingle( toClass = Cache::class, toModule = Consts.Modules.ProvidersName ) fun createCache(context: Context) = CoilUtils.createDefaultCache(context) @BindProvider( toClass = IMovieApi::class, toModule = Consts.Modules.ProvidersName ) fun createMovieApi(client: OkHttpClient): IMovieApi = createWebServiceApi(client) @BindSingle( toClass = ImageLoader::class, toModule = Consts.Modules.ProvidersName ) fun createImageLoader(context: Context, client: OkHttpClient) = ImageLoader(context) { availableMemoryPercentage(0.5) bitmapPoolPercentage(0.5) crossfade(true) okHttpClient(client) } }
0
null
3
11
12e2780c29ca3a3642094f82e72078bf39d5d908
1,210
KODI
MIT License
arrangor/src/main/kotlin/no/nav/amt/tiltak/ansatt/ArrangorAnsattRepository.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.ansatt import no.nav.amt.tiltak.common.db_utils.DbUtils.sqlParameters import no.nav.amt.tiltak.common.db_utils.getLocalDateTime import no.nav.amt.tiltak.common.db_utils.getUUID import no.nav.amt.tiltak.core.domain.tilgangskontroll.ArrangorAnsattRolle import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Component import java.time.LocalDateTime import java.util.UUID @Component open class ArrangorAnsattRepository( private val template: NamedParameterJdbcTemplate ) { private val rowMapper = RowMapper { rs, _ -> AnsattDbo( id = rs.getUUID("id"), personligIdent = rs.getString("personlig_ident"), fornavn = rs.getString("fornavn"), mellomnavn = rs.getString("mellomnavn"), etternavn = rs.getString("etternavn"), tilgangerSistSynkronisert = rs.getLocalDateTime("tilganger_sist_synkronisert"), sistVelykkedeInnlogging = rs.getLocalDateTime("sist_velykkede_innlogging"), createdAt = rs.getLocalDateTime("created_at"), modifiedAt = rs.getLocalDateTime("modified_at") ) } fun upsertAnsatt(id: UUID, personligIdent: String, fornavn: String, mellomnavn: String?, etternavn: String) { val sql = """ INSERT INTO arrangor_ansatt(id, personlig_ident, fornavn, mellomnavn, etternavn) VALUES(:id, :personligIdent, :fornavn, :mellomnavn, :etternavn) ON CONFLICT (id) DO UPDATE SET fornavn = :fornavn, mellomnavn = :mellomnavn, etternavn = :etternavn """.trimIndent() val parameters = sqlParameters( "id" to id, "personligIdent" to personligIdent, "fornavn" to fornavn, "mellomnavn" to mellomnavn, "etternavn" to etternavn ) template.update(sql, parameters) } fun get(ansattId: UUID): AnsattDbo? { val parameters = MapSqlParameterSource().addValues( mapOf( "ansattId" to ansattId ) ) return template.query( "SELECT * FROM arrangor_ansatt WHERE id = :ansattId", parameters, rowMapper ).firstOrNull() } fun getByPersonligIdent(personligIdent: String): AnsattDbo? { val parameters = MapSqlParameterSource().addValues( mapOf( "personligIdent" to personligIdent ) ) return template.query( "SELECT * FROM arrangor_ansatt WHERE personlig_ident = :personligIdent", parameters, rowMapper ).firstOrNull() } fun getAnsatte(ansattIder: List<UUID>): List<AnsattDbo> { if (ansattIder.isEmpty()) return emptyList() val sql = "SELECT * FROM arrangor_ansatt WHERE id in (:ansattIder)" val parameters = sqlParameters("ansattIder" to ansattIder) return template.query(sql, parameters, rowMapper) } fun getAnsatteForGjennomforing(gjennomforingId: UUID, rolle: ArrangorAnsattRolle): List<AnsattDbo> { val sql = """ SELECT distinct a.* FROM arrangor_ansatt a INNER JOIN arrangor_ansatt_rolle aar on a.id = aar.ansatt_id INNER JOIN arrangor_ansatt_gjennomforing_tilgang aagt on aar.ansatt_id = aagt.ansatt_id WHERE aagt.gjennomforing_id = :gjennomforingId AND aar.rolle = CAST(:rolle AS arrangor_rolle) AND aagt.gyldig_fra < CURRENT_TIMESTAMP AND aagt.gyldig_til > CURRENT_TIMESTAMP """.trimIndent() return template.query( sql, sqlParameters( "gjennomforingId" to gjennomforingId, "rolle" to rolle.name, ), rowMapper ) } fun getAnsatteMedRolleForArrangor(arrangorId: UUID, rolle: ArrangorAnsattRolle): List<AnsattDbo> { val sql = """ SELECT distinct a.* FROM arrangor_ansatt a INNER JOIN arrangor_ansatt_rolle aar on a.id = aar.ansatt_id WHERE aar.arrangor_id = :arrangorId AND aar.rolle = CAST(:rolle AS arrangor_rolle) AND aar.gyldig_fra < CURRENT_TIMESTAMP AND aar.gyldig_til > CURRENT_TIMESTAMP """.trimIndent() return template.query( sql, sqlParameters( "arrangorId" to arrangorId, "rolle" to rolle.name, ), rowMapper ) } fun setSistOppdatertForAnsatt(ansattId: UUID, tilgangerSistSynkronisert: LocalDateTime) { val sql = """ UPDATE arrangor_ansatt SET tilganger_sist_synkronisert = :tilgangerSistSynkronisert where id = :id """.trimIndent() template.update( sql, sqlParameters( "id" to ansattId, "tilgangerSistSynkronisert" to tilgangerSistSynkronisert ) ) } fun getEldsteSistRolleSynkroniserteAnsatte(antall: Int): List<AnsattDbo> { val sql = """ SELECT * FROM arrangor_ansatt ORDER BY tilganger_sist_synkronisert ASC LIMIT :antall """.trimIndent() return template.query( sql, sqlParameters("antall" to antall), rowMapper ) } fun setVelykketInnlogging(ansattId: UUID) { val sql = """ UPDATE arrangor_ansatt SET sist_velykkede_innlogging = CURRENT_TIMESTAMP WHERE id = :ansattId """.trimIndent() template.update(sql, sqlParameters("ansattId" to ansattId)) } }
3
Kotlin
3
3
871b71af7e7aa7da177f7e7c77b554c7cbdd17f0
4,914
amt-tiltak
MIT License
valuedef-compiler-idea/src/main/kotlin/com/bennyhuo/kotlin/valuedef/idea/ValueDefModelBuilder.kt
bennyhuo
439,819,685
false
null
package com.bennyhuo.kotlin.valuedef.idea import com.bennyhuo.kotlin.valuedef.BuildConfig import org.gradle.api.Project import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import java.io.Serializable import java.lang.Exception /** * Created by benny at 2022/1/13 8:14 AM. */ class ValueDefModelBuilder : AbstractKotlinGradleModelBuilder() { override fun buildAll(modelName: String?, project: Project): Any { val plugin = project.plugins.findPlugin(BuildConfig.KOTLIN_PLUGIN_ID) return ValueDefGradleModelImpl(plugin != null) } override fun canBuild(modelName: String?): Boolean { return modelName == ValueDefGradleModel::class.java.name } override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create(project, e, "Gradle import errors") .withDescription("Unable to build ${BuildConfig.KOTLIN_PLUGIN_ID} plugin configuration") } } interface ValueDefGradleModel : Serializable { val isEnabled: Boolean } class ValueDefGradleModelImpl(override val isEnabled: Boolean) : ValueDefGradleModel
0
Kotlin
0
4
5b5ebfe900e25372d3c076b24dfb175945866a38
1,222
KotlinValueDef
MIT License
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/commands/test/splitting/byTestName/TestsSplittingByNamesSaver.kt
JetBrains
49,584,664
false
{"Kotlin": 2624677, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
package jetbrains.buildServer.dotnet.commands.test.splitting.byTestName interface TestsSplittingByNamesSaver { fun tryToSave(presumablyTestNameLine: String) }
3
Kotlin
25
94
9665e2ac5c4e70b3b50b95275346cce1f95574d5
165
teamcity-dotnet-plugin
Apache License 2.0
plugin/src/main/java/net/bytemc/bytecloud/plugin/plattform/bungeecord/BungeeCordPlatformBootstrap.kt
bytemcnetzwerk
684,494,766
false
{"Kotlin": 163692}
package net.bytemc.bytecloud.plugin.plattform.bungeecord import net.md_5.bungee.api.ProxyServer import net.md_5.bungee.api.plugin.Plugin class BungeeCordPlatformBootstrap : Plugin() { override fun onEnable() { ProxyServer.getInstance().servers.clear() } override fun onDisable() { } }
2
Kotlin
3
5
45151c0f561b822a3baec171a8b1419582d90426
313
bytecloud
Apache License 2.0
core/src/commonTest/kotlin/co/nimblehq/jsonapi/json/JsonApiTest.kt
nimblehq
539,351,996
false
{"Kotlin": 29329}
package co.nimblehq.jsonapi import co.nimblehq.jsonapi.helpers.mock.NetworkIncludedMockModel import co.nimblehq.jsonapi.helpers.mock.NetworkMetaMockModel import co.nimblehq.jsonapi.helpers.mock.NetworkMockModel import co.nimblehq.jsonapi.helpers.mock.NetworkOnlyMetaMockModel import co.nimblehq.jsonapi.json.JsonApi import co.nimblehq.jsonapi.model.JsonApiException import kotlinx.serialization.json.Json import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.fail class JsonApiTest { private val json = Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true } var jsonApi = JsonApi(json) @Test fun `when calling decodeFromJsonApiString with single object it returns correct object`() { val decoded = jsonApi.decodeFromJsonApiString<NetworkMockModel>( NetworkMockModel.response ) assertEquals(decoded.title, "JSON:API paints my bikeshed!") assertEquals(decoded.body, "The shortest article. Ever.") assertEquals(decoded.created, "2015-05-22T14:56:29.000Z") assertEquals(decoded.itemVersion, 2) } @Test fun `when calling decodeFromJsonApiString with array object it returns correct object`() { val decoded = jsonApi.decodeFromJsonApiString<List<NetworkMockModel>>( NetworkMockModel.arrayResponse ) assertEquals(decoded.size, 1) assertEquals(decoded.first().title, "JSON:API paints my bikeshed!") assertEquals(decoded.first().body, "The shortest article. Ever.") assertEquals(decoded.first().created, "2015-05-22T14:56:29.000Z") assertEquals(decoded.first().itemVersion, 2) } @Test fun `when calling decodeFromJsonApiString with single object with included it returns correct object`() { val decoded = jsonApi.decodeFromJsonApiString<NetworkIncludedMockModel>( NetworkIncludedMockModel.response ) assertEquals(decoded.title, "JSON:API paints my bikeshed!") assertEquals(decoded.body, "The shortest article. Ever.") assertEquals(decoded.created, "2015-05-22T14:56:29.000Z") assertEquals(decoded.author.name, "John") } @Test fun `when calling decodeFromJsonApiString with array object with included it returns correct object`() { val decoded = jsonApi.decodeFromJsonApiString<List<NetworkIncludedMockModel>>( NetworkIncludedMockModel.arrayResponse ) assertEquals(decoded.size, 1) assertEquals(decoded.first().title, "JSON:API paints my bikeshed!") assertEquals(decoded.first().body, "The shortest article. Ever.") assertEquals(decoded.first().created, "2015-05-22T14:56:29.000Z") assertEquals(decoded.first().author.name, "John") } @Test fun `when calling decodeFromJsonApiString with single object with only meta it returns correct object`() { val decoded = jsonApi.decodeFromJsonApiString<NetworkOnlyMetaMockModel>( NetworkOnlyMetaMockModel.responseWithMetaOnly ) assertEquals(decoded.message, "Success") } @Test fun `when calling decodeWithMetaFromJsonApiString with array object it returns correct object`() { val decoded = jsonApi.decodeWithMetaFromJsonApiString<List<NetworkMockModel>, NetworkMetaMockModel>( NetworkMetaMockModel.responseWithMeta ) assertEquals(decoded.first.size, 1) assertEquals(decoded.first.first().title, "JSON:API paints my bikeshed!") assertEquals(decoded.first.first().body, "The shortest article. Ever.") assertEquals(decoded.first.first().created, "2015-05-22T14:56:29.000Z") assertEquals(decoded.first.first().itemVersion, 2) assertEquals(decoded.second.page, 2) assertEquals(decoded.second.totalPages, 13) } @Test fun `when calling decodeFromJsonApiString with error response it returns correct error`() { try { val decoded = jsonApi.decodeFromJsonApiString<NetworkMockModel>( NetworkMockModel.errorResponse ) fail("Should not parse error") } catch (e: JsonApiException) { assertEquals(e.errors.first().detail, "Missing `data` Member at document's top level.") } } }
0
Kotlin
2
3
bdbf40200827b626867db8e15924486036cf00aa
4,324
jsonapi-kotlin
MIT License
app/src/main/java/com/sedsoftware/yaptalker/presentation/features/imagedisplay/di/ImageDisplayActivityModule.kt
EitlerPereira
115,528,632
true
{"Kotlin": 350092, "Shell": 1229, "IDL": 510, "Prolog": 237, "CSS": 50}
package com.sedsoftware.yaptalker.presentation.features.imagedisplay.di import dagger.Module @Module class ImageDisplayActivityModule
0
Kotlin
0
0
e90fd7f7ed3024e1a58f9f8e0e1ba01cd986bcd1
136
YapTalker
Apache License 2.0
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/ToArrayLowering.kt
evant
277,371,822
true
{"Kotlin": 44780046, "Java": 7640484, "JavaScript": 195805, "HTML": 76860, "Lex": 23805, "TypeScript": 21613, "Groovy": 11198, "CSS": 9144, "Shell": 7220, "Batchfile": 5362, "Swift": 2272, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
/* * Copyright 2010-2018 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.backend.jvm.lower import org.jetbrains.kotlin.backend.common.ClassLoweringPass import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.phaser.makeIrFilePhase import org.jetbrains.kotlin.backend.jvm.JvmBackendContext import org.jetbrains.kotlin.backend.jvm.JvmLoweredDeclarationOrigin import org.jetbrains.kotlin.backend.jvm.codegen.isJvmInterface import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.irBlockBody import org.jetbrains.kotlin.ir.builders.irCall import org.jetbrains.kotlin.ir.builders.irReturn import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl import org.jetbrains.kotlin.ir.declarations.impl.IrTypeParameterImpl import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl import org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor import org.jetbrains.kotlin.ir.descriptors.WrappedTypeParameterDescriptor import org.jetbrains.kotlin.ir.descriptors.WrappedValueParameterDescriptor import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrTypeParameterSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.isClass import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.utils.DFS internal val toArrayPhase = makeIrFilePhase( ::ToArrayLowering, name = "ToArray", description = "Handle toArray functions" ) private class ToArrayLowering(private val context: JvmBackendContext) : ClassLoweringPass { override fun lower(irClass: IrClass) { if (irClass.isJvmInterface || !irClass.isCollectionSubClass()) return val irBuiltIns = context.irBuiltIns val symbols = context.ir.symbols val toArrayName = Name.identifier("toArray") val genericToArray = irClass.declarations.filterIsInstance<IrSimpleFunction>().find { it.isGenericToArray(context) } val nonGenericToArray = irClass.declarations.filterIsInstance<IrSimpleFunction>().find { it.isNonGenericToArray() } val isDirectCollectionSubClass = irClass.isDirectCollectionSubClass() if (genericToArray == null) { if (isDirectCollectionSubClass) { val typeParameterDescriptor = WrappedTypeParameterDescriptor() val typeParameter = IrTypeParameterImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrTypeParameterSymbolImpl(typeParameterDescriptor), Name.identifier("T"), index = 0, variance = Variance.INVARIANT, isReified = false ).apply { typeParameterDescriptor.bind(this) superTypes.add(irBuiltIns.anyNType) } val substitutedArrayType = irBuiltIns.arrayClass.typeWith(typeParameter.defaultType) val functionDescriptor = WrappedSimpleFunctionDescriptor() val irFunction = IrFunctionImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrSimpleFunctionSymbolImpl(functionDescriptor), toArrayName, Visibilities.PUBLIC, Modality.OPEN, returnType = substitutedArrayType, isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false ) functionDescriptor.bind(irFunction) irFunction.parent = irClass typeParameter.parent = irFunction irFunction.typeParameters += typeParameter val dispatchReceiverParameterDescriptor = WrappedValueParameterDescriptor() irFunction.dispatchReceiverParameter = IrValueParameterImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrValueParameterSymbolImpl(dispatchReceiverParameterDescriptor), Name.special("<this>"), index = -1, type = irClass.defaultType, varargElementType = null, isCrossinline = false, isNoinline = false ).apply { parent = irFunction } val valueParameterDescriptor = WrappedValueParameterDescriptor() irFunction.valueParameters += IrValueParameterImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrValueParameterSymbolImpl(valueParameterDescriptor), Name.identifier("array"), index = 0, varargElementType = null, type = substitutedArrayType, isCrossinline = false, isNoinline = false ).apply { valueParameterDescriptor.bind(this) parent = irFunction } irFunction.body = context.createIrBuilder(irFunction.symbol).irBlockBody { +irReturn( irCall(symbols.genericToArray, symbols.genericToArray.owner.returnType).apply { putValueArgument( 0, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irFunction.dispatchReceiverParameter!!.symbol) ) putValueArgument(1, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irFunction.valueParameters[0].symbol)) }) } irClass.declarations.add(irFunction) } } else { (genericToArray as IrFunctionImpl).visibility = Visibilities.PUBLIC } if (nonGenericToArray == null) { if (isDirectCollectionSubClass) { val functionDescriptor = WrappedSimpleFunctionDescriptor() val irFunction = IrFunctionImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrSimpleFunctionSymbolImpl(functionDescriptor), toArrayName, Visibilities.PUBLIC, Modality.OPEN, returnType = irBuiltIns.arrayClass.typeWith(irBuiltIns.anyNType), isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false ) functionDescriptor.bind(irFunction) irFunction.parent = irClass val dispatchReceiverParameterDescriptor = WrappedValueParameterDescriptor() irFunction.dispatchReceiverParameter = IrValueParameterImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.TO_ARRAY, IrValueParameterSymbolImpl(dispatchReceiverParameterDescriptor), Name.special("<this>"), index = -1, type = irClass.defaultType, varargElementType = null, isCrossinline = false, isNoinline = false ).apply { parent = irFunction } irFunction.body = context.createIrBuilder(irFunction.symbol).irBlockBody { +irReturn( irCall(symbols.nonGenericToArray, symbols.nonGenericToArray.owner.returnType).apply { putValueArgument( 0, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irFunction.dispatchReceiverParameter!!.symbol) ) }) } irClass.declarations.add(irFunction) } } else { (nonGenericToArray as IrFunctionImpl).visibility = Visibilities.PUBLIC } } } private val IrClass.superClasses get() = superTypes.mapNotNull { it.getClass() } // Have to check by name, since irBuiltins is unreliable. internal fun IrClass.isCollectionSubClass() = DFS.ifAny(listOf(this), IrClass::superClasses) { it.defaultType.isCollection() } // If this class inherits from another Kotlin class that implements Collection, it already has toArray. private fun IrClass.isDirectCollectionSubClass() = isCollectionSubClass() && !superClasses.any { it.isClass && it.origin != IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB && it.isCollectionSubClass() } internal fun IrSimpleFunction.isGenericToArray(context: JvmBackendContext): Boolean { if (name.asString() != "toArray") return false if (typeParameters.size != 1 || valueParameters.size != 1 || extensionReceiverParameter != null) return false val paramType = valueParameters[0].type if (!returnType.isArray() || !paramType.isArray()) return false val elementType = typeParameters[0].defaultType val expectedType = context.ir.symbols.array.typeWith(elementType) return expectedType == paramType && expectedType == returnType } internal fun IrSimpleFunction.isNonGenericToArray(): Boolean { if (name.asString() != "toArray") return false if (typeParameters.isNotEmpty() || valueParameters.isNotEmpty() || extensionReceiverParameter != null) return false return returnType.isArray() }
0
null
0
1
fb1d4e01ed9b6f45d9886fcc697197591cf8b67c
10,978
kotlin
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/object/UpdateDetail.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.domain.`object` import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.Payload import com.anytypeio.anytype.domain.base.BaseUseCase import com.anytypeio.anytype.domain.block.repo.BlockRepository // TODO rename to SetObjectDetails class UpdateDetail(private val repo: BlockRepository): BaseUseCase<Payload, UpdateDetail.Params>() { override suspend fun run(params: Params) = safe { repo.setObjectDetail( ctx = params.target, key = params.key, value = params.value ) } data class Params( val target: Id, val key: String, val value: Any? ) }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
694
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/masrofy/screens/onboarding/OnboardingViewModel.kt
salmanA169
589,714,976
false
null
package com.masrofy.screens.onboarding import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.masrofy.ONBOARDING_IS_FIRST_TIME import com.masrofy.ONBOARDING_SCREENS_ARGS import com.masrofy.coroutine.DispatcherProvider import com.masrofy.currency.COUNTRY_DATA import com.masrofy.currency.CURRENCY_DATA import com.masrofy.currency.Currency import com.masrofy.data.database.MasrofyDatabase import com.masrofy.emoji.EmojiData import com.masrofy.onboarding.OnBoardingManager import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import java.util.Locale import javax.inject.Inject @HiltViewModel class OnboardingViewModel @Inject constructor( private val db: MasrofyDatabase, savedStateHandle: SavedStateHandle, private val dataStore: DataStore<Preferences>, private val dispatcherProvider: DispatcherProvider ) : ViewModel() { private val _onboardingState = MutableStateFlow(OnboardingState()) val onboardingState = _onboardingState.asStateFlow() private val isFirstTime = savedStateHandle.get<Boolean>(ONBOARDING_IS_FIRST_TIME)!! private val screensOnboarding = savedStateHandle.get<Array<String>>(ONBOARDING_SCREENS_ARGS)!! private val onboardingManager = OnBoardingManager(db,dataStore) private val _effect = MutableStateFlow<OnboardingEffect?>(null) val effect = _effect.asStateFlow() init { _onboardingState.update { it.copy( currencyItems = initialCurrencyItems(), currentCountryCode = Locale.getDefault().country ) } } fun onEvent(event: OnboardingEvent) { when (event) { OnboardingEvent.Back -> back() is OnboardingEvent.CurrencyData -> { onboardingManager.setCurrentCurrencyOnboardingData( event.currency.currencyCode ) _onboardingState.update { it.copy( selectedCurrency = event.currency ) } updateValue() } OnboardingEvent.Next -> next() OnboardingEvent.Finish -> { viewModelScope.launch(dispatcherProvider.io) { onboardingManager.finish() _effect.update { OnboardingEffect.Close } } } } } fun resetEffect(){ _effect.update { null } } private fun next() { onboardingManager.next() updateValue() } private fun back() { onboardingManager.back() updateValue() } init { onboardingManager.setData(isFirstTime, screensOnboarding.toList()) updateValue() } private fun updateValue() { _onboardingState.update { it.copy( onboardingManager.screens, onboardingManager.isFirstScreen(), onboardingManager.canMove(), onboardingManager.isLastScreen(), onboardingManager.currentIndex, if (onboardingManager.isLastScreen()) "Finish" else "Next" ) } } private fun initialCurrencyItems(): List<CurrencyItem> { return CURRENCY_DATA.flatMap { (key, value) -> value.countryCodes.map { val countryName = COUNTRY_DATA[it]?.name.orEmpty() val flagKey = countryName.lowercase().replace(" ", "_") val flag = EmojiData.DATA[flagKey] ?: "🏳️" CurrencyItem( currencySymbol = value.symbol, flag = flag, countryName = countryName, countryCode = it, Currency( key,it ) ) } }.sortedBy { it.countryName } } } sealed class OnboardingEvent { object Next : OnboardingEvent() object Back : OnboardingEvent() class CurrencyData(val currency: Currency) : OnboardingEvent() object Finish:OnboardingEvent() } sealed class OnboardingEffect{ object Close :OnboardingEffect() }
2
Kotlin
1
9
fb671fc1e2c628fb467bca9d3109799b3e1d43f2
4,564
masrofy
Apache License 2.0
src/Day07.kt
shoresea
576,381,520
false
{"Kotlin": 29960}
import java.util.* fun main() { fun getDirectories(root: Directory): List<Directory> { val directories = ArrayList<Directory>() val queue = Stack<Directory>() queue.add(root) while (queue.isNotEmpty()) { val current = queue.pop() directories.add(current) current.children.filterIsInstance<Directory>().let { queue.addAll(it) } } return directories } fun generateFilesystem(inputs: List<String>): Directory { val root = Directory("/", ArrayList(), null) var current: FileSystemNode = root for (input in inputs) { if (input.startsWith("$ cd ")) { current = current as Directory val dirName = input.substringAfter("$ cd ").trim() current = when (dirName) { "/" -> { root } ".." -> { current.parent!! } else -> { current.children.firstOrNull { it.name == dirName } ?: Directory(dirName, ArrayList(), current) .also { (current as Directory).children.add(it) } } } } else if (input.startsWith("$ ls")) { continue } else { if (input.startsWith("dir")) { Directory(input.substringAfter("dir ").trim(), ArrayList(), current) .also { (current as Directory).children.add(it) } } else { val props = input.split(" ").map { it.trim() } File(props[1], props[0].toInt()) .also { (current as Directory).children.add(it) } } } } return root } fun part1(inputs: List<String>): Int { val root = generateFilesystem(inputs) return getDirectories(root).map { it.size() }.filter { it <= 100000 }.sum() } fun part2(inputs: List<String>): Int { val root = generateFilesystem(inputs) val availableStorage = 70000000 - root.size() val requiredFreeStorage = 30000000 - availableStorage return getDirectories(root).map{ it.size() }.filter { it >= requiredFreeStorage }.min() } val input = readInput("Day07") part1(input).println() part2(input).println() } abstract class FileSystemNode(open val name: String) { abstract fun size(): Int } data class File(override val name: String, private val size: Int) : FileSystemNode(name) { override fun size(): Int = size } data class Directory(override val name: String, val children: ArrayList<FileSystemNode>, val parent: FileSystemNode?) : FileSystemNode(name) { override fun size(): Int = children.sumOf { it.size() } }
0
Kotlin
0
0
e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e
2,909
AOC2022InKotlin
Apache License 2.0
app/src/main/java/com/silverpine/uu/sample/bluetooth/viewmodel/BaseViewModel.kt
SilverPineSoftware
594,244,294
false
{"Kotlin": 322495, "Shell": 10612}
package com.silverpine.uu.sample.bluetooth.viewmodel import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.silverpine.uu.core.uuDispatchMain import com.silverpine.uu.ux.UUAlertDialog import com.silverpine.uu.ux.UUMenuItem import com.silverpine.uu.ux.UUToast open class BaseViewModel: ViewModel() { private var _menuItems: MutableLiveData<ArrayList<UUMenuItem>> = MutableLiveData() val menuItems: LiveData<ArrayList<UUMenuItem>> = _menuItems var gotoActivity: (Class<out AppCompatActivity>, Bundle?)->Unit = { _, _ -> } var showAlertDialog: (UUAlertDialog)->Unit = { } var onToast: (UUToast)->Unit = { } protected fun updateMenu() { val list = buildMenu() uuDispatchMain() { _menuItems.value = list } } open fun buildMenu(): ArrayList<UUMenuItem> { return arrayListOf() } }
0
Kotlin
0
0
64fdc8440c0eae9a66b5355ef6462d6cbf2eb705
1,017
UUKotlinBluetooth
MIT License
mvvm-dagger/src/main/java/com/nphau/android/shared/common/ParameterizedSingleton.kt
ThanhHuong98
432,947,065
false
{"Kotlin": 165721, "Java": 1330, "Shell": 87}
/* * Created by nphau on 31/10/2021, 21:47 * Copyright (c) 2021 . All rights reserved. * Last modified 31/10/2021, 21:37 */ package com.nphau.android.shared.common open class ParameterizedSingleton<out T, in A>(creator: (A) -> T) { private var creator: ((A) -> T)? = creator @Volatile private var instance: T? = null fun getInstance(argument: A): T { val checkInstance = instance if (checkInstance != null) return checkInstance return synchronized(this) { val synchronizedCheck = instance if (synchronizedCheck != null) return synchronizedCheck else { val createdInstance = creator!!(argument) instance = createdInstance creator = null createdInstance } } } }
0
null
0
1
ac0402ae4734285ef5e647d1f53a1f9f4a8d98cd
834
android.clean-architecture.mvvm
Apache License 2.0
build-logic/src/main/kotlin/JvmJUnit4Plugin.kt
duckie-team
557,999,746
false
{"Kotlin": 115491}
/* * Designed and developed by 2022 <NAME>. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/ApiLibrary/blob/trunk/LICENSE */ import land.sungbin.apilibrary.convention.androidTestImplementations import land.sungbin.apilibrary.convention.libs import land.sungbin.apilibrary.convention.setupJunit import land.sungbin.apilibrary.convention.testImplementations import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies /** * Android 프레임워크에 의존적이지 않은 순수한 Junit4 테스트 환경을 구성합니다. */ internal class JvmJUnit4Plugin : Plugin<Project> { override fun apply(project: Project) { with(project) { dependencies { testImplementations( libs.findLibrary("test-strikt").get(), libs.findLibrary("test-coroutines").get(), ) androidTestImplementations( libs.findLibrary("test-strikt").get(), libs.findLibrary("test-coroutines").get(), ) setupJunit( core = libs.findLibrary("test-junit-core").get(), engine = libs.findLibrary("test-junit-engine").get(), ) } } } }
11
Kotlin
0
4
157f41d6dc98b00c71ee1c2390567a38f495d94f
1,291
ApiLibrary
MIT License
idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceModifierFix.kt
JetBrains
278,369,660
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class ReplaceModifierFix( element: KtModifierListOwner, private val replacement: KtModifierKeywordToken ) : KotlinQuickFixAction<KtModifierListOwner>(element), CleanupFix { @Nls private val text = KotlinBundle.message("replace.with.0", replacement.value) override fun getText() = text override fun getFamilyName() = KotlinBundle.message("replace.modifier") override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.addModifier(replacement) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val deprecatedModifier = Errors.DEPRECATED_MODIFIER.cast(diagnostic) val modifier = deprecatedModifier.a val replacement = deprecatedModifier.b val modifierListOwner = deprecatedModifier.psiElement.getParentOfType<KtModifierListOwner>(strict = true) ?: return null return when (modifier) { KtTokens.HEADER_KEYWORD, KtTokens.IMPL_KEYWORD -> ReplaceModifierFix(modifierListOwner, replacement) else -> null } } } }
191
Kotlin
4372
82
cc81d7505bc3e9ad503d706998ae8026c067e838
2,136
intellij-kotlin
Apache License 2.0
kotlin-utility-spring-boot/src/main/kotlin/com/windea/utility/springboot/security/jwt/JwtProperties.kt
DragonKnightOfBreeze
189,628,889
false
null
package com.windea.utility.springboot.security.jwt import org.springframework.boot.context.properties.* /**Jwt的属性类。*/ @ConfigurationProperties("com.windea.security.jwt") class JwtProperties { /**jwt口令的请求头。*/ var tokenHeader: String = "Authorization" /**jwt口令的开头。*/ var tokenHead: String = "Bearer " /**jwt密钥。*/ lateinit var secret: String /**jwt过期时间。*/ var expiration: Int = 86400 }
0
Kotlin
0
0
93b18f66beb64eb46cdd4c55b08c27c58a84c9cb
399
Kotlin-Utility
MIT License
android/src/test/java/com/jdamcd/runlog/android/util/ModelFixture.kt
jdamcd
308,253,514
false
null
package com.jdamcd.runlog.android.util import com.jdamcd.runlog.shared.ActivityCard val activityCard = ActivityCard( id = 123, name = "cool run", type = "run", label = null, distance = "10.3k", time = "40:00" )
0
Kotlin
0
20
a620723359db57bb59981f6ba5f648ea56dfe490
237
runlog-kmm
MIT License
composeApp/src/commonMain/kotlin/ui/pages/cali/InfoPage.kt
edsonDeCavalho
812,314,880
false
{"Kotlin": 57707, "Swift": 721, "HTML": 305}
package ui.pages.cali import MainViewModel import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun InfoPage(paddingModifier: Modifier,mainViewModel : MainViewModel) { LaunchedEffect(Unit) { mainViewModel.updateTitle("Informations") } // mainViewModel.updateTitle("Home") Box( modifier = paddingModifier.fillMaxSize(), contentAlignment = Alignment.CenterStart, ) { // Text(text="InfoPage", fontSize = 70.sp , modifier = Modifier.align(Alignment.Center)) Scaffold { MaterialTheme { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp) ) { item { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier.fillMaxWidth() ) { Text( text = "Navigation", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = "Elevated in a way that it's imcompresible for the human eye giving a force undestructable.", modifier = Modifier .padding(10.dp), textAlign = TextAlign.Center, ) } Spacer(modifier = Modifier.height(10.dp)) } item { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier.fillMaxWidth() ) { Text( text = "Navigation", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = "Elevated in a way that it's imcompresible for the human eye giving a force undestructable.", modifier = Modifier .padding(10.dp), textAlign = TextAlign.Center, ) } } item { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier.fillMaxWidth() ) { Text( text = "Navigation", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = "Elevated in a way that it's imcompresible for the human eye giving a force undestructable.", modifier = Modifier .padding(10.dp), textAlign = TextAlign.Center, ) } } item { ElevatedCard( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier.fillMaxWidth() ) { Text( text = "Navigation", modifier = Modifier .padding(16.dp), textAlign = TextAlign.Center, ) Text( text = "Elevated in a way that it's imcompresible for the human eye giving a force undestructable.", modifier = Modifier .padding(10.dp), textAlign = TextAlign.Center, ) } } } } } } }
0
Kotlin
0
1
d2d9d329068c2f326e23519f6327fefa3777d795
5,320
Demo_KMP_Room_database
MIT License
src/main/kotlin/no/nav/familie/ks/sak/config/featureToggle/FeatureToggleConfig.kt
navikt
533,308,075
false
{"Kotlin": 3819299, "Gherkin": 192343, "Shell": 1839, "Dockerfile": 467}
package no.nav.familie.ks.sak.config.featureToggle class FeatureToggleConfig { companion object { // Operasjonelle const val TEKNISK_VEDLIKEHOLD_HENLEGGELSE = "familie-ks-sak.teknisk-vedlikehold-henleggelse.tilgangsstyring" const val TEKNISK_ENDRING = "familie-ks-sak.behandling.teknisk-endring" const val KAN_MANUELT_KORRIGERE_MED_VEDTAKSBREV = "familie-ks-sak.behandling.korreksjon-vedtaksbrev" const val KAN_OPPRETTE_OG_ENDRE_SAMMENSATTE_KONTROLLSAKER = "familie-ks-sak.kan-opprette-og-endre-sammensatte-kontrollsaker" const val KAN_KJORE_LOVENDRING_FLERE_GANGER = "familie-ks-sak.kan-kjore-lovendring-flere-ganger" const val OVERGANGSORDNING = "familie-ks-sak.overgangsordning" // Ikke operasjonelle const val OPPRETT_SAK_PÅ_RIKTIG_ENHET_OG_SAKSBEHANDLER = "familie-ba-ks-sak.opprett-sak-paa-riktig-enhet-og-saksbehandler" const val BRUK_NY_LØYPE_FOR_GENERERING_AV_ANDELER = "familie-ks-sak.bruk-ny-loype-for-generering-av-andeler" } }
8
Kotlin
1
2
c39fb12189c468a433ca2920b1aa0f5509b23d54
1,031
familie-ks-sak
MIT License