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
app/src/main/java/me/impa/knockonports/viewmodel/MainViewModel.kt
waldoswify93
304,538,268
true
{"Kotlin": 201069, "C++": 4698, "CMake": 1691, "C": 451}
/* * Copyright (c) 2018 <NAME> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 me.impa.knockonports.viewmodel import android.app.Application import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Intent import androidx.lifecycle.* import androidx.paging.PagedList import androidx.paging.toLiveData import kotlinx.coroutines.* import me.impa.knockonports.R import me.impa.knockonports.data.* import me.impa.knockonports.database.KnocksRepository import me.impa.knockonports.database.entity.LogEntry import me.impa.knockonports.database.entity.Sequence import me.impa.knockonports.ext.default import me.impa.knockonports.ext.startSequence import me.impa.knockonports.json.SequenceData import me.impa.knockonports.json.SequenceStep import me.impa.knockonports.util.Logging import me.impa.knockonports.util.info import me.impa.knockonports.util.toast import me.impa.knockonports.util.warn import me.impa.knockonports.widget.KnocksWidget import java.io.File class MainViewModel(application: Application): AndroidViewModel(application), Logging { private val repository by lazy { KnocksRepository(application) } private lateinit var sequenceList: LiveData<List<Sequence>> private lateinit var log: LiveData<PagedList<LogEntry>> private val selectedSequence = MutableLiveData<Sequence?>() private val settingsTabIndex = MutableLiveData<Int>() private val fabVisible = MutableLiveData<Boolean>().default(true) private val logVisible = MutableLiveData<Boolean>().default(false) private val pendingOrderChanges: MutableLiveData<List<Long>> = MutableLiveData() private val installedApps = MutableLiveData<List<AppData>?>().default(null) private val dirtySequence = Transformations.map(selectedSequence) { runBlocking { savePendingData() } it?.copy() } private val dirtySteps = Transformations.map(selectedSequence) { it?.steps?.onEach { e -> e.icmpSizeOffset = it.icmpType?.offset ?: 0 }?.toMutableList() ?: mutableListOf() } fun getSequenceList(): LiveData<List<Sequence>> { runBlocking { savePendingData() } if (!::sequenceList.isInitialized) { runBlocking { sequenceList = repository.getSequences() } } return sequenceList } fun getLog(): LiveData<PagedList<LogEntry>> { if (!::log.isInitialized) { runBlocking { //repository.getLogEntries().toLiveData log = repository.getLogEntries().toLiveData(pageSize = 50) } } return log } fun getSelectedSequence(): LiveData<Sequence?> = selectedSequence fun setSelectedSequence(sequence: Sequence?) { selectedSequence.value = sequence } fun getDirtySteps(): LiveData<MutableList<SequenceStep>> = dirtySteps fun getDirtySequence(): LiveData<Sequence?> = dirtySequence fun getSettingsTabIndex(): LiveData<Int> = settingsTabIndex fun setSettingsTabIndex(index: Int) { settingsTabIndex.value = index } fun getFabVisible(): LiveData<Boolean> = fabVisible fun setFabVisible(isVisible: Boolean) { fabVisible.value = isVisible } fun getLogVisible(): LiveData<Boolean> = logVisible fun setLogVisible(isVisible: Boolean) { logVisible.value = isVisible } fun getInstalledApps(): LiveData<List<AppData>?> = installedApps fun setInstalledApps(appList: List<AppData>?) { installedApps.value = appList } fun setPendingDataChanges(changes: List<Long>) { pendingOrderChanges.value = changes } fun findSequence(id: Long): Sequence? = runBlocking { repository.findSequence(id) } override fun onCleared() { super.onCleared() runBlocking { savePendingData() } } fun deleteSequence(sequence: Sequence) { sequence.id ?: return runBlocking { savePendingData() repository.deleteSequence(sequence) addToLog(EventType.SEQUENCE_DELETED, data = listOf(sequence.name)) viewModelScope.launch { updateWidgets() if (sequence.id == selectedSequence.value?.id) { selectedSequence.value = null } } } } fun addToLog(event: EventType, date: Long = System.currentTimeMillis(), data: List<String?>? = null) { runBlocking { repository.saveLogEntry(LogEntry(null, date, event, data)) } } fun createEmptySequence() { setSelectedSequence(Sequence(null, null, null, null, 500, null, null, IcmpType.WITHOUT_HEADERS, listOf(SequenceStep(SequenceStepType.UDP, null, null, null, null, ContentEncoding.RAW).apply { icmpSizeOffset = IcmpType.WITHOUT_HEADERS.offset }), DescriptionType.DEFAULT, null)) } fun saveDirtyData() { val seq = dirtySequence.value seq ?: return if (seq.id == null) { seq.order = pendingOrderChanges.value?.size ?: sequenceList.value?.size ?: 0 } seq.steps = dirtySteps.value runBlocking { repository.saveSequence(seq) addToLog(EventType.SEQUENCE_SAVED, data = listOf(seq.name)) viewModelScope.launch { updateWidgets() } } } fun knock(sequence: Sequence) { val seqId = sequence.id ?: return val application = getApplication<Application>() application.startSequence(seqId) } private fun savePendingData() { val data = pendingOrderChanges.value data ?: return val changes = mutableListOf<Sequence>() data.forEachIndexed { index, l -> val seq = sequenceList.value?.firstOrNull { it.id == l } if (seq != null && seq.order != index) { seq.order = index changes.add(seq) } } if (changes.size > 0) { runBlocking { repository.updateSequences(changes) } } } fun exportData(fileName: String) { val application = getApplication<Application>() CoroutineScope(Dispatchers.IO).launch { try { info { "Exporting data to $fileName" } val data = sequenceList.value?.asSequence()?.map { SequenceData.fromEntity(it) }?.toList() ?: return@launch File(fileName).writeText(SequenceData.toJson(data)) addToLog(EventType.EXPORT, data = listOf(fileName, data.size.toString())) viewModelScope.launch { application.toast(application.resources.getString(R.string.export_success, fileName)) } info { "Export complete" } } catch (e: Exception) { warn("Unable to export data", e) addToLog(EventType.ERROR_EXPORT, data = listOf(fileName, e.message)) viewModelScope.launch { application.toast(R.string.error_export) } } } } fun importData(fileName: String) { val application = getApplication<Application>() val order = sequenceList.value?.size ?: 0 CoroutineScope(Dispatchers.IO).launch { try { val raw = File(fileName).readText() val data = SequenceData.fromJson(raw) data.forEachIndexed { index, sequenceData -> val seq = sequenceData.toEntity() seq.order = order + index repository.saveSequence(seq) } addToLog(EventType.IMPORT, data = listOf(fileName, data.size.toString())) viewModelScope.launch { application.toast(application.resources.getQuantityString(R.plurals.import_success, data.size, data.size, fileName)) } } catch (e: Exception) { warn("Unable to import data", e) addToLog(EventType.ERROR_IMPORT, data = listOf(fileName, e.message)) viewModelScope.launch { application.toast(R.string.error_import) } } } } private fun updateWidgets() { val application = getApplication<Application>() val intent = Intent(application, KnocksWidget::class.java) intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE val widgetManager = AppWidgetManager.getInstance(application) val ids = widgetManager.getAppWidgetIds(ComponentName(application, KnocksWidget::class.java)) widgetManager.notifyAppWidgetViewDataChanged(ids, android.R.id.list) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids) application.sendBroadcast(intent) } }
0
null
0
0
c49c13adb8e37efa818f70f11a139580656ad503
9,732
knockonports
Apache License 2.0
app/src/main/java/com/quoinsight/tv/PlaybackVideoFragment.kt
QuoInsight
852,073,699
false
{"Kotlin": 47521, "Java": 36912, "Shell": 1386}
package com.quoinsight.tv import android.net.Uri import android.os.Bundle import androidx.leanback.app.VideoSupportFragment import androidx.leanback.app.VideoSupportFragmentGlueHost import androidx.leanback.media.MediaPlayerAdapter import androidx.leanback.media.PlaybackTransportControlGlue import androidx.leanback.widget.PlaybackControlsRow /** Handles video playback with media controls. */ class PlaybackVideoFragment : VideoSupportFragment() { private lateinit var mTransportControlGlue: androidx.leanback.media.PlaybackTransportControlGlue<MediaPlayerAdapter> private lateinit var glueHost : androidx.leanback.app.VideoSupportFragmentGlueHost private lateinit var playerAdapter :androidx.leanback.media.MediaPlayerAdapter override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) val (_, title, description, _, _, videoUrl) = activity?.intent?.getSerializableExtra(DetailsActivity.MOVIE) as Movie //val glueHost = androidx.leanback.app.VideoSupportFragmentGlueHost(this@PlaybackVideoFragment) //val playerAdapter = androidx.leanback.media.MediaPlayerAdapter(context) glueHost = androidx.leanback.app.VideoSupportFragmentGlueHost(this@PlaybackVideoFragment) playerAdapter = androidx.leanback.media.MediaPlayerAdapter(context) playerAdapter.setRepeatAction(androidx.leanback.widget.PlaybackControlsRow.RepeatAction.INDEX_NONE) mTransportControlGlue = androidx.leanback.media.PlaybackTransportControlGlue(getActivity(), playerAdapter) mTransportControlGlue.host = glueHost mTransportControlGlue.title = title mTransportControlGlue.subtitle = description mTransportControlGlue.playWhenPrepared() playerAdapter.setDataSource(android.net.Uri.parse(videoUrl)) } override fun onPause() { super.onPause() mTransportControlGlue.pause() } }
0
Kotlin
0
0
b48e4295e4b14c65f6b60c0712822f749c4d135e
1,947
tv.apk
MIT License
eureka-server/src/main/kotlin/io/microservicesexample/eurekaserver/EurekaServerApplication.kt
rkudryashov
159,522,528
false
null
package microservice.workshop.eurekaserver import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer @SpringBootApplication @EnableEurekaServer class EurekaServerApplication fun main(args: Array<String>) { runApplication<EurekaServerApplication>(*args) }
2
null
4
80
400cfd04020178286724ef22e720ac6bcdb36be3
390
microservices-example
Apache License 2.0
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package89/Foo08993.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.module4.package89 class Foo08993 { fun method0() { Foo08992().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
347
android_multi_module_experiment
Apache License 2.0
src/test/kotlin/no/nav/soknad/arkivering/soknadsarkiverer/service/fileservice/FilestorageServiceTests.kt
navikt
213,857,164
false
null
package no.nav.soknad.arkivering.soknadsarkiverer.service.fileservice import io.prometheus.client.CollectorRegistry import no.nav.security.token.support.client.spring.ClientConfigurationProperties import no.nav.soknad.arkivering.soknadsarkiverer.config.AppConfiguration import no.nav.soknad.arkivering.soknadsarkiverer.config.ArchivingException import no.nav.soknad.arkivering.soknadsarkiverer.dto.FilElementDto import no.nav.soknad.arkivering.soknadsarkiverer.utils.* import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.ActiveProfiles import java.util.* @ActiveProfiles("test") @SpringBootTest @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @ConfigurationPropertiesScan("no.nav.soknad.arkivering", "no.nav.security.token") @EnableConfigurationProperties(ClientConfigurationProperties::class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class FilestorageServiceTests { @Value("\${application.mocked-port-for-external-services}") private val portToExternalServices: Int? = null @Suppress("unused") @MockBean private lateinit var clientConfigurationProperties: ClientConfigurationProperties @Suppress("unused") @MockBean private lateinit var collectorRegistry: CollectorRegistry @Autowired private lateinit var appConfiguration: AppConfiguration @Autowired private lateinit var filestorageService: FilestorageService private lateinit var fileIdsAndResponses: List<Pair<String, String>> private val key = UUID.randomUUID().toString() @BeforeAll fun beforeAll() { setupMockedNetworkServices(portToExternalServices!!, appConfiguration.config.joarkUrl, appConfiguration.config.filestorageUrl) } @BeforeEach fun setup() { fileIdsAndResponses = (0 until 100).map { number -> UUID.randomUUID().toString() to number.toString() } } @AfterAll fun teardown() { stopMockedNetworkServices() } @Test fun `getFilesFromFilestorage - Asking for 0 files - Makes one request - Empty list is returned`() { val numberOfFiles = 0 val files = mockNumberOfFilesAndPerformRequest(numberOfFiles) assertEquals(numberOfFiles, files.size) assertFileContentIsCorrect(files) verifyMockedGetRequests(0, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } @Test fun `getFilesFromFilestorage - Asking for 1 file - Makes one request - List of 1 is returned`() { val numberOfFiles = 1 val files = mockNumberOfFilesAndPerformRequest(numberOfFiles) assertEquals(numberOfFiles, files.size) assertFileContentIsCorrect(files) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } @Test fun `getFilesFromFilestorage - Asking for 6 files - Makes two requests - List of 6 is returned`() { val numberOfFiles = 6 mockFilestorageIsWorking(fileIdsAndResponses.take(filesInOneRequestToFilestorage)) mockFilestorageIsWorking(fileIdsAndResponses.drop(filesInOneRequestToFilestorage).take(1)) mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val files = filestorageService.getFilesFromFilestorage(key, soknadarkivschema) assertEquals(numberOfFiles, files.size) assertFileContentIsCorrect(files) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.take(filesInOneRequestToFilestorage))) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.drop(filesInOneRequestToFilestorage).take(1))) } @Test fun `getFilesFromFilestorage - Asking for 11 files - Makes three requests - List of 11 is returned`() { val numberOfFiles = 11 mockFilestorageIsWorking(fileIdsAndResponses.take(filesInOneRequestToFilestorage)) mockFilestorageIsWorking(fileIdsAndResponses.drop(filesInOneRequestToFilestorage).take(filesInOneRequestToFilestorage)) mockFilestorageIsWorking(fileIdsAndResponses.drop(filesInOneRequestToFilestorage * 2).take(1)) mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val files = filestorageService.getFilesFromFilestorage(key, soknadarkivschema) assertEquals(numberOfFiles, files.size) assertFileContentIsCorrect(files) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.take(filesInOneRequestToFilestorage))) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.drop(filesInOneRequestToFilestorage).take(filesInOneRequestToFilestorage))) verifyMockedGetRequests(1, makeUrl(fileIdsAndResponses.drop(filesInOneRequestToFilestorage * 2).take(1))) } @Test fun `getFilesFromFilestorage - Asking for 3 files - Only 2 is returned - will throw exception`() { val threeFilesInRequest = fileIdsAndResponses.take(3).joinToString(",") { it.first } val twoFilesInResponse = fileIdsAndResponses.take(2) mockFilestorageIsWorking(twoFilesInResponse, threeFilesInRequest) mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(3).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(3).map { it.first }) assertThrows<ArchivingException> { filestorageService.getFilesFromFilestorage(key, soknadarkivschema) } } @Test fun `getFilesFromFilestorage - Asking for 3 files - Filestorage is down - will throw exception`() { val numberOfFiles = 3 mockFilestorageIsDown() mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) assertThrows<ArchivingException> { filestorageService.getFilesFromFilestorage(key, soknadarkivschema) } } @Test fun `getFilesFromFilestorage - Asking for 3 files - One of the files have been deleted - will throw FilesAlreadyDeletedException`() { val numberOfFiles = 3 mockRequestedFileIsGone() mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val e = assertThrows<Exception> { filestorageService.getFilesFromFilestorage(key, soknadarkivschema) } assertTrue(e.cause is FilesAlreadyDeletedException) } @Test fun `deleteFilesFromFilestorage - Deleting 0 files - Makes one request`() { val numberOfFiles = 0 mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) filestorageService.deleteFilesFromFilestorage(key, soknadarkivschema) verifyMockedDeleteRequests(1, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } @Test fun `deleteFilesFromFilestorage - Deleting 1 files - Makes one request`() { val numberOfFiles = 1 mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) filestorageService.deleteFilesFromFilestorage(key, soknadarkivschema) verifyMockedDeleteRequests(1, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } @Test fun `deleteFilesFromFilestorage - Deleting 11 files - Makes one request`() { val numberOfFiles = 11 mockFilestoreageDeletionIsWorking(fileIdsAndResponses.take(numberOfFiles).map { it.first }) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) filestorageService.deleteFilesFromFilestorage(key, soknadarkivschema) verifyMockedDeleteRequests(1, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } @Test fun `deleteFilesFromFilestorage - Deleting 1 files - Filestorage is down - throws no exception`() { val numberOfFiles = 1 mockFilestorageDeletionIsNotWorking() val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) filestorageService.deleteFilesFromFilestorage(key, soknadarkivschema) verifyMockedDeleteRequests(1, makeUrl(fileIdsAndResponses.take(numberOfFiles))) } private fun assertFileContentIsCorrect(files: List<FilElementDto>) { assertAll("All files should have the right content", files.map { result -> { assertEquals(fileIdsAndResponses.first { it.first == result.uuid }.second, result.fil?.map { it.toInt().toChar() }?.joinToString("")) } }) } private fun makeUrl(fileIdsAndResponses: List<Pair<String, String>>) = appConfiguration.config.filestorageUrl.replace("?", "\\?") + fileIdsAndResponses.joinToString(",") { it.first } private fun mockNumberOfFilesAndPerformRequest(numberOfFiles: Int): List<FilElementDto> { mockFilestorageIsWorking(fileIdsAndResponses.take(numberOfFiles)) val soknadarkivschema = createSoknadarkivschema(fileIdsAndResponses.take(numberOfFiles).map { it.first }) return filestorageService.getFilesFromFilestorage(key, soknadarkivschema) } }
4
Kotlin
0
0
8a1b3de5b7f923df71d7bb149ed1c27c1fe951b4
9,504
soknadsarkiverer
MIT License
vck/src/androidMain/kotlin/at/asitplus/wallet/lib/agent/CryptoService.android.kt
a-sit-plus
602,578,639
false
{"Kotlin": 1076316}
package at.asitplus.wallet.lib.agent import at.asitplus.KmmResult import at.asitplus.KmmResult.Companion.wrap import at.asitplus.signum.indispensable.josef.* import javax.crypto.Cipher import javax.crypto.Mac import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec actual open class PlatformCryptoShim actual constructor(actual val keyMaterial: KeyMaterial) { actual open fun encrypt( key: ByteArray, iv: ByteArray, aad: ByteArray, input: ByteArray, algorithm: JweEncryption ): KmmResult<AuthenticatedCiphertext> = runCatching { val jcaCiphertext = Cipher.getInstance(algorithm.jcaName).also { if (algorithm.isAuthenticatedEncryption) { it.init( Cipher.ENCRYPT_MODE, SecretKeySpec(key, algorithm.jcaKeySpecName), GCMParameterSpec(algorithm.ivLengthBits, iv) ) it.updateAAD(aad) } else { it.init( Cipher.ENCRYPT_MODE, SecretKeySpec(key, algorithm.jcaKeySpecName), ) } }.doFinal(input) if (algorithm.isAuthenticatedEncryption) { val ciphertext = jcaCiphertext.dropLast(algorithm.ivLengthBits / 8).toByteArray() val authtag = jcaCiphertext.takeLast(algorithm.ivLengthBits / 8).toByteArray() AuthenticatedCiphertext(ciphertext, authtag) } else { AuthenticatedCiphertext(jcaCiphertext, byteArrayOf()) } }.wrap() actual open suspend fun decrypt( key: ByteArray, iv: ByteArray, aad: ByteArray, input: ByteArray, authTag: ByteArray, algorithm: JweEncryption ): KmmResult<ByteArray> = runCatching { Cipher.getInstance(algorithm.jcaName).also { if (algorithm.isAuthenticatedEncryption) { it.init( Cipher.DECRYPT_MODE, SecretKeySpec(key, algorithm.jcaKeySpecName), GCMParameterSpec(algorithm.ivLengthBits, iv) ) it.updateAAD(aad) } else { it.init( Cipher.DECRYPT_MODE, SecretKeySpec(key, algorithm.jcaKeySpecName), ) } }.doFinal(input + authTag) }.wrap() actual open fun performKeyAgreement( ephemeralKey: EphemeralKeyHolder, recipientKey: JsonWebKey, algorithm: JweAlgorithm ): KmmResult<ByteArray> { return KmmResult.success("sharedSecret-${algorithm.identifier}".encodeToByteArray()) } actual open fun performKeyAgreement(ephemeralKey: JsonWebKey, algorithm: JweAlgorithm): KmmResult<ByteArray> { return KmmResult.success("sharedSecret-${algorithm.identifier}".encodeToByteArray()) } actual open fun hmac( key: ByteArray, algorithm: JweEncryption, input: ByteArray, ): KmmResult<ByteArray> = runCatching { Mac.getInstance(algorithm.jcaHmacName).also { it.init(SecretKeySpec(key, algorithm.jcaKeySpecName)) }.doFinal(input) }.wrap() }
11
Kotlin
1
22
6f29a2ba84aceda63026afcfc8fd6cc0d8ccbb00
3,233
vck
Apache License 2.0
core/descriptors.jvm/src/org/jetbrains/kotlin/builtins/jvm/JvmBuiltInClassDescriptorFactory.kt
JetBrains
3,432,266
false
null
/* * 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.builtins.jvm import org.jetbrains.kotlin.builtins.BuiltInsPackageFragment import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.deserialization.ClassDescriptorFactory import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorImpl import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.getValue class JvmBuiltInClassDescriptorFactory( storageManager: StorageManager, private val moduleDescriptor: ModuleDescriptor, private val computeContainingDeclaration: (ModuleDescriptor) -> DeclarationDescriptor = { module -> module.getPackage(KOTLIN_FQ_NAME).fragments.filterIsInstance<BuiltInsPackageFragment>().first() } ) : ClassDescriptorFactory { private val cloneable by storageManager.createLazyValue { ClassDescriptorImpl( computeContainingDeclaration(moduleDescriptor), CLONEABLE_NAME, Modality.ABSTRACT, ClassKind.INTERFACE, listOf(moduleDescriptor.builtIns.anyType), SourceElement.NO_SOURCE, false, storageManager ).apply { initialize(CloneableClassScope(storageManager, this), emptySet(), null) } } override fun shouldCreateClass(packageFqName: FqName, name: Name): Boolean = name == CLONEABLE_NAME && packageFqName == KOTLIN_FQ_NAME override fun createClass(classId: ClassId): ClassDescriptor? = when (classId) { CLONEABLE_CLASS_ID -> cloneable else -> null } override fun getAllContributedClassesIfPossible(packageFqName: FqName): Collection<ClassDescriptor> = when (packageFqName) { KOTLIN_FQ_NAME -> setOf(cloneable) else -> emptySet() } companion object { private val KOTLIN_FQ_NAME = StandardNames.BUILT_INS_PACKAGE_FQ_NAME private val CLONEABLE_NAME = StandardNames.FqNames.cloneable.shortName() val CLONEABLE_CLASS_ID = ClassId.topLevel(StandardNames.FqNames.cloneable.toSafe()) } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,405
kotlin
Apache License 2.0
state-tracker/src/main/java/org/jetbrains/ruby/stateTracker/RubyClassHierarchy.kt
JetBrains
85,180,339
false
null
package org.jetbrains.ruby.stateTracker interface RubyClassHierarchy { val loadPaths: List<String> val topLevelConstants: Map<String, RubyConstant> fun getRubyModule(fqn: String) : RubyModule? class Impl(override val loadPaths: List<String>, rubyModules: List<RubyModule>, override val topLevelConstants: Map<String, RubyConstant>) : RubyClassHierarchy { private val name2modules = rubyModules.associateBy( {it.name} , {it}) override fun getRubyModule(fqn: String): RubyModule? { return name2modules[fqn] } } } interface RubyConstant { val name: String val type: String val extended: List<String> data class Impl(override val name: String, override val type: String, override val extended: List<String>) : RubyConstant } interface RubyModule { val name: String val classIncluded: List<RubyModule> val instanceIncluded: List<RubyModule> val classMethods: List<RubyMethod> val instanceMethods: List<RubyMethod> class Impl(override val name: String, override val classIncluded: List<RubyModule>, override val instanceIncluded: List<RubyModule>, override val classMethods: List<RubyMethod>, override val instanceMethods: List<RubyMethod>) : RubyModule } interface RubyClass: RubyModule { val superClass : RubyClass class Impl(override val name: String, override val classIncluded: List<RubyModule>, override val instanceIncluded: List<RubyModule>, override val classMethods: List<RubyMethod>, override val instanceMethods: List<RubyMethod>, override val superClass: RubyClass) : RubyClass companion object : RubyClass { val EMPTY = this override val name: String get() = "" override val classIncluded: List<RubyModule> get() = emptyList() override val instanceIncluded: List<RubyModule> get() = emptyList() override val classMethods: List<RubyMethod> get() = emptyList() override val instanceMethods: List<RubyMethod> get() = emptyList() override val superClass: RubyClass get() = this } } interface RubyMethod { val name: String val location: Location? val arguments: List<ArgInfo> data class ArgInfo(val kind: ArgumentKind, val name: String) class Impl(override val name: String, override val location: Location?, override val arguments: List<ArgInfo>) : RubyMethod enum class ArgumentKind { REQ, OPT, REST, KEY, KEY_REST, KEY_REQ, BLOCK; companion object { fun fromString(name : String): ArgumentKind { return when (name) { "req" -> REQ "opt" -> OPT "rest" -> REST "key" -> KEY "keyrest" -> KEY_REST "keyreq" -> KEY_REQ "block" -> BLOCK else -> throw IllegalArgumentException(name) } } } } } interface Location { val path: String val lineNo: Int data class Impl(override val path: String, override val lineNo: Int) : Location }
17
Kotlin
8
135
df63525a226c4926614a3937546b570b68bc42aa
3,470
ruby-type-inference
Apache License 2.0
ChatAvatarSetter/src/main/kotlin/ChatAvatarSetter.kt
InsanusMokrassar
242,931,149
false
{"Kotlin": 158639, "HTML": 2109}
import dev.inmo.micro_utils.coroutines.runCatchingSafely import dev.inmo.tgbotapi.bot.ktor.telegramBot import dev.inmo.tgbotapi.extensions.api.chat.modify.setChatPhoto import dev.inmo.tgbotapi.extensions.api.files.downloadFile import dev.inmo.tgbotapi.extensions.api.send.reply import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithLongPolling import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onPhoto import dev.inmo.tgbotapi.requests.abstracts.asMultipartFile import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers suspend fun main(args: Array<String>) { val bot = telegramBot(args.first()) bot.buildBehaviourWithLongPolling(scope = CoroutineScope(Dispatchers.IO)) { onPhoto { val bytes = downloadFile(it.content) runCatchingSafely { setChatPhoto( it.chat.id, bytes.asMultipartFile("sample.jpg") ) }.onSuccess { b -> if (b) { reply(it, "Done") } else { reply(it, "Something went wrong") } }.onFailure { e -> e.printStackTrace() reply(it, "Something went wrong (see logs)") } } }.join() }
6
Kotlin
5
45
e34f0ec9d8ffc49ce562e4c18b8b54225cbc1660
1,337
TelegramBotAPI-examples
MIT License
examples/migration/android-compose-dagger/buildSrc/src/main/kotlin/template/workspace_template.kt
Morfly
368,910,388
false
null
/* * Copyright 2021 Pavlo Stavytskyi * * 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. */ @file:Suppress("LocalVariableName", "FunctionName", "SpellCheckingInspection", "UNUSED_VARIABLE") package template import org.morfly.airin.starlark.lang.StringType import org.morfly.airin.starlark.lang.WORKSPACE import org.morfly.airin.starlark.library.* fun workspace_template( artifactList: List<String>, composeArtifactsWithoutVersion: List<String> /** * */ ) = WORKSPACE { workspace(name = "android-compose-dagger") val KOTLIN_COMPILER_VERSION by "1.5.10" val COMPOSE_VERSION by "1.0.0" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") val RULES_JAVA_VERSION by "4.0.0" val RULES_JAVA_SHA by "34b41ec683e67253043ab1a3d1e8b7c61e4e8edefbcad485381328c934d072fe" http_archive( name = "rules_java", url = "https://github.com/bazelbuild/rules_java/releases/download/{v}/rules_java-{v}.tar.gz".format { "v" `=` RULES_JAVA_VERSION }, sha256 = RULES_JAVA_SHA, ) load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains") "rules_java_dependencies"() "rules_java_toolchains"() val DAGGER_TAG by "2.36" val DAGGER_SHA by "1e6d5c64d336af2e14c089124bf2bd9d449010db02534ce820abc6a7f0429c86" http_archive( name = "dagger", strip_prefix = "dagger-dagger-%s" `%` DAGGER_TAG, sha256 = DAGGER_SHA, urls = list["https://github.com/google/dagger/archive/dagger-%s.zip" `%` DAGGER_TAG], ) val (DAGGER_ARTIFACTS, DAGGER_REPOSITORIES) = load( "@dagger//:workspace_defs.bzl", "DAGGER_ARTIFACTS", "DAGGER_REPOSITORIES" ).v<List<StringType>, List<StringType>>() val RULES_JVM_EXTERNAL_VERSION by "4.1" val RULES_JVM_EXTERNAL_SHA by "f36441aa876c4f6427bfb2d1f2d723b48e9d930b62662bf723ddfb8fc80f0140" http_archive( name = "rules_jvm_external", sha256 = RULES_JVM_EXTERNAL_SHA, strip_prefix = "rules_jvm_external-%s" `%` RULES_JVM_EXTERNAL_VERSION, urls = list[ "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" `%` RULES_JVM_EXTERNAL_VERSION, ], ) load("@rules_jvm_external//:defs.bzl", "maven_install") val composeArtifacts = linkedSetOf<String>().also { it += composeArtifactsWithoutVersion it += "androidx.compose.compiler:compiler" it += "androidx.compose.runtime:runtime" }.map { "$it:%s" `%` COMPOSE_VERSION } maven_install( artifacts = DAGGER_ARTIFACTS `+` artifactList.sorted() + composeArtifacts + list[ "com.google.guava:guava:28.1-android" ], override_targets = dict { "org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm" to "@//third_party:kotlinx_coroutines_core_jvm" "org.jetbrains.kotlin:kotlin-reflect" to "@//third_party:kotlin_reflect" "androidx.room:room-runtime" to "@//third_party:room_runtime" }, repositories = DAGGER_REPOSITORIES `+` list[ "https://maven.google.com", "https://repo1.maven.org/maven2", ], ) // Secondary maven artifact repository that works as a workaround for those artifacts // that have problems loading with the primary 'maven_install' rule. // It loads problematic artifacts separately which are being handled in the 'third-party' // package. // As a result, the primary 'maven-install' overrides problematic artifacts with the fixed ones // from the 'third_party' package. maven_install( name = "maven_secondary", artifacts = list[ "org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.1", "androidx.room:room-runtime:2.3.0", ], repositories = list[ "https://maven.google.com", "https://repo1.maven.org/maven2", ] ) val RULES_ANDROID_VERSION by "0.1.1" val RULES_ANDROID_SHA by "cd06d15dd8bb59926e4d65f9003bfc20f9da4b2519985c27e190cddc8b7a7806" http_archive( name = "rules_android", sha256 = RULES_ANDROID_SHA, strip_prefix = "rules_android-%s" `%` RULES_ANDROID_VERSION, urls = list[ "https://github.com/bazelbuild/rules_android/archive/v%s.zip" `%` RULES_ANDROID_VERSION, ], ) load("@rules_android//android:rules.bzl", "android_sdk_repository") android_sdk_repository( name = "androidsdk", api_level = 29, build_tools_version = "29.0.3", ) val RULES_KOTLIN_VERSION by "c26007a1776a79d94bea7c257ef07a23bbc998d5" val RULES_KOTLIN_SHA by "be7b1fac4f93fbb81eb79f2f44caa97e1dfa69d2734e4e184443acd9f5182386" http_archive( name = "io_bazel_rules_kotlin", sha256 = RULES_KOTLIN_SHA, strip_prefix = "rules_kotlin-%s" `%` RULES_KOTLIN_VERSION, urls = list[ "https://github.com/bazelbuild/rules_kotlin/archive/%s.tar.gz" `%` RULES_KOTLIN_VERSION, ], ) load("@io_bazel_rules_kotlin//kotlin:dependencies.bzl", "kt_download_local_dev_dependencies") "kt_download_local_dev_dependencies"() load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kotlin_repositories") val RULES_KOTLIN_COMPILER_RELEASE by dict { "urls" to list[ "https://github.com/JetBrains/kotlin/releases/download/v{v}/kotlin-compiler-{v}.zip".format { "v" `=` KOTLIN_COMPILER_VERSION }, ] "sha256" to "2f8de1d73b816354055ff6a4b974b711c11ad55a68b948ed30b38155706b3c4e" } kotlin_repositories( compiler_release = RULES_KOTLIN_COMPILER_RELEASE, ) register_toolchains("//:kotlin_toolchain") }
1
Kotlin
3
31
f778911492a8de2e2b11e1caa53d1b8e5f3eb08f
6,255
airin
Apache License 2.0
src/main/kotlin/days/Day8.kt
hughjdavey
225,440,374
false
null
package days class Day8 : Day(8) { override fun partOne(): Any { val min = decodeImage(inputString.trim(), 6, 25).minBy { it.countOf('0') } return if (min == null) 0 else min.countOf('1') * min.countOf('2') } override fun partTwo(): Any { // HCGFE return "\n" + realImage(inputString.trim(), 6, 25).rows.joinToString("\n") { it.replace('0', ' ').replace('1', '■') } } fun decodeImage(imageData: String, imageHeight: Int, imageWidth: Int): List<ImageLayer> { val layerCount = imageData.length / (imageHeight * imageWidth) return imageData.chunked(imageData.length / layerCount).map { ImageLayer(it.chunked(imageWidth)) } } fun realImage(imageData: String, imageHeight: Int, imageWidth: Int): ImageLayer { val layers = decodeImage(imageData, imageHeight, imageWidth) val rows = (0 until imageHeight).flatMap { x -> (0 until imageWidth).map { y -> layers.topVisiblePixel(x to y) } } .chunked(imageWidth).map { it.fold("") { acc, c -> acc.plus(c) } } return ImageLayer(rows) } data class ImageLayer(val rows: List<String>) { fun countOf(char: Char): Int { return rows.joinToString("").toList().count { it == char } } } private fun List<ImageLayer>.topVisiblePixel(position: Pair<Int, Int>): Char { return this.find { it.rows[position.first][position.second] != '2' }?.rows?.get(position.first)?.get(position.second) ?: 'X' } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
1,503
aoc-2019
Creative Commons Zero v1.0 Universal
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/sagemaker/CfnUserProfileUserSettingsPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.sagemaker import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.sagemaker.CfnUserProfile /** * A collection of settings that apply to users of Amazon SageMaker Studio. * * These settings are specified when the * [CreateUserProfile](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateUserProfile.html) * API is called, and as `DefaultUserSettings` when the * [CreateDomain](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateDomain.html) API * is called. * * `SecurityGroups` is aggregated when specified in both calls. For all other settings in * `UserSettings` , the values specified in `CreateUserProfile` take precedence over those specified in * `CreateDomain` . * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sagemaker.*; * UserSettingsProperty userSettingsProperty = UserSettingsProperty.builder() * .executionRole("executionRole") * .jupyterServerAppSettings(JupyterServerAppSettingsProperty.builder() * .defaultResourceSpec(ResourceSpecProperty.builder() * .instanceType("instanceType") * .sageMakerImageArn("sageMakerImageArn") * .sageMakerImageVersionArn("sageMakerImageVersionArn") * .build()) * .build()) * .kernelGatewayAppSettings(KernelGatewayAppSettingsProperty.builder() * .customImages(List.of(CustomImageProperty.builder() * .appImageConfigName("appImageConfigName") * .imageName("imageName") * // the properties below are optional * .imageVersionNumber(123) * .build())) * .defaultResourceSpec(ResourceSpecProperty.builder() * .instanceType("instanceType") * .sageMakerImageArn("sageMakerImageArn") * .sageMakerImageVersionArn("sageMakerImageVersionArn") * .build()) * .build()) * .rStudioServerProAppSettings(RStudioServerProAppSettingsProperty.builder() * .accessStatus("accessStatus") * .userGroup("userGroup") * .build()) * .securityGroups(List.of("securityGroups")) * .sharingSettings(SharingSettingsProperty.builder() * .notebookOutputOption("notebookOutputOption") * .s3KmsKeyId("s3KmsKeyId") * .s3OutputPath("s3OutputPath") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sagemaker-userprofile-usersettings.html) */ @CdkDslMarker public class CfnUserProfileUserSettingsPropertyDsl { private val cdkBuilder: CfnUserProfile.UserSettingsProperty.Builder = CfnUserProfile.UserSettingsProperty.builder() private val _securityGroups: MutableList<String> = mutableListOf() /** * @param executionRole The execution role for the user. */ public fun executionRole(executionRole: String) { cdkBuilder.executionRole(executionRole) } /** * @param jupyterServerAppSettings The Jupyter server's app settings. */ public fun jupyterServerAppSettings(jupyterServerAppSettings: IResolvable) { cdkBuilder.jupyterServerAppSettings(jupyterServerAppSettings) } /** * @param jupyterServerAppSettings The Jupyter server's app settings. */ public fun jupyterServerAppSettings(jupyterServerAppSettings: CfnUserProfile.JupyterServerAppSettingsProperty) { cdkBuilder.jupyterServerAppSettings(jupyterServerAppSettings) } /** * @param kernelGatewayAppSettings The kernel gateway app settings. */ public fun kernelGatewayAppSettings(kernelGatewayAppSettings: IResolvable) { cdkBuilder.kernelGatewayAppSettings(kernelGatewayAppSettings) } /** * @param kernelGatewayAppSettings The kernel gateway app settings. */ public fun kernelGatewayAppSettings(kernelGatewayAppSettings: CfnUserProfile.KernelGatewayAppSettingsProperty) { cdkBuilder.kernelGatewayAppSettings(kernelGatewayAppSettings) } /** * @param rStudioServerProAppSettings A collection of settings that configure user interaction * with the `RStudioServerPro` app. */ public fun rStudioServerProAppSettings(rStudioServerProAppSettings: IResolvable) { cdkBuilder.rStudioServerProAppSettings(rStudioServerProAppSettings) } /** * @param rStudioServerProAppSettings A collection of settings that configure user interaction * with the `RStudioServerPro` app. */ public fun rStudioServerProAppSettings(rStudioServerProAppSettings: CfnUserProfile.RStudioServerProAppSettingsProperty) { cdkBuilder.rStudioServerProAppSettings(rStudioServerProAppSettings) } /** * @param securityGroups The security groups for the Amazon Virtual Private Cloud (VPC) that * Studio uses for communication. * Optional when the `CreateDomain.AppNetworkAccessType` parameter is set to `PublicInternetOnly` * . * * Required when the `CreateDomain.AppNetworkAccessType` parameter is set to `VpcOnly` , unless * specified as part of the `DefaultUserSettings` for the domain. * * Amazon SageMaker adds a security group to allow NFS traffic from SageMaker Studio. Therefore, * the number of security groups that you can specify is one less than the maximum number shown. */ public fun securityGroups(vararg securityGroups: String) { _securityGroups.addAll(listOf(*securityGroups)) } /** * @param securityGroups The security groups for the Amazon Virtual Private Cloud (VPC) that * Studio uses for communication. * Optional when the `CreateDomain.AppNetworkAccessType` parameter is set to `PublicInternetOnly` * . * * Required when the `CreateDomain.AppNetworkAccessType` parameter is set to `VpcOnly` , unless * specified as part of the `DefaultUserSettings` for the domain. * * Amazon SageMaker adds a security group to allow NFS traffic from SageMaker Studio. Therefore, * the number of security groups that you can specify is one less than the maximum number shown. */ public fun securityGroups(securityGroups: Collection<String>) { _securityGroups.addAll(securityGroups) } /** * @param sharingSettings Specifies options for sharing SageMaker Studio notebooks. */ public fun sharingSettings(sharingSettings: IResolvable) { cdkBuilder.sharingSettings(sharingSettings) } /** * @param sharingSettings Specifies options for sharing SageMaker Studio notebooks. */ public fun sharingSettings(sharingSettings: CfnUserProfile.SharingSettingsProperty) { cdkBuilder.sharingSettings(sharingSettings) } public fun build(): CfnUserProfile.UserSettingsProperty { if(_securityGroups.isNotEmpty()) cdkBuilder.securityGroups(_securityGroups) return cdkBuilder.build() } }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
6,955
awscdk-dsl-kotlin
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/K2Tests.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.testbase.* import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.condition.OS import kotlin.test.Ignore import kotlin.test.assertEquals @Disabled("Used for local testing only") @MppGradlePluginTests @DisplayName("K2: Hierarchical multiplatform") class K2HierarchicalMppIT : HierarchicalMppIT() { override val defaultBuildOptions: BuildOptions get() = super.defaultBuildOptions.copy(languageVersion = "2.0") } @MppGradlePluginTests @DisplayName("KLibs in K2") class K2KlibBasedMppIT : KlibBasedMppIT() { override val defaultBuildOptions: BuildOptions = super.defaultBuildOptions.copyEnsuringK2().disableConfigurationCache_KT70416() } @Disabled("Used for local testing only") class K2CommonizerIT : CommonizerIT() { override val defaultBuildOptions: BuildOptions get() = super.defaultBuildOptions.copy(languageVersion = "2.0") } @Ignore class K2CommonizerHierarchicalIT : CommonizerHierarchicalIT() { override val defaultBuildOptions: BuildOptions = super.defaultBuildOptions .copy(languageVersion = "2.0") .disableConfigurationCache_KT70416() } @MppGradlePluginTests @DisplayName("K2: custom tests") class CustomK2Tests : KGPBaseTest() { override val defaultBuildOptions: BuildOptions get() = super.defaultBuildOptions.copyEnsuringK2() @GradleTest @DisplayName("Serialization plugin in common source set. KT-56911") fun testHmppDependenciesInJsTests(gradleVersion: GradleVersion) { project( "k2-serialization-plugin-in-common-sourceset", gradleVersion, ) { val taskToExecute = ":compileKotlinJs" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("HMPP compilation without JS target. KT-57376, KT-57377, KT-57635, KT-57654") fun testHmppCompilationWithoutJsTarget(gradleVersion: GradleVersion) { with(project("k2-mpp-without-js", gradleVersion)) { val taskToExecute = ":compileIntermediateMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("HMPP compilation with JS target and old stdlib. KT-59151") fun testHmppCompilationWithJsAndOldStdlib(gradleVersion: GradleVersion) { with(project("k2-mpp-js-old-stdlib", gradleVersion)) { val taskToExecute = ":compileKotlinJs" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Native metadata of intermediate with reference to internal in common. KT-58219") fun nativeMetadataOfIntermediateWithReferenceToInternalInCommon(gradleVersion: GradleVersion) { with(project("k2-native-intermediate-metadata", gradleVersion)) { val taskToExecute = ":compileNativeMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Native metadata of intermediate with multiple targets. KT-61461") fun nativeMetadataOfIntermediateWithMultipleTargets(gradleVersion: GradleVersion) { with(project("k2-native-intermediate-multiple-targets", gradleVersion)) { val taskToExecute = ":compileNativeMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Compiling shared native source with FirFakeOverrideGenerator referencing a common entity. KT-58145") fun kt581450MppNativeSharedCrash(gradleVersion: GradleVersion) { with( project( "kt-581450-mpp-native-shared-crash", gradleVersion, ) ) { val taskToExecute = ":compileNativeMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Compiling shared native source with intrinsic initializer from common source set in Native-shared source set. KT-58444") fun kt58444NativeSharedConstantIntrinsic(gradleVersion: GradleVersion) { with( project( "kt-58444-native-shared-constant-intrinsic", gradleVersion, ) ) { val taskToExecute = ":compileNativeMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Java binary dependency class contains unresolved annotation argument. KT-60181") fun kt60181JavaDependencyAnnotatedWithUnresolved(gradleVersion: GradleVersion) { with( project( "k2-java-dep-unresolved-annotation-argument", gradleVersion, ) ) { val taskToExecute = ":compileKotlin" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("All source sets have opt-in for annotation defined in platform source set. KT-60755") fun kt60755OptInDefinedInPlatform(gradleVersion: GradleVersion) { with( project( "k2-mpp-opt-in-in-platform", gradleVersion, ) ) { val taskToExecute = ":compileKotlinJvm" build(taskToExecute) { assertTasksExecuted(taskToExecute) assertOutputDoesNotContain("Opt-in requirement marker foo.bar.MyOptIn is unresolved") } } } @GradleTest @DisplayName("Common metadata compilation. KT-60943") fun kt60943CommonMetadataCompilation(gradleVersion: GradleVersion) { project( "k2-serialization-plugin-in-common-sourceset", gradleVersion, ) { val taskToExecute = ":compileCommonMainKotlinMetadata" build(taskToExecute) { assertTasksExecuted(taskToExecute) } } } @GradleTest @DisplayName("Common metadata compilation (expect actual discrimination). KT-61540") fun kt60438MetadataExpectActualDiscrimination(gradleVersion: GradleVersion) { project( "k2-kt-61540-expect-actual-discrimination", gradleVersion, ) { build("assemble") { assertTasksExecuted(":compileCommonMainKotlinMetadata") assertTasksExecuted(":compileNativeMainKotlinMetadata") assertTasksExecuted(":compileLinuxMainKotlinMetadata") } } } @GradleTest @DisplayName("No overload resolution ambiguity between expect and non-expect in native") fun kt61778NoOverloadResolutionAmbiguityBetweenExpectAndNonExpectInNative(gradleVersion: GradleVersion) { project( "k2-no-overload-resolution-ambiguity-between-expect-and-non-expect-in-native", gradleVersion, ) { build("compileCommonMainKotlinMetadata") { assertTasksExecuted(":compileCommonMainKotlinMetadata") extractNativeTasksCommandLineArgumentsFromOutput(":compileCommonMainKotlinMetadata") { val stdlibCounts = args.count { it != "-nostdlib" && it.contains("stdlib") } assertEquals( 1, stdlibCounts, "Expected a single stdlib in the command line arguments, but got $stdlibCounts" ) } } } } @GradleTest @DisplayName("Native metadata compilation with constant expressions (KT-63835)") fun nativeMetadataCompilationWithConstantExpressions(gradleVersion: GradleVersion) { project("k2-native-metadata-compilation-with-constant-expressions", gradleVersion) { build("compileCommonMainKotlinMetadata") { assertTasksExecuted(":compileCommonMainKotlinMetadata") } } } @GradleTest @DisplayName("Native metadata compilation against other klib (KT-65840)") fun nativeMetadataCompilationWithAgainstOtherKlib(gradleVersion: GradleVersion) { project("k2-common-native-against-other-klib", gradleVersion) { build(":app:compileNativeMainKotlinMetadata") { assertTasksExecuted(":app:compileNativeMainKotlinMetadata") } } } } @NativeGradlePluginTests @OsCondition(supportedOn = [OS.MAC], enabledOnCI = [OS.MAC]) @DisplayName("K2: custom MacOS tests") class CustomK2MacOSTests : KGPBaseTest() { override val defaultBuildOptions: BuildOptions get() = super.defaultBuildOptions.copyEnsuringK2() @GradleTest @DisplayName("Universal metadata compilation with constant expressions (KT-63835)") fun universalMetadataCompilationWithConstantExpressions(gradleVersion: GradleVersion) { project("k2-universal-metadata-compilation-with-constant-expressions", gradleVersion) { build("assemble") { assertTasksExecuted(":assemble") assertTasksExecuted(":compileIosMainKotlinMetadata") } } } }
183
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
9,649
kotlin
Apache License 2.0
library/controller/kmp-tor-controller/src/jvmAndroidMain/kotlin/io/matthewnelson/kmp/tor/controller/internal/io/-WriterWrapper.kt
05nelsonm
456,238,754
false
{"Kotlin": 1053325}
/* * Copyright (c) 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.matthewnelson.kmp.tor.controller.internal.io import io.matthewnelson.kmp.tor.controller.common.exceptions.TorControllerException import java.io.IOException import java.io.OutputStreamWriter @JvmInline internal actual value class WriterWrapper private actual constructor(private val value: Any) { private inline val asWriter: OutputStreamWriter get() = value as OutputStreamWriter @Throws(TorControllerException::class) internal actual fun write(string: String) { try { asWriter.write(string) } catch (e: IOException) { throw TorControllerException(e) } } @Throws(TorControllerException::class) internal actual fun flush() { try { asWriter.flush() } catch (e: IOException) { throw TorControllerException(e) } } companion object { internal fun wrap(writer: OutputStreamWriter): WriterWrapper = WriterWrapper(writer) } }
25
Kotlin
5
33
7888dc90b99b04f8d28f8abe7ccfb7402e2bd1bc
1,575
kmp-tor
Apache License 2.0
appbase/src/main/java/com/pthw/appbase/utils/LocalBroadcastEventBus.kt
PhyoThihaWin
769,428,664
false
{"Kotlin": 66565}
package com.pthw.appbase.utils import com.pthw.appbase.utils.LocalBroadcastEventBus.EventType import com.pthw.appbase.utils.LocalBroadcastEventBus.LocalEventListener import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.filterIsInstance import timber.log.Timber import javax.inject.Inject import kotlin.coroutines.coroutineContext /** * Created by P.T.H.W on 20/11/2023. * * Replacement for [LocalBroadcastManager], it'll be deprecated in future. Inspire to EventBus, * use singleton [MutableStateFlow] and collected from [MainActivity]. Currently it's used for @401, @502, @RatingReview. * If you want to add more other events, add in [LocalEventListener], [EventType]. */ class LocalBroadcastEventBus @Inject constructor() { private val _events = MutableStateFlow<EventType?>(null) private val events = _events.asStateFlow() fun publish(event: EventType) { Timber.i("EventBus : publish") _events.value = event } fun clear() { _events.value = null } suspend fun subscribe(onEvent: LocalEventListener) { clear() events.filterIsInstance<EventType>() .collectLatest { event -> coroutineContext.ensureActive() when (event) { is EventType.UnAuthenticated -> { onEvent.unauthenticated() } is EventType.ServiceUnavailable -> { onEvent.serviceUnavailable() } is EventType.IllegalAccount -> { onEvent.illegalAccount() } is EventType.NavigateScreen -> { onEvent.navigateScreen(event.data) } } } } sealed class EventType { object UnAuthenticated : EventType() object ServiceUnavailable : EventType() object IllegalAccount : EventType() class NavigateScreen(val data: Any?) : EventType() } abstract class LocalEventListener { // 401 open fun unauthenticated() { Timber.i("EventBus : unauthenticated") } // 503 open fun serviceUnavailable() { Timber.i("EventBus : serviceUnavailable") } // 451 open fun illegalAccount() { Timber.i("EventBus : illegalAccount") } open fun navigateScreen(data: Any?) { Timber.i("EventBus : navigateScreen") } } }
0
Kotlin
0
0
a96fb34881e17b6bef8ca3048605900abd9977e4
2,686
compose-rsa-biometric
Apache License 2.0
PodcastEngine/src/main/kotlin/File.kt
StaticallyTypedRice
175,922,384
false
null
package podcastengine.file import java.net.URL import java.util.NoSuchElementException class FileName(_name: String, _noExtraSpaces: Boolean = true) { companion object { val invalidFilenameCharacters = arrayOf( '\\', '/', ':', '*', '?', '"', '<', '>', '|' ) } val noExtraSpaces = _noExtraSpaces // Whether to remove extra spaces when parsing the file name val name = parse(_name) // Automatically parse the filename when initializing the object val extension = parseExtension(name) // The file extension /** * Removes invalid file name characters. * * @param name The string to be parsed. * @param placeholder Replace invalid file name characters with this string. */ fun removeInvalidFilenameCharacters(name: String, placeholder: String = ""): String { var newName = name for (character in invalidFilenameCharacters) { newName = newName.replace(character.toString(), placeholder) } return newName } /** * Removes extra spaces from the file name. * * @param name The string to be parsed. */ fun removeExtraSpaces(name: String): String { return name.replace("\\s+".toRegex(), " ") } /** * Parses a string into a valid file name. * * @param name The string to be parsed. */ fun parse(name: String): String { var newName = name newName = removeInvalidFilenameCharacters(newName) if (noExtraSpaces) { newName = removeExtraSpaces(newName) } return newName } /** * Parse the file extension. * * @param name The string to be parsed. */ fun parseExtension(name: String): String { var nameList: List<String> try { nameList = name.split(".").dropLastWhile { it.isEmpty() } if (nameList.lastIndex == 0) { // The file name does not contain dots and therefore has no extension return "" } else { return nameList.last() } } catch (e: NoSuchElementException) { return "" } } } /** * Parses the file name from a URL. * - Gets the final item in a slash character seperated URL. * - Removes query strings. * * Assumes that the URL will be structured as a standard file path. * * @param url The URL to parse. */ fun parseFilenameFromUrl(url: URL): FileName { try { return FileName(url.path.split("/").dropLastWhile { it.isEmpty() }.last()) } catch (e: NoSuchElementException) { return FileName("") } }
0
Kotlin
0
6
1172461097881b075fb7f9e10c94e4bde92eb1af
2,823
PodKatch
MIT License
LudoSpringBoot/game-server/src/test/kotlin/hu/bme/aut/alkfejl/ludospringboot/gameserver/GameServerApplicationTests.kt
Kis-Benjamin
693,261,151
false
{"Kotlin": 358575, "Shell": 2693, "Dockerfile": 2134}
/* * Copyright © 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package hu.bme.aut.alkfejl.ludospringboot.gameserver import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class GameServerApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
731f304280ad30068c0149fdd04a94213ebea2e1
829
Ludo
Apache License 2.0
FloatButton/app/src/main/java/com/example/floatbutton/MainActivity.kt
yuuuuke
335,872,718
false
null
package com.example.floatbutton import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.graphics.Color import android.graphics.Point import android.os.Bundle import android.os.IBinder import android.util.Log import android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN import android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE import android.widget.FrameLayout import androidx.appcompat.app.AppCompatActivity import com.example.floatbutton.function1.Function1Activity import com.example.floatbutton.function10.Function10Activity import com.example.floatbutton.function11.Function11Activity import com.example.floatbutton.function12.Function12Activity import com.example.floatbutton.function13.Function13Activity import com.example.floatbutton.function15.Function15Activity import com.example.floatbutton.function2.Function2Activity import com.example.floatbutton.function3.Function3Activity import com.example.floatbutton.function4.Function4Activity import com.example.floatbutton.function5.Function5Activity import com.example.floatbutton.function6.Function6Activity import com.example.floatbutton.function7.Function7Activity import com.example.floatbutton.function8.Function8Activity import com.example.floatbutton.function9.Function9Activity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), ServiceConnection { private lateinit var mAdapter: FunctionAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) window.statusBarColor = Color.TRANSPARENT val frameLayout = findViewById<FrameLayout>(R.id.root_layout) frameLayout.systemUiVisibility = (SYSTEM_UI_FLAG_LAYOUT_STABLE or SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) mAdapter = FunctionAdapter(this) function_list.adapter = mAdapter addView() val display = getWindowManager().getDefaultDisplay(); val point = Point(); display.getSize(point); val width = display.getWidth(); val height = display.getHeight(); Log.v("zwp", "$width//" + height) val scale: Float = getResources().getDisplayMetrics().density Log.v("zwp", "${height / scale + 0.5f}///") } private fun addView() { val function1 = FunctionBean("七彩光圈") { startActivity(Intent(this, Function1Activity::class.java)) } mAdapter.addData(function1) val function2 = FunctionBean("水波纹") { startActivity(Intent(this, Function2Activity::class.java)) } mAdapter.addData(function2) val function3 = FunctionBean("蜘蛛网") { startActivity(Intent(this, Function3Activity::class.java)) } mAdapter.addData(function3) val function4 = FunctionBean("翻页效果") { startActivity(Intent(this, Function4Activity::class.java)) } mAdapter.addData(function4) val function5 = FunctionBean("圆角Drawable") { startActivity(Intent(this, Function5Activity::class.java)) } mAdapter.addData(function5) val function7 = FunctionBean("分组列表") { startActivity(Intent(this, Function7Activity::class.java)) } mAdapter.addData(function7) val function8 = FunctionBean("画") { startActivity(Intent(this, Function8Activity::class.java)) } mAdapter.addData(function8) val function9 = FunctionBean("点击跟踪") { startActivity(Intent(this, Function9Activity::class.java)) } mAdapter.addData(function9) val function10 = FunctionBean("测试") { startActivity(Intent(this, Function10Activity::class.java)) } mAdapter.addData(function10) val function11 = FunctionBean("DiffUtils") { startActivity(Intent(this, Function11Activity::class.java)) } mAdapter.addData(function11) val function12 = FunctionBean("折叠布局") { startActivity(Intent(this, Function12Activity::class.java)) } mAdapter.addData(function12) val function6 = FunctionBean("铁汁") { startActivity(Intent(this, Function6Activity::class.java)) } mAdapter.addData(function6) val function13 = FunctionBean("LayoutManager") { startActivity(Intent(this, Function13Activity::class.java)) } mAdapter.addData(function13) val function15 = FunctionBean("LayoutManager2") { startActivity(Intent(this, Function15Activity::class.java)) } mAdapter.addData(function15) // Log.v("zwp", "Acname:" + Thread.currentThread().name + "/id:" + Thread.currentThread().id) // val function10 = FunctionBean("Service测试") { // bindService(Intent(this,MainService::class.java),this,0) // } // mAdapter.addData(function10) // lastCustomNonConfigurationInstance?.let{ // Log.v("zwp",it.toString()) // } } // // private fun createIntentSender(): IntentSender { // val intent = Intent(this, MainActivity::class.java).apply { // action = ACTION_INSTALL // } // val pending = PendingIntent.getActivity(this, 0, intent, 0) // return pending.intentSender // } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { TODO("Not yet implemented") } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } override fun onRetainCustomNonConfigurationInstance(): Any { return "my name is lastConfiguration" } override fun onResume() { LogV("onResume") super.onResume() } override fun onStop() { super.onStop() } override fun onDestroy() { LogV("onDestroy") super.onDestroy() } }
0
Kotlin
0
0
ed2776a9cf736624fb9c7357c8ff321cb6503044
5,985
practice
Apache License 2.0
core/src/main/kotlin/io/holunda/connector/decide/DecideFunction.kt
holunda-io
630,812,028
false
null
package io.holunda.connector.decide import com.fasterxml.jackson.databind.* import io.camunda.connector.api.annotation.* import io.camunda.connector.api.error.* import io.camunda.connector.api.outbound.* import io.holunda.connector.common.* import io.holunda.connector.decide.DecisionOutputType.* import io.holunda.connector.generic.* import org.slf4j.* import java.util.* @OutboundConnector( name = "gpt-decide", inputVariables = ["inputJson", "instructions", "outputType", "possibleValues", "model", "apiKey"], type = "gpt-decide" ) class DecideFunction : OutboundConnectorFunction { @Throws(Exception::class) override fun execute(context: OutboundConnectorContext): Any { LOG.info("Executing DecideFunction") val request = context.variables.readFromJson<DecideRequest>() LOG.info("Request: {}", request) context.validate(request) context.replaceSecrets(request) return executeConnector(request) } private fun executeConnector(request: DecideRequest): DecideResult { val result = LLMServiceClient.run("decide", DecideTask( request.model.modelId, request.inputJson, request.instructions, request.outputType.name.lowercase(), request.possibleValues ) ) LOG.info("DecideFunction result: $result") return DecideResult(result) } data class DecideTask( val model: String, val context: JsonNode, val instructions: String, val output_type: String, val possible_values: List<Any>? ) companion object { private val LOG = LoggerFactory.getLogger(DecideFunction::class.java) } }
17
null
0
11
636aa37afaf33e092fde968d7875a23f9cd0b6db
1,617
camunda-8-connector-gpt
Apache License 2.0
src/main/java/com/internshala/indiexhackathon/MainActivity.kt
devrs8123
746,165,829
false
{"Kotlin": 22902}
package com.internshala.indiexhackathon import android.animation.ObjectAnimator import android.content.Intent import android.graphics.drawable.AnimationDrawable import android.net.Uri import android.os.Bundle import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import android.view.View import android.view.animation.AnimationUtils import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var btnStartVoiceRecognition: Button private lateinit var textViewChat: TextView private lateinit var speechRecognizer: SpeechRecognizer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnStartVoiceRecognition = findViewById(R.id.btnStartVoiceRecognition) textViewChat = findViewById(R.id.textViewChat) btnStartVoiceRecognition.setOnClickListener { startVoiceRecognition() startButtonAnimation() // Start the rotation animation } setupSpeechRecognizer() } private fun startButtonAnimation() { // Rotate the button 360 degrees on the Y-axis val rotationAnimator = ObjectAnimator.ofFloat(btnStartVoiceRecognition, View.ROTATION_Y, 0f, 360f) rotationAnimator.duration = 1000 // Animation duration in milliseconds rotationAnimator.start() } private fun startVoiceRecognition() { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US") try { speechRecognizer.startListening(intent) } catch (e: Exception) { // Handle exception e.printStackTrace() } } private fun setupSpeechRecognizer() { speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this) speechRecognizer.setRecognitionListener(object : RecognitionListener { override fun onReadyForSpeech(params: Bundle?) {} override fun onBeginningOfSpeech() {} override fun onRmsChanged(rmsdB: Float) {} override fun onBufferReceived(buffer: ByteArray?) {} override fun onEndOfSpeech() {} override fun onError(error: Int) {} override fun onResults(results: Bundle?) { val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) if (!matches.isNullOrEmpty()) { val spokenText = matches[0] checkPronunciation(spokenText) } } override fun onPartialResults(partialResults: Bundle?) {} override fun onEvent(eventType: Int, params: Bundle?) {} }) } private fun checkPronunciation(spokenText: String) { val pronunciationDictionary = mapOf( "example" to "example", "apple" to "apple", "banana" to "banana", "elephant" to "elephant", "giraffe" to "giraffe", "chocolate" to "chocolate", "algorithm" to "algorithm", "happiness" to "happiness", "technology" to "technology", "communication" to "communication", "abandon" to "abandon", "ability" to "ability", "absolutely" to "absolutely", "accumulate" to "accumulate", "acknowledge" to "acknowledge", "adventure" to "adventure", "advocate" to "advocate", "affection" to "affection", "aggregate" to "aggregate", "alleviate" to "alleviate", "beautiful" to "beautiful", "benevolent" to "benevolent", "caterpillar" to "caterpillar", "celestial" to "celestial", "challenge" to "challenge", "compassion" to "compassion", "delicate" to "delicate", "effervescent" to "effervescent", "eloquent" to "eloquent", "fantastic" to "fantastic", "gratitude" to "gratitude", "harmony" to "harmony", "illuminate" to "illuminate", "imagination" to "imagination", "infinite" to "infinite", "jubilant" to "jubilant", "kaleidoscope" to "kaleidoscope", "luminous" to "luminous", "magnificent" to "magnificent", "nurturing" to "nurturing", "optimistic" to "optimistic", "paradise" to "paradise", "quintessential" to "quintessential", "resplendent" to "resplendent", "serendipity" to "serendipity", "tranquil" to "tranquil", "umbrella" to "umbrella", "vibrant" to "vibrant", "wonderful" to "wonderful", "xylophone" to "xylophone", "yesterday" to "yesterday", "zeppelin" to "zeppelin", "ambitious" to "ambitious", "bewilder" to "bewilder", "captivate" to "captivate", "dexterity" to "dexterity", "effulgent" to "effulgent", "felicitous" to "felicitous", "gargantuan" to "gargantuan", "higgledy-piggledy" to "higgledy-piggledy", "incandescent" to "incandescent", "juxtapose" to "juxtapose", "kaleidoscopic" to "kaleidoscopic", "labyrinthine" to "labyrinthine", "mellifluous" to "mellifluous", "nostalgia" to "nostalgia", "oblivion" to "oblivion", "peregrination" to "peregrination", "quizzical" to "quizzical", "recumbentibus" to "recumbentibus", "serendipitous" to "serendipitous", "tintinnabulation" to "tintinnabulation", "ubiquitous" to "ubiquitous", "verisimilitude" to "verisimilitude", "wherewithal" to "wherewithal", "xenodochial" to "xenodochial", "yonderly" to "yonderly", "zeitgeist" to "zeitgeist", // Additional Common Words "hello" to "hello", "goodbye" to "goodbye", "please" to "please", "thank you" to "thank you", "sorry" to "sorry", "yes" to "yes", "no" to "no", "excuse me" to "excuse me", "sorry" to "sorry", "pardon" to "pardon", "ok" to "ok", "fine" to "fine", "help" to "help", "thanks" to "thanks", "bye" to "bye", "nice" to "nice", "love" to "love", "friend" to "friend", "family" to "family", "home" to "home", "work" to "work", "play" to "play", "eat" to "eat", "drink" to "drink", "sleep" to "sleep", "happy" to "happy", "sad" to "sad", "angry" to "angry", "funny" to "funny", "serious" to "serious", "crazy" to "crazy", "cool" to "cool", "hot" to "hot", "cold" to "cold", "fast" to "fast", "slow" to "slow", "big" to "big", "small" to "small", "old" to "old", "new" to "new", "high" to "high", "low" to "low", "rich" to "rich", "poor" to "poor", "happy" to "happy", "sad" to "sad", "angry" to "angry", "love" to "love", "hate" to "hate", "beautiful" to "beautiful", "ugly" to "ugly", "clean" to "clean", "dirty" to "dirty", "easy" to "easy", "difficult" to "difficult", "cheap" to "cheap", "expensive" to "expensive", "old" to "old", "young" to "young", "long" to "long", "short" to "short", "near" to "near", "far" to "far", "right" to "right", "left" to "left", "good" to "good", "bad" to "bad", "happy" to "happy", "sad" to "sad", "angry" to "angry", "love" to "love", "hate" to "hate", "fast" to "fast", "slow" to "slow", "hot" to "hot", "cold" to "cold", "strong" to "strong", "weak" to "weak", "thick" to "thick", "thin" to "thin", "deep" to "deep", "shallow" to "shallow", "dark" to "dark", "light" to "light", "noisy" to "noisy", "quiet" to "quiet", "empty" to "empty", "full" to "full", "hard" to "hard", "soft" to "soft", "clean" to "clean", "dirty" to "dirty", "wet" to "wet", "dry" to "dry", "smooth" to "smooth", "rough" to "rough", "sweet" to "sweet", "sour" to "sour", "bitter" to "bitter", "spicy" to "spicy", "tasty" to "tasty", "delicious" to "delicious", "fresh" to "fresh", "stale" to "stale", "healthy" to "healthy", "unhealthy" to "unhealthy", "happy" to "happy", "sad" to "sad", "angry" to "angry", "love" to "love", "hate" to "hate", "alive" to "alive", "dead" to "dead", "right" to "right", "wrong" to "wrong", "true" to "true", "false" to "false", "open" to "open", "closed" to "closed", "begin" to "begin", "end" to "end", "start" to "start", "stop" to "stop", "win" to "win", "lose" to "lose", "pass" to "pass", "fail" to "fail", "create" to "create", "destroy" to "destroy", "build" to "build", "break" to "break", "buy" to "buy", "sell" to "sell", "find" to "find", "lose" to "lose", "give" to "give", "take" to "take", "enter" to "enter", "exit" to "exit", "win" to "win", "lose" to "lose", "help" to "help", "hurt" to "hurt", "arrive" to "arrive", "leave" to "leave", "remember" to "remember", "forget" to "forget", "speak" to "speak", "listen" to "listen", "read" to "read", "write" to "write", "learn" to "learn", "teach" to "teach", "understand" to "understand", "confuse" to "confuse", "win" to "win", "lose" to "lose", "wait" to "wait", "hurry" to "hurry", "begin" to "begin", "end" to "end", "start" to "start", "stop" to "stop", "like" to "like", "dislike" to "dislike", "enjoy" to "enjoy", "suffer" to "suffer", "laugh" to "laugh", "cry" to "cry", "smile" to "smile", "frown" to "frown", "live" to "live", "die" to "die", "hope" to "hope", "fear" to "fear", "dream" to "dream", "wake up" to "wake up", "sleep" to "sleep", "work" to "work", "rest" to "rest", "play" to "play", "study" to "study", "travel" to "travel", "stay" to "stay", "move" to "move", "talk" to "talk", "silent" to "silent", "see" to "see", "blind" to "blind", "thank you" to "thank you", "understand" to "understand", "happy birthday" to "happy birthday", "congratulations" to "congratulations", "good morning" to "good morning", "good afternoon" to "good afternoon", "good evening" to "good evening", "good night" to "good night", "how are you?" to "how are you?", "I'm fine, thank you" to "I'm fine, thank you", "what's your name?" to "what's your name?", "I love coding." to "I love coding.", "The sun is shining." to "The sun is shining.", "I enjoy reading books." to "I enjoy reading books.", "Life is beautiful." to "Life is beautiful.", "Let's go for a walk." to "Let's go for a walk.", "I'm feeling great today." to "I'm feeling great today.", "It's a lovely day." to "It's a lovely day.", "Can you help me, please?" to "Can you help me, please?", "What's for dinner?" to "What's for dinner?", // Add more words and their correct pronunciations here ) val bestMatch = findBestMatch(spokenText, pronunciationDictionary) if (bestMatch != null) { updateChat("Bot: Pronunciation of '${bestMatch.first}' is correct!") playSparkleAnimation() } else { updateChat("Bot: Pronunciation needs improvement. Try again!") } } private fun findBestMatch(spokenText: String, pronunciationDictionary: Map<String, String>): Pair<String, Double>? { var bestMatch: Pair<String, Double>? = null for ((word, correctPronunciation) in pronunciationDictionary) { val similarity = calculateSimilarity(spokenText, correctPronunciation) println("Word: $word, Similarity: $similarity") if (bestMatch == null || similarity > bestMatch.second) { bestMatch = Pair(word, similarity) } } // Adjust the threshold based on your requirements return if (bestMatch?.second ?: 0.0 >= 0.7) bestMatch else null } private fun playSparkleAnimation() { val sparkleAnimation = AnimationUtils.loadAnimation(this, R.anim.sparkle_animation) textViewChat.startAnimation(sparkleAnimation) } private fun calculateSimilarity(text1: String, text2: String): Double { val maxLength = maxOf(text1.length, text2.length) val editDistance = LevenshteinDistance.calculate(text1, text2) // Use a similarity ratio based on the length of the strings val similarity = 1.0 - (editDistance.toDouble() / maxLength.toDouble()) return similarity } object LevenshteinDistance { fun calculate(s1: String, s2: String): Int { val m = s1.length val n = s2.length val d = Array(m + 1) { IntArray(n + 1) } for (i in 0..m) { for (j in 0..n) { if (i == 0) { d[i][j] = j } else if (j == 0) { d[i][j] = i } else { d[i][j] = minOf( d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + if (s1[i - 1] == s2[j - 1]) 0 else 1 ) } } } return d[m][n] } } private fun updateChat(message: String) { textViewChat.text = message } // Override onDestroy to release SpeechRecognizer override fun onDestroy() { super.onDestroy() speechRecognizer.destroy() } fun openLink(view: View) { // Specify the URL you want to open val url = "https://www.duolingo.com/" // Create an Intent with the ACTION_VIEW action and the URL val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) // Start the activity with the intent startActivity(intent) } }
0
Kotlin
0
0
3f0205539196122d21aa8bedff65b66e846726a2
16,412
Indie-Code-X-AI-Hackathon
Apache License 2.0
neutrino/src/commonMain/kotlin/io/github/kleinstein/neutrino/DI.kt
Klein-Stein
486,564,264
false
{"Kotlin": 30072, "Ruby": 1599}
package io.github.kleinstein.neutrino import io.github.kleinstein.neutrino.fabrics.Provider import io.github.kleinstein.neutrino.contracts.* import io.github.kleinstein.neutrino.exceptions.NeutrinoException import io.github.kleinstein.neutrino.fabrics.Singleton import io.github.kleinstein.neutrino.references.Weak import kotlin.native.concurrent.ThreadLocal import kotlin.reflect.typeOf /** * DI container interface */ interface DI: IResolvable, IBuildable<DI>, Collection<IModule> { /** * Attaches a new module to the DI container * * @param child [IModule] instance */ fun attach(child: IModule) /** * Attaches a collection of modules to the DI container * * @param children A collection of children */ fun attachAll(vararg children: IModule) /** * Checks if the DI container contains a module with the passed name * * @param name Module name * @return Boolean result */ fun contains(name: String): Boolean /** * Detaches an existing module from the DI container * * @param name Module name * @return Module or `null` if the module doesn't exist */ fun detach(name: String): IModule? /** * Returns an attached module by name * * @param name Module name * @return An attached [IModule]'s instance or throws [an exception][NeutrinoException] */ operator fun get(name: String): IModule @ThreadLocal companion object { /** * A global instance of [DI container][DI], use this instance to attach injectors */ val global: DI = NeutrinoDI {} /** * Creates a new module without calling the [IModule.build] method * * @param name Module name * @param body Initialization block of dependencies (optional) * @return New module */ fun module(name: String, body: (IModule.() -> Unit)? = null): IModule = Module(name, body) } } /** * Adds a new fabric to the module * * @param fabric An instance of the [IFabric] implementation */ inline fun <reified T: Any> IModule.addFabric(fabric: IFabric<T>) = addFabric(Key(type = typeOf<T>()), fabric) /** * Adds a fabric to the [module][IModule] as the singleton fabric * * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.singleton(noinline fabric: () -> T) { this.addFabric(Singleton(fabric)) } /** * Adds a fabric to the [module][IModule] as the singleton fabric * * @param tag Fabric tag * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.singleton(tag: String, noinline fabric: () -> T) { this.addFabric(Key( type = typeOf<T>(), tag = tag, ), Singleton(fabric)) } /** * Adds a fabric to the [module][IModule] as the weak singleton fabric * * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.weakSingleton(noinline fabric: () -> T) { this.addFabric(Singleton<Weak<T>> { Weak(fabric()) }) } /** * Adds a fabric to the [module][IModule] as the weak singleton fabric * * @param tag Fabric tag * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.weakSingleton(tag: String, noinline fabric: () -> T) { this.addFabric(Key( type = typeOf<Weak<T>>(), tag = tag, ), Singleton { Weak(fabric()) }) } /** * Adds a fabric to the [module][IModule] as the provider fabric * * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.provider(noinline fabric: () -> T) { this.addFabric(Provider(fabric)) } /** * Adds a fabric to the [module][IModule] as the provider fabric * * @param tag Fabric tag * @param fabric Dependency fabric */ inline fun <reified T: Any> IModule.provider(tag: String, noinline fabric: () -> T) { this.addFabric(Key( type = typeOf<T>(), tag = tag, ), Provider(fabric)) } /** * Returns a child from the container by the passed tag * * @param T Child type * @param tag Child tag * @return Resolved child or throws [an exception][NeutrinoException] */ inline fun <reified T: Any> IResolvable.resolve(tag: String): T = resolve(typeOf<T>(), tag) /** * Returns a child from the container * * @param T Child type * @return Resolved child or throws [an exception][NeutrinoException] */ inline fun <reified T: Any> IResolvable.resolve(): T = resolve(typeOf<T>()) /** * Lazy returns a child from the container by the passed tag * * @param T Child type * @param tag Child tag * @return Lazy resolved child or throws [an exception][NeutrinoException] */ inline fun <reified T: Any> IResolvable.resolveLazy(tag: String): Lazy<T> = resolveLazy(typeOf<T>(), tag) /** * Lazy returns a child from the container by the passed tag * * @param T Child type * @return Lazy resolved child or throws [an exception][NeutrinoException] */ inline fun <reified T: Any> IResolvable.resolveLazy(): Lazy<T> = resolveLazy(typeOf<T>())
0
Kotlin
0
0
7b9c2f0b26bf89aaaf6f0cc169f9e0afff0a694c
5,009
neutrino
MIT License
feature/monster-registration/android/src/main/kotlin/br/alexandregpereira/hunter/monster/registration/ui/form/MonsterStatsForm.kt
alexandregpereira
347,857,709
false
{"Kotlin": 1267769, "Swift": 74314, "Shell": 139}
package br.alexandregpereira.hunter.monster.registration.ui.form import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import br.alexandregpereira.hunter.domain.model.Monster import br.alexandregpereira.hunter.monster.registration.R import br.alexandregpereira.hunter.ui.compose.Form import br.alexandregpereira.hunter.ui.compose.FormField @Composable internal fun MonsterStatsForm( monster: Monster, modifier: Modifier = Modifier, onMonsterChanged: (Monster) -> Unit = {} ) { Form( modifier = modifier, title = stringResource(R.string.monster_registration_stats), formFields = listOf( FormField.Number( key = "armorClass", label = stringResource(R.string.monster_registration_armor_class), value = monster.stats.armorClass, ), FormField.Number( key = "hitPoints", label = stringResource(R.string.monster_registration_hit_points), value = monster.stats.hitPoints, ), FormField.Text( key = "hitDice", label = stringResource(R.string.monster_registration_hit_dice), value = monster.stats.hitDice, ), ), onFormChanged = { field -> when (field.key) { "armorClass" -> onMonsterChanged( monster.copy( stats = monster.stats.copy( armorClass = field.intValue ) ) ) "hitPoints" -> onMonsterChanged( monster.copy( stats = monster.stats.copy( hitPoints = field.intValue ) ) ) "hitDice" -> onMonsterChanged( monster.copy(stats = monster.stats.copy(hitDice = field.stringValue)) ) } }, ) }
7
Kotlin
4
79
ba86ff4c03c723403eeaca6bd567b7389c40cae1
2,107
Monster-Compendium
Apache License 2.0
app/src/main/java/com/suda/yzune/wakeupschedule/course_add/SelectWeekFragment.kt
dongguayaya
165,588,699
true
{"Kotlin": 453481, "Java": 215}
package com.suda.yzune.wakeupschedule.course_add import android.os.Bundle import android.view.* import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.suda.yzune.wakeupschedule.R import es.dmoral.toasty.Toasty import kotlinx.android.synthetic.main.fragment_select_week.* import org.jetbrains.anko.support.v4.dip class SelectWeekFragment : DialogFragment() { var position = -1 private lateinit var viewModel: AddCourseViewModel private val liveData = MutableLiveData<ArrayList<Int>>() private val result = ArrayList<Int>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { position = it.getInt("position") } viewModel = ViewModelProviders.of(activity!!).get(AddCourseViewModel::class.java) liveData.observe(this, Observer { if (it?.size == viewModel.maxWeek) { tv_all.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.white)) tv_all.background = ContextCompat.getDrawable(context!!, R.drawable.select_textview_bg) } if (it?.size != viewModel.maxWeek) { tv_all.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.black)) tv_all.background = null } val flag = viewModel.judgeType(it!!, viewModel.maxWeek) if (flag == 1) { tv_type1.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.white)) tv_type1.background = ContextCompat.getDrawable(context!!, R.drawable.select_textview_bg) } if (flag != 1) { tv_type1.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.black)) tv_type1.background = null } if (flag == 2) { tv_type2.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.white)) tv_type2.background = ContextCompat.getDrawable(context!!, R.drawable.select_textview_bg) } if (flag != 2) { tv_type2.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.black)) tv_type2.background = null } }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return inflater.inflate(R.layout.fragment_select_week, container, false) } override fun onResume() { super.onResume() liveData.value = viewModel.editList[position].weekList.value result.addAll(liveData.value!!) showWeeks() initEvent() } private fun showWeeks() { ll_week.removeAllViews() val context = ll_week.context val margin = dip(4) val textViewSize = dip(32) val llHeight = dip(40) for (i in 0 until Math.ceil(viewModel.maxWeek / 6.0).toInt()) { val linearLayout = LinearLayout(context) linearLayout.orientation = LinearLayout.HORIZONTAL ll_week.addView(linearLayout) val params = linearLayout.layoutParams params.width = ViewGroup.LayoutParams.MATCH_PARENT params.height = llHeight linearLayout.layoutParams = params for (j in 0..5) { val week = i * 6 + j + 1 if (week > viewModel.maxWeek) { break } val textView = TextView(context) val textParams = LinearLayout.LayoutParams(textViewSize, textViewSize) textParams.setMargins(margin, margin, margin, margin) textView.layoutParams = textParams textView.text = "$week" textView.gravity = Gravity.CENTER if (week in result) { textView.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.white)) textView.background = ContextCompat.getDrawable(context, R.drawable.week_selected_bg) } else { textView.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.black)) textView.background = null } textView.setOnClickListener { if (textView.background == null) { result.add(week) liveData.value = result textView.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.white)) textView.background = ContextCompat.getDrawable(context, R.drawable.week_selected_bg) } else { result.remove(week) liveData.value = result textView.setTextColor(ContextCompat.getColor(activity!!.applicationContext, R.color.black)) textView.background = null } } textView.setLines(1) linearLayout.addView(textView) //selections[week - 1] = textView } } } private fun initEvent() { tv_all.setOnClickListener { if (tv_all.background == null) { result.clear() for (i in 1..viewModel.maxWeek) { result.add(i) } showWeeks() liveData.value = result } else { result.clear() showWeeks() liveData.value = result } } tv_type1.setOnClickListener { if (tv_type1.background == null) { result.clear() for (i in 1..viewModel.maxWeek step 2) { result.add(i) } showWeeks() liveData.value = result } } tv_type2.setOnClickListener { if (tv_type2.background == null) { result.clear() for (i in 2..viewModel.maxWeek step 2) { result.add(i) } showWeeks() liveData.value = result } } btn_cancel.setOnClickListener { dismiss() } btn_save.setOnClickListener { if (result.size == 0){ Toasty.error(context!!.applicationContext, "请至少选择一周").show() } else{ viewModel.editList[position].weekList.value = result dismiss() } } } companion object { @JvmStatic fun newInstance(arg: Int) = SelectWeekFragment().apply { arguments = Bundle().apply { putInt("position", arg) } } } }
0
Kotlin
0
0
ed0770170f1eea7af4a46e3a53a574ef59b0f9c0
7,308
WakeupSchedule_Kotlin
Apache License 2.0
src/main/kotlin/com/projectcitybuild/repositories/WarpRepository.kt
projectcitybuild
42,997,941
false
null
package com.projectcitybuild.repositories import com.projectcitybuild.entities.SerializableLocation import com.projectcitybuild.entities.Warp import com.projectcitybuild.modules.database.DataSource class WarpRepository( private val dataSource: DataSource, ) { private val nameCache: MutableList<String> = mutableListOf() private var hasBuiltNameCache = false fun exists(name: String): Boolean { return first(name) != null } fun first(name: String): Warp? { return dataSource.database() .getFirstRow("SELECT * FROM `warps` WHERE `name`= ? LIMIT 1", name) ?.let { row -> Warp( name = row.get("name"), location = SerializableLocation( worldName = row.get("world_name"), x = row.get("x"), y = row.get("y"), z = row.get("z"), pitch = row.get("pitch"), yaw = row.get("yaw"), ), createdAt = row.get("created_at"), ) } } fun names(): List<String> { if (hasBuiltNameCache) { return nameCache } return dataSource.database() .getResults("SELECT `name` FROM `warps` ORDER BY `name` ASC") .map { row -> row.getString("name") } .also { warpNames -> nameCache.addAll(warpNames) nameCache.sort() hasBuiltNameCache = true } } fun all(): List<Warp> { return dataSource.database() .getResults("SELECT * FROM `warps` ORDER BY `name` ASC") .map { row -> Warp( name = row.get("name"), location = SerializableLocation( worldName = row.get("world_name"), x = row.get("x"), y = row.get("y"), z = row.get("z"), pitch = row.get("pitch"), yaw = row.get("yaw"), ), createdAt = row.get("created_at"), ) } .also { nameCache.clear() nameCache.addAll(it.map { warp -> warp.name }) nameCache.sort() hasBuiltNameCache = true } } fun add(warp: Warp) { dataSource.database().executeInsert( "INSERT INTO `warps` VALUES (?, ?, ?, ?, ?, ?, ?, ?)", warp.name, warp.location.worldName, warp.location.x, warp.location.y, warp.location.z, warp.location.pitch, warp.location.yaw, warp.createdAt, ) nameCache.clear() hasBuiltNameCache = false } fun delete(name: String) { dataSource.database() .executeUpdate("DELETE FROM `warps` WHERE `name`= ?", name) nameCache.remove(name) } fun flush() { nameCache.clear() hasBuiltNameCache = false } }
9
Kotlin
0
3
36a7197d870aa24a9b9ea65567a35fa38f86a31d
3,186
PCBridge
MIT License
app/src/main/java/com/qlang/eyepetizer/bean/TabTitleInfo.kt
qlang122
309,645,125
false
null
package com.qlang.eyepetizer.bean data class TabTitleInfo(var name: String, var tag: Int = -1, var pageUrl: String? = null) { }
1
null
3
2
3eefe4b5734aeb58994ff1af7a1850c7b7740e64
128
EyepetizerTv
Apache License 2.0
app/src/main/java/com/flixclusive/common/UiText.kt
rhenwinch
659,237,375
false
null
package com.flixclusive.core.util.common.ui import android.content.Context import androidx.annotation.StringRes import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource sealed class UiText { data class StringValue(val str: String) : UiText() class StringResource( @StringRes val stringId: Int, vararg val args: Any, ) : UiText() fun asString(context: Context): String { return when (this) { is StringValue -> str is StringResource -> context.getString(stringId, *args) } } @Composable fun asString(): String { return when (this) { is StringValue -> str is StringResource -> stringResource(id = stringId, formatArgs = args) } } }
24
null
9
96
a90215b8c40ac0675cd217b38b842d2d57c90acc
793
Flixclusive
MIT License
libraries/scripting/common/src/kotlin/script/experimental/api/scriptData.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ @file:Suppress("unused") package kotlin.script.experimental.api import java.net.URL interface ScriptSource { val location: URL? val text: String? data class Position(val line: Int, val col: Int, val absolutePos: Int? = null) data class Range(val start: Position, val end: Position) data class Location(val start: Position, val end: Position? = null) } data class ScriptSourceNamedFragment(val name: String?, val range: ScriptSource.Range) enum class ScriptBodyTarget { Constructor, SingleAbstractMethod } data class ResolvingRestrictionRule( val action: Action, val pattern: String // FQN wildcard ) { enum class Action { Allow, Deny } } interface ScriptDependency { // Q: anything generic here? }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
935
kotlin
Apache License 2.0
app/src/main/java/net/odiak/granite/EditActivity.kt
odiak
456,617,511
false
{"Kotlin": 66770}
package net.odiak.granite import android.content.ContentResolver import android.net.Uri import android.os.Bundle import android.os.ParcelFileDescriptor import android.provider.DocumentsContract import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.setContent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.whenStarted import kotlinx.coroutines.* import net.odiak.granite.ui.theme.GraniteTheme import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.parser.MarkdownParser import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileOutputStream class EditActivity : ComponentActivity() { companion object { const val EXTRA_URI = "URI" const val EXTRA_NAME = "NAME" } private val name by lazy { intent.getStringExtra(EXTRA_NAME)!! } private val uri by lazy { intent.getStringExtra(EXTRA_URI)!! } private val root by lazy { DocumentFile.fromTreeUri( this, Uri.parse(uri) )!! } private val pref by lazy { GranitePreference(this) } private val recentFiles = mutableStateOf(emptyList<SimpleFile>()) private val currentFile = mutableStateOf<SimpleFile?>(null) private val tree = mutableStateOf<ASTNode?>(null) private val src = mutableStateOf("") private val editingNode = mutableStateOf<ASTNode?>(null) private val editingText = mutableStateOf(TextFieldValue()) private val parser = MarkdownParser(GFMWithWikiLinkFlavourDescriptor()) private val drawerState = DrawerState(DrawerValue.Open) @OptIn(DelicateCoroutinesApi::class, androidx.compose.runtime.ExperimentalComposeApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val scope = rememberCoroutineScope() val fr = remember { FocusRequester() } LaunchedEffect(currentFile.value) { if (currentFile.value != null || pref.fetchLastOpened()?.uri != uri) { pref.updateLastOpened(LastOpened(uri = uri, name = currentFile.value?.name)) } } LaunchedEffect(editingNode.value) { val text = editingNode.value?.getTextInNode(src.value)?.toString() ?: "" editingText.value = editingText.value.copy(text = text, selection = TextRange(text.length)) if (editingNode.value != null) { fr.requestFocus() } } LaunchedEffect(recentFiles.value) block@{ if (currentFile.value != null || recentFiles.value.isEmpty()) return@block val lastOpenedName = pref.fetchLastOpened()?.name ?: return@block val file = recentFiles.value.find { it.name == lastOpenedName } ?: return@block openFile(file) scope.launch { drawerState.close() } } BackHandler(enabled = drawerState.isOpen) { scope.launch { drawerState.close() } } GraniteTheme { ModalDrawer( drawerState = drawerState, drawerContent = { DrawerContent( recentFiles.value, onSelected = { file -> openFile(file) scope.launch { drawerState.close() } }) }) { Surface( color = MaterialTheme.colors.surface, contentColor = MaterialTheme.colors.onSurface ) { Column { TopAppBar( navigationIcon = { IconButton(onClick = { scope.launch { drawerState.open() } }) { Icon(Icons.Filled.Menu, contentDescription = "open menu") } }, title = { Text(text = currentFile.value?.name ?: "Granite") }) Surface( color = MaterialTheme.colors.surface, contentColor = MaterialTheme.colors.onSurface, shape = MaterialTheme.shapes.medium ) { LazyColumn { tree.value?.let { items(it.children) { node -> if (node === editingNode.value) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp), horizontalArrangement = Arrangement.End ) { EditingActionButton( onClick = { editingNode.value = null }, text = "Cancel" ) Spacer(modifier = Modifier.width(10.dp)) EditingActionButton( onClick = { saveEditing() }, text = "Done" ) } TextField( modifier = Modifier .fillMaxWidth() .focusRequester(fr), value = editingText.value, onValueChange = { editingText.value = it } ) } else { TopLevelBlock( src = src.value, node = node, onClick = { editingNode.value = node }, onChangeCheckbox = if (editingNode.value == null) ::saveCheckboxChange else null ) } } } } } } } } } } } override fun onResume() { super.onResume() updateRecentFiles() } @OptIn(DelicateCoroutinesApi::class) private fun updateRecentFiles() { GlobalScope.launch(Dispatchers.IO) { whenStarted { recentFiles.value = getRecentFiles(contentResolver, root.uri) .sortedByDescending { it.lastModified } .take(100) .toList() } } } private fun openFile(file: SimpleFile) { currentFile.value = file contentResolver.openFileDescriptor(file.uri, "r")!!.use { desc -> FileInputStream(desc.fileDescriptor).bufferedReader().use { reader -> val s = reader.readText() tree.value = parser.buildMarkdownTreeFromString(s) src.value = s } } } private fun saveEditing() { val children = tree.value?.children ?: return val file = currentFile.value ?: return val newSrc = children.joinToString("") { if (it == editingNode.value) editingText.value.text else it.getTextInNode(src.value) } save(newSrc, file) } private fun save(newSrc: String, file: SimpleFile) { contentResolver.openFileDescriptorForWriting(file.uri)!!.use { desc -> FileOutputStream(desc.fileDescriptor).bufferedWriter().use { writer -> writer.write(newSrc) } } editingNode.value = null tree.value = parser.buildMarkdownTreeFromString(newSrc) src.value = newSrc } private fun saveCheckboxChange(node: ASTNode, checked: Boolean) { if (editingNode.value != null) return val file = currentFile.value ?: return val text = if (checked) "[x] " else "[ ] " val range = node.startOffset until node.endOffset val newSrc = src.value.replaceRange(range, text) save(newSrc, file) } } private data class SimpleFile(val uri: Uri, val name: String, val lastModified: Long) private fun getRecentFiles( resolver: ContentResolver, parent: Uri, parentName: String? = null ): Sequence<SimpleFile> { val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( parent, DocumentsContract.getDocumentId(parent) ) val cursor = resolver.query(childrenUri, null, null, null) ?: return emptySequence() return sequence { cursor.use { cur -> while (cur.moveToNext()) { val docId = cur.getString(cur.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)) val uri = DocumentsContract.buildDocumentUriUsingTree(parent, docId) val name = cur.getString(cur.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)) val fullName = if (parentName == null) name else "$parentName/$name" val mimeType = cur.getString(cur.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)) if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { yieldAll(getRecentFiles(resolver, uri, fullName)) } else if (fullName.endsWith(".md")) { val lm = cur.getLong(cur.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)) yield(SimpleFile(uri, fullName.removeSuffix(".md"), lm)) } } } } } @Composable private fun DrawerContent(recentFiles: List<SimpleFile>, onSelected: (SimpleFile) -> Unit) { Column { Text(fontSize = 20.sp, text = "Recent") LazyColumn { itemsIndexed(recentFiles) { i, file -> if (i != 0) Divider() Text( modifier = Modifier .fillMaxWidth() .clickable { onSelected(file) } .padding(10.dp), text = file.name ) } } } } private fun ContentResolver.openFileDescriptorForWriting(uri: Uri): ParcelFileDescriptor? = try { openFileDescriptor(uri, "wt") } catch (_: FileNotFoundException) { openFileDescriptor(uri, "w") } @Composable private fun EditingActionButton(onClick: () -> Unit, text: String) { Button( onClick = onClick, contentPadding = PaddingValues(horizontal = 6.dp, vertical = 4.dp) ) { Text(fontSize = 12.sp, text = text) } }
0
Kotlin
0
0
c45f9f55d98b3f0c9925c844481889547cbb5fee
12,956
granite-android
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/entities/Wallet.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.bankwallet.entities import android.os.Parcelable import io.horizontalsystems.bankwallet.modules.transactions.TransactionSource import io.horizontalsystems.marketkit.models.CoinType import io.horizontalsystems.marketkit.models.PlatformCoin import kotlinx.android.parcel.Parcelize import java.util.* @Parcelize data class Wallet( val configuredPlatformCoin: ConfiguredPlatformCoin, val account: Account ) : Parcelable { private val blockchain: TransactionSource.Blockchain get() = when (val coinType = coinType) { CoinType.Bitcoin -> TransactionSource.Blockchain.Bitcoin CoinType.BitcoinCash -> TransactionSource.Blockchain.BitcoinCash CoinType.Dash -> TransactionSource.Blockchain.Dash CoinType.Litecoin -> TransactionSource.Blockchain.Litecoin CoinType.Ethereum -> TransactionSource.Blockchain.Ethereum CoinType.BinanceSmartChain -> TransactionSource.Blockchain.BinanceSmartChain CoinType.Zcash -> TransactionSource.Blockchain.Zcash is CoinType.Bep2 -> TransactionSource.Blockchain.Bep2(coinType.symbol) is CoinType.Erc20 -> TransactionSource.Blockchain.Ethereum is CoinType.Bep20 -> TransactionSource.Blockchain.BinanceSmartChain is CoinType.ArbitrumOne, is CoinType.Avalanche, is CoinType.Fantom, is CoinType.HarmonyShard0, is CoinType.HuobiToken, is CoinType.Iotex, is CoinType.Moonriver, is CoinType.OkexChain, is CoinType.PolygonPos, is CoinType.Solana, is CoinType.Sora, is CoinType.Tomochain, is CoinType.Xdai, is CoinType.Unsupported -> throw IllegalArgumentException("Unsupported coin may not have transactions to show") } val platformCoin get() = configuredPlatformCoin.platformCoin val coinSettings get() = configuredPlatformCoin.coinSettings val coin get() = platformCoin.coin val platform get() = platformCoin.platform val coinType get() = platformCoin.coinType val decimal get() = platform.decimals val badge get() = when (coinType) { CoinType.Bitcoin, CoinType.Litecoin, -> coinSettings.derivation?.value?.uppercase() CoinType.BitcoinCash -> coinSettings.bitcoinCashCoinType?.value?.uppercase() else -> coinType.blockchainType } val transactionSource get() = TransactionSource(blockchain, account, coinSettings) constructor(platformCoin: PlatformCoin, account: Account) : this(ConfiguredPlatformCoin(platformCoin), account) override fun equals(other: Any?): Boolean { if (other is Wallet) { return configuredPlatformCoin == other.configuredPlatformCoin && account == other.account } return super.equals(other) } override fun hashCode(): Int { return Objects.hash(configuredPlatformCoin, account) } }
163
Kotlin
219
402
5ce20e6e4e0f75a76496051ba6f78312bc641a51
3,094
unstoppable-wallet-android
MIT License
chess-api/src/main/kotlin/pluto/chess/figure/StartPawn.kt
oliver2619
462,463,055
false
{"Kotlin": 214537}
package pluto.chess.figure import pluto.chess.board.* import pluto.chess.move.* import pluto.chess.move.DefaultMove import pluto.chess.move.PawnDoubleStepMove import pluto.chess.move.PawnNonCapturingMove internal class StartPawn(color: FigureColor, field: Field) : Pawn(color, field) { private val lineMoves: Array<Move> = arrayOf(PawnNonCapturingMove(color, field), PawnDoubleStepMove(color, field)) private val capturingMoves: Array<Move> = Masks.pawnAttack(field, color) .streamFields() .map { targetField -> PawnCapturingMove(color, field, targetField) } .toArray { arrayOfNulls<Move>(it) } override fun findMove(board: Board, targetField: Field, conversion: Conversion?): MoveWithBoard? { if (conversion != null) { return null } for (move in capturingMoves) { if (move.targetField == targetField) { if (move.isNotBlocked(board)) { val newBoard = board.moved(move) if (!newBoard.isKingAttacked(color)) { return MoveWithBoard(move, newBoard) } } return null } } for (move in lineMoves) { if (move.isNotBlocked(board)) { if (move.targetField == targetField) { val newBoard = board.moved(move) if (!newBoard.isKingAttacked(color)) { return MoveWithBoard(move, newBoard) } return null } } else { break } } return null } override fun getMoves(board: Board, consumer: MoveConsumer): MoveConsumerResult { var ret = MoveConsumerResult.CONTINUE_ALL for (move in capturingMoves) { if (move.isNotBlocked(board)) { val newBoard = board.moved(move) if (!newBoard.isKingAttacked(color)) { ret = ret combine consumer.move(move, newBoard) if (ret == MoveConsumerResult.CANCEL) { return ret } } } } if (ret != MoveConsumerResult.CONTINUE_ALL) { return ret } for (move in lineMoves) { if (move.isNotBlocked(board)) { val newBoard = board.moved(move) if (!newBoard.isKingAttacked(color)) { ret = ret combine consumer.move(move, newBoard) if (ret != MoveConsumerResult.CONTINUE_ALL) { return ret } } } else { break } } return ret } override fun getValueChangingMoves(board: Board, consumer: MoveConsumer): Boolean { for (move in capturingMoves) { if (move.isNotBlocked(board)) { val newBoard = board.moved(move) if (!newBoard.isKingAttacked(color)) { if (consumer.move(move, newBoard) == MoveConsumerResult.CANCEL) { return false } } } } return true } }
0
Kotlin
0
0
7826be4e8c2e811f74b47066b77d05546e03ccbc
3,289
chess
MIT License
library/src/main/java/com/mooveit/library/providers/definition/ChuckNorrisFactsProvider.kt
moove-it
79,579,060
false
null
package com.mooveit.library.providers.definition interface ChuckNorrisFactsProvider : Provider { fun fact(): String }
18
Kotlin
48
525
12b87899d62c5fa701141f8f98cb7265ab58bc15
123
fakeit
MIT License
lib/src/main/kotlin/com/lemonappdev/konsist/api/ext/list/KoModuleProviderListExt.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.api.ext.list import com.lemonappdev.konsist.api.provider.KoModuleProvider /** * List containing declarations with module. * * @param name The module name to include. * @param names The module name(s) to include. * @return A list containing declarations that reside in any of the specified modules. */ fun <T : KoModuleProvider> List<T>.withModule(name: String, vararg names: String): List<T> = filter { it.resideInModule(name) || names.any { module -> it.resideInModule(module) } } /** * List containing declarations without module. * * @param name The module name to exclude. * @param names The module name(s) to exclude. * @return A list containing declarations that don't reside in any of the specified modules. */ fun <T : KoModuleProvider> List<T>.withoutModule(name: String, vararg names: String): List<T> = filter { !it.resideInModule(name) && names.none { module -> it.resideInModule(module) } }
4
null
19
768
22f45504ab1c88fca8314bd86f91af7dd8a3672b
959
konsist
Apache License 2.0
common-app/src/main/java/de/rki/covpass/commonapp/uielements/CheckContextCheckboxElement.kt
Digitaler-Impfnachweis
376,239,258
false
null
/* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.commonapp.uielements import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.view.isVisible import de.rki.covpass.commonapp.databinding.CheckContextCheckboxBinding import kotlin.properties.Delegates public class CheckContextCheckboxElement @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : FrameLayout( context, attrs, defStyleAttr, ) { private val binding: CheckContextCheckboxBinding = CheckContextCheckboxBinding.inflate(LayoutInflater.from(context)) private var title: Int? by Delegates.observable(null) { _, _, newValue -> if (newValue != null) { binding.checkContextCheckboxElementTitle.setText(newValue) } binding.checkContextCheckboxElementTitle.isVisible = newValue != null } private var subtitle: Int? by Delegates.observable(null) { _, _, newValue -> if (newValue != null) { binding.checkContextCheckboxElementSubtitle.setText(newValue) } binding.checkContextCheckboxElementSubtitle.isVisible = newValue != null } private var isChecked: Boolean by Delegates.observable(false) { _, _, newValue -> binding.checkContextCheckboxElementCheckbox.isChecked = newValue } init { addView(binding.root) binding.root.layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } public fun updateValues(title: Int?, subtitle: Int?) { this.title = title this.subtitle = subtitle } public fun updateCheckbox(isChecked: Boolean) { this.isChecked = isChecked } @JvmName("isCheckboxChecked") public fun isChecked(): Boolean = binding.checkContextCheckboxElementCheckbox.isChecked }
47
null
62
185
7301f1500dab4a686aa40341500667cf4cc54d1e
2,036
covpass-android
Apache License 2.0
src/main/kotlin/com/rrvieir4/pickarr/services/clients/servarr/sonarr/models/Season.kt
rrvieira
413,513,263
false
{"Kotlin": 61434, "Dockerfile": 501, "Shell": 74}
package com.rrvieir4.pickarr.services.clients.servarr.sonarr.models data class Season( val seasonNumber: Int, val monitored: Boolean )
0
Kotlin
0
3
557eb2b9c06ec60062dbfd293ece3846fb5ff1b1
143
pickarr
MIT License
pet-kata/src/test/kotlin/com/example/pets/Exercise2.kt
mike-neck
323,036,209
false
null
package com.example.pets import com.example.pets.fixtures.PetDomain import com.example.pets.fixtures.assertAll import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.ints.shouldBeExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith /** * In this course, you will work with these functions. * * - [List.flatMap] * - [List.filter] * - [List.filterIndexed] * - [List.filterNot] * - [List.count] * - [List.find] * - [List.any] * - [List.all] * - [List.none] * - [List.distinct] */ @ExtendWith(PetDomain::class) class Exercise2 { @Test fun doAnyPeopleHaveCats(people: People) { // Replace { false } block, with a any function call on `People.items` val anySatisfy: Boolean = people { false } anySatisfy shouldBe true } @Test fun doAllPeopleHavePets(people: People) { // Replace { true } block, with a method call send to people that checks if all people have pets val allPeopleHavePets: Boolean = people { true } allPeopleHavePets shouldBe false } @Test fun howManyPeopleHaveCats(people: People) { // Replace { 100 } block, with a method call to count the number of people having cats. val countOfPeopleHavingCats: Int = people { 100 } countOfPeopleHavingCats shouldBeExactly 2 } @Test fun findMarySmith(people: People) { // Replace { Person() } block, with a method call on `people` to find '<NAME>' val person: Person = people { Person() } assertAll { test { person.firstName shouldBe "Mary" } test { person.lastName shouldBe "Smith" } } } @Test fun peopleWithPets(people: People) { // Replace { listOf } block, with a method call on `people` to find people owning pets val peopleWithPets: List<Person> = people { listOf() } peopleWithPets shouldHaveSize 7 } @Test fun allPetTypesOfAllPeople(people: People) { // Replace { setOf } block, with a method call on `people` of mapping to distinct `PetType`. val allPetTypes: Set<PetType> = people { setOf() } allPetTypes shouldBe setOf( PetType.CAT, PetType.DOG, PetType.TURTLE, PetType.HAMSTER, PetType.BIRD, PetType.SNAKE) } @Test fun firstNamesOfAllPeople(people: People) { // Transform people into a list of first names val firstNames: List<String> = people { listOf() } firstNames shouldBe listOf("Mary", "Bob", "Ted", "Jake", "Barry", "Terry", "Harry", "John") } }
2
Kotlin
1
5
8b90499d6e29c1d8e4a7459fc3f31e4b26afd0c3
2,502
kotlin-jvm-stdlib-kata
Apache License 2.0
app/src/main/java/com/example/android/codelabs/navigation/HomeFragment.kt
apsommer
273,306,001
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Proguard": 1, "XML": 34, "Kotlin": 6, "Java": 1}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.codelabs.navigation import android.os.Bundle import android.view.* import android.widget.Button import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.navOptions /** * Fragment used to show how to navigate to another destination */ class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.home_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // define animation for the transition between destinations val options = navOptions { anim { enter = R.anim.slide_in_right exit = R.anim.slide_out_left popEnter = R.anim.slide_in_left popExit = R.anim.slide_out_right } } // navigate directly to "one" using the NavController val button = view.findViewById<Button>(R.id.navigate_destination_button) button?.setOnClickListener { findNavController().navigate(R.id.flow_step_one_dest, null, options) // pass bundle with ... Navigation.createNavigateOnClickListener(int id, Bundle bundle) } // navigate from "one" to "two" using the "next action" defined in graph/one // navigating via actions is preferred as it allows the options to be defined in XML rather than programmatically // view.findViewById<Button>(R.id.navigate_action_button) // .setOnClickListener(Navigation.createNavigateOnClickListener(R.id.next_action, null)) // alternate method to navigate with action that uses generated Directions class val buttonD = view.findViewById<Button>(R.id.navigate_action_button) buttonD.setOnClickListener { val action = HomeFragmentDirections.nextAction(1) findNavController().navigate(action) } } // these fragment toolbar items are merged into existing activity toolbar items override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.main, menu) } }
1
null
1
1
5e1e427ce71af7cba34bcaca8aa07dccd51facb9
3,010
android-navigation
Apache License 2.0
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/components/smartCastProvider/AbstractHLSmartCastInfoTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 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.analysis.api.impl.base.test.components import org.jetbrains.kotlin.analysis.api.impl.barebone.test.FrontendApiTestConfiguratorService import org.jetbrains.kotlin.analysis.api.impl.barebone.test.expressionMarkerProvider import org.jetbrains.kotlin.analysis.api.impl.base.test.test.framework.AbstractHLApiSingleFileTest import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.model.TestModule import org.jetbrains.kotlin.test.services.TestServices import org.jetbrains.kotlin.test.services.assertions abstract class AbstractHLSmartCastInfoTest(configurator: FrontendApiTestConfiguratorService) : AbstractHLApiSingleFileTest(configurator) { override fun doTestByFileStructure(ktFile: KtFile, module: TestModule, testServices: TestServices) { super.doTestByFileStructure(ktFile, module, testServices) val expression = testServices.expressionMarkerProvider.getSelectedElement(ktFile) as KtExpression val actual = executeOnPooledThreadInReadAction { analyseForTest(expression) { val smartCastInfo = expression.getSmartCastInfo() buildString { appendLine("expression: ${expression.text}") appendLine("isStable: ${smartCastInfo?.isStable}") appendLine("smartCastType: ${smartCastInfo?.smartCastType?.render()}") } } } testServices.assertions.assertEqualsToTestDataFileSibling(actual) } }
135
null
4980
40,442
817f9f13b71d4957d8eaa734de2ac8369ad64770
1,762
kotlin
Apache License 2.0
app/src/main/java/com/harera/hayat/adapter/MedicinesAdapter.kt
hassan0shaban
373,620,499
false
null
package com.harera.hayat.adapter import android.location.Geocoder import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.harera.hayat.adapter.MedicinesAdapter.ViewHolder import com.harera.hayat.databinding.CardViewMedicineProductBinding import com.harera.hayat.ui.feed.FeedMedicine import com.harera.hayat.ui.feed.MedicineViewModel import com.harera.hayat.utils.location.LocationUtils import com.harera.hayat.utils.time.Time import java.util.* class MedicinesAdapter(private var list: List<FeedMedicine>) : RecyclerView.Adapter<ViewHolder>() { class ViewHolder(val bind: CardViewMedicineProductBinding) : RecyclerView.ViewHolder(bind.root) { var medicineViewModel = MedicineViewModel() fun updateUI(feedMedicine: FeedMedicine) { bind.addTime.text = Time.timeFromNowInString(feedMedicine.addingTime) bind.expireDate.text = Time.convertTimestampToString(feedMedicine.expireDate) bind.price.text = feedMedicine.price.toString().plus(" جنيه") bind.medicineName.text = feedMedicine.name updateLocation(feedMedicine.location) updateImage(feedMedicine.imageUrl) } private fun updateImage(imageUrl: String) { medicineViewModel.image.observeForever { bind.image.setImageBitmap(it) } medicineViewModel.loadImage(imageUrl) } private fun updateLocation(location: Map<String, Double>) { val geocoder = Geocoder(bind.root.context, Locale.getDefault()) bind.location.text = LocationUtils.getLocationAddressName(location, geocoder) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { CardViewMedicineProductBinding.inflate(LayoutInflater.from(parent.context), parent, false) .let { return ViewHolder(it) } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.updateUI(list[position]) } override fun getItemCount(): Int = list.size fun setList(medicines: List<FeedMedicine>) { list = medicines } }
1
Kotlin
1
1
210e8a704b126a55eaaea7afef7b3272542b501c
2,253
Hayat-EG-Android
MIT License
compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/coroutines/coroutineConstants.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}
/* * Copyright 2010-2022 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.codegen.coroutines const val SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME = "\$completion" const val SUSPEND_CALL_RESULT_NAME = "\$result" const val ILLEGAL_STATE_ERROR_MESSAGE = "call to 'resume' before 'invoke' with coroutine"
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
466
kotlin
Apache License 2.0
retrofit/app/src/main/java/com/gsesdras/retrofit/data/model/AccountDTO.kt
gsesdras
492,298,329
false
null
package com.gsesdras.retrofit.data.model data class AccountDTO( val id: String, val name: String, val username: String, val createdAt: String, val avatar: String )
0
Kotlin
0
0
dcc85a2f8cb8853962dba3bbf4081078238e6dde
184
android-samples
MIT License
libraries/extensions/src/main/kotlin/com/egoriku/grodnoroads/extensions/Firebase.kt
egorikftp
485,026,420
false
null
package com.egoriku.grodnoroads.extensions import com.egoriku.grodnoroads.extensions.common.ResultOf import com.google.firebase.FirebaseException import com.google.firebase.database.* import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow inline fun <reified T> Query.awaitValueEventListener(): Flow<ResultOf<List<T>>> = callbackFlow { val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { val entityList = snapshot.children.mapNotNull { dataSnapshot -> dataSnapshot.valueOf<T>() } trySend(ResultOf.Success(entityList)) } catch (e: DatabaseException) { trySend(ResultOf.Failure(e)) } } override fun onCancelled(error: DatabaseError) { val exception = FirebaseException(getErrorMessage(error.code)) trySend(ResultOf.Failure(exception)) } } addValueEventListener(valueEventListener) awaitClose { removeEventListener(valueEventListener) } } inline fun <reified T> DatabaseReference.awaitValueEventListener(): Flow<ResultOf<List<T>>> = callbackFlow { val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { val entityList = snapshot.children.mapNotNull { dataSnapshot -> dataSnapshot.valueOf<T>() } trySend(ResultOf.Success(entityList)) } catch (e: DatabaseException) { trySend(ResultOf.Failure(e)) } } override fun onCancelled(error: DatabaseError) { val exception = FirebaseException(getErrorMessage(error.code)) trySend(ResultOf.Failure(exception)) } } addValueEventListener(valueEventListener) awaitClose { removeEventListener(valueEventListener) } } inline fun <reified T> DatabaseReference.awaitSingleValueEventListener(): Flow<ResultOf<List<T>>> = callbackFlow { val valueEventListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { val entityList = mutableListOf<T>() snapshot.children.forEach { dataSnapshot -> dataSnapshot.valueOf<T>()?.let { entityList.add(it) } } trySend(ResultOf.Success(entityList)) } catch (e: DatabaseException) { trySend(ResultOf.Failure(e)) } } override fun onCancelled(error: DatabaseError) { val exception = FirebaseException(getErrorMessage(error.code)) trySend(ResultOf.Failure(exception)) } } addListenerForSingleValueEvent(valueEventListener) awaitClose { removeEventListener(valueEventListener) } } fun getErrorMessage(errorCode: Int): String { return when (errorCode) { DatabaseError.DISCONNECTED -> "disconnected" DatabaseError.EXPIRED_TOKEN -> "expired.token" DatabaseError.INVALID_TOKEN -> "invalid.token" DatabaseError.MAX_RETRIES -> "max.retries" DatabaseError.NETWORK_ERROR -> "network.error" DatabaseError.OPERATION_FAILED -> "operation.failed" DatabaseError.OVERRIDDEN_BY_SET -> "overridden.by.set" DatabaseError.PERMISSION_DENIED -> "permission.denied" DatabaseError.UNAVAILABLE -> "unavailable" DatabaseError.USER_CODE_EXCEPTION -> "user.code.exception" DatabaseError.UNKNOWN_ERROR -> "unknown.error" else -> "other error" } } inline fun <reified T> DataSnapshot.valueOf(): T? { return getValue(T::class.java) }
2
null
1
9
43fcdea90af3233a29912d196d2ae53e5323855f
4,161
GrodnoRoads
Apache License 2.0
rendering/src/com/android/tools/rendering/classloading/loaders/DelegatingClassLoader.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.rendering.classloading.loaders import org.jetbrains.org.objectweb.asm.ClassReader /** * A [DelegatingClassLoader.Loader] that has a static mapping of the FQCN and the byte array * representation. Mainly useful for testing or cases where the elements can be loaded ahead of time * and retained. */ class StaticLoader(private val classes: Map<String, ByteArray>) : DelegatingClassLoader.Loader { constructor(vararg pairs: Pair<String, ByteArray>) : this(mapOf(*pairs)) override fun loadClass(fqcn: String): ByteArray? = classes[fqcn] } /** Instance of a [DelegatingClassLoader.Loader] that never succeeds to find a class. */ object NopLoader : DelegatingClassLoader.Loader { override fun loadClass(fqcn: String): ByteArray? = null } /** * A [ClassLoader] that delegates the loading of the classes to a [DelegatingClassLoader.Loader]. * This allows the creation of class loaders that do loading differently without using inheritance. */ open class DelegatingClassLoader(parent: ClassLoader?, private val loader: Loader) : ClassLoader(parent) { /** Interface to be implemented by classes that can load classes. */ interface Loader { /** * Loads a class and returns the [ByteArray] representation or null if it could not be loaded. */ fun loadClass(fqcn: String): ByteArray? } /** * Cache of the classes that were renamed during [findClass]. This allows [loadClass] to ask for * the renamed name directly in future calls. */ private val renamedClasses = mutableMapOf<String, String>() @Throws(ClassNotFoundException::class) final override fun loadClass(name: String): Class<*> { onBeforeLoadClass(name) val start = System.currentTimeMillis() var loaded = false try { val clazz = super.loadClass(renamedClasses[name] ?: name) loaded = true return clazz } finally { onAfterLoadClass(name, loaded, System.currentTimeMillis() - start) } } @Throws(ClassNotFoundException::class) final override fun findClass(name: String): Class<*> { onBeforeFindClass(name) val start = System.currentTimeMillis() var found = false try { val bytes = loader.loadClass(name) ?: throw ClassNotFoundException(name) val redefinedName = ClassReader(bytes).className.replace('/', '.') if (name != redefinedName) { renamedClasses[name] = redefinedName // The class was renamed during the loading transformations, check if we had already loaded // the transformed version. // This can happen if the user code is using reflection. In those cases, we might load a // transformed class when initializing the code // so class A loads class _renamed_.B during A initialization. // // If the user code invokes Class.forName("B"), loadClass will not find it as loaded and // will invoke findClass. Here, we will // reload the class from disk, and will notice the class is supposed to be named // "_renamed_.B". // We save the mapping from B to _renamed_.B in renamedClasses so, in a future invocation we // do not get past loadClass. val redefinedClass = findLoadedClass(redefinedName) if (redefinedClass != null) { found = true return redefinedClass } } val clazz = defineClass(ClassReader(bytes).className.replace('/', '.'), bytes, 0, bytes.size) found = true return clazz } finally { onAfterFindClass(name, found, System.currentTimeMillis() - start) } } /** Called when [ClassLoader.loadClass] starts. */ protected open fun onBeforeLoadClass(fqcn: String) {} /** * Called when [ClassLoader.loadClass] finishes. * * @param fqcn the Fully Qualified Name of the class. * @param loaded true if the class was loaded or false otherwise. * @param durationMs time in milliseconds that the load took. */ protected open fun onAfterLoadClass(fqcn: String, loaded: Boolean, durationMs: Long) {} /** Called when [ClassLoader.findClass] starts. */ protected open fun onBeforeFindClass(fqcn: String) {} /** * Called when [ClassLoader.findClass] ends. * * @param fqcn the Fully Qualified Name of the class. * @param found true if the class was found or false otherwise. * @param durationMs time in milliseconds that the lookup took. */ protected open fun onAfterFindClass(fqcn: String, found: Boolean, durationMs: Long) {} }
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
5,113
android
Apache License 2.0
base/build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/application/JetifierTest.kt
qiangxu1996
301,210,525
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.integration.application import com.android.build.gradle.integration.common.fixture.GradleTestProject import com.android.build.gradle.integration.common.runner.FilterableParameterized import com.android.build.gradle.integration.common.truth.ApkSubject.assertThat import com.android.build.gradle.integration.common.truth.ScannerSubject.Companion.assertThat import com.android.build.gradle.integration.common.utils.TestFileUtils import com.android.build.gradle.options.BooleanOption import com.google.common.truth.Truth.assertThat import com.google.common.base.Throwables import org.gradle.tooling.BuildException import org.junit.Assert.fail import org.junit.Assume.assumeFalse import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.io.IOException /** * Integration test for the Jetifier feature. */ @RunWith(FilterableParameterized::class) class JetifierTest(private val withKotlin: Boolean) { companion object { @Parameterized.Parameters(name = "withKotlin_{0}") @JvmStatic fun parameters() = listOf( arrayOf(true), arrayOf(false) ) } @get:Rule val project = GradleTestProject.builder() .fromTestProject("jetifier") .withKotlinGradlePlugin(withKotlin) .create() @Before @Throws(IOException::class) fun setUp() { if (withKotlin) { TestFileUtils.searchAndReplace( project.getSubproject(":app").buildFile, "apply plugin: 'com.android.application'", "apply plugin: 'com.android.application'\n" + "apply plugin: 'kotlin-android'\n" + "apply plugin: 'kotlin-kapt'" ) TestFileUtils.searchAndReplace( project.getSubproject(":app").buildFile, "annotationProcessor 'com.example.annotationprocessor:annotationProcessor:1.0'", "kapt 'com.example.annotationprocessor:annotationProcessor:1.0'" ) } } @Test fun testJetifierDisabled() { // It's enough to test without Kotlin (to save test execution time) assumeFalse(withKotlin) // Build the project with Jetifier disabled project.executor().with(BooleanOption.ENABLE_JETIFIER, false).run("assembleDebug") val apk = project.getSubproject(":app").getApk(GradleTestProject.ApkType.DEBUG) apk.use { // 1. Check that the old support library is not yet replaced with a new one assertThat(apk).containsClass("Landroid/support/v7/preference/Preference;") assertThat(apk).doesNotContainClass("Landroidx/preference/Preference;") // 2. Check that the library to refactor is not yet refactored assertThat(apk).hasClass("Lcom/example/androidlib/MyPreference;") .that().hasSuperclass("Landroid/support/v7/preference/Preference;") } } @Test fun testJetifierEnabledAndroidXEnabled() { prepareProjectForAndroidX() // Build the project with Jetifier enabled and AndroidX enabled project.executor() .with(BooleanOption.USE_ANDROID_X, true) .with(BooleanOption.ENABLE_JETIFIER, true) .run("assembleDebug") val apk = project.getSubproject(":app").getApk(GradleTestProject.ApkType.DEBUG) apk.use { // 1. Check that the old support library has been replaced with a new one assertThat(apk).doesNotContainClass("Landroid/support/v7/preference/Preference;") assertThat(apk).containsClass("Landroidx/preference/Preference;") // 2. Check that the library to refactor has been refactored assertThat(apk).hasClass("Lcom/example/androidlib/MyPreference;") .that().hasSuperclass("Landroidx/preference/Preference;") } } @Test fun testJetifierEnabledAndroidXDisabled() { // It's enough to test without Kotlin (to save test execution time) assumeFalse(withKotlin) // Build the project with Jetifier enabled but AndroidX disabled, expect failure try { project.executor() .with(BooleanOption.USE_ANDROID_X, false) .with(BooleanOption.ENABLE_JETIFIER, true) .run("assembleDebug") fail("Expected BuildException") } catch (e: BuildException) { assertThat(Throwables.getStackTraceAsString(e)) .contains("AndroidX must be enabled when Jetifier is enabled.") } } @Test fun testAndroidArchNavigationLibrariesAreJetified() { // It's enough to test without Kotlin (to save test execution time) assumeFalse(withKotlin) // Regression test for https://issuetracker.google.com/79667498 prepareProjectForAndroidX() // Add an android.arch.navigation dependency TestFileUtils.appendToFile( project.getSubproject(":app").buildFile, "dependencies{\n" + "implementation 'android.arch.navigation:navigation-fragment:1.0.0-rc01'\n" + "}\n" ) // Build the project with Jetifier enabled and AndroidX enabled project.executor() .with(BooleanOption.USE_ANDROID_X, true) .with(BooleanOption.ENABLE_JETIFIER, true) .run("assembleDebug") val apk = project.getSubproject(":app").getApk(GradleTestProject.ApkType.DEBUG) apk.use { // Check that the android.arch.navigation library has been jetified assertThat(apk).hasClass("Landroidx/navigation/fragment/NavHostFragment;") .that().hasSuperclass("Landroidx/fragment/app/Fragment;") } } @Test fun testBlacklistedLibrariesAreNotJetified() { // It's enough to test without Kotlin (to save test execution time) assumeFalse(withKotlin) // Regression test for https://issuetracker.google.com/119135578 prepareProjectForAndroidX() TestFileUtils.appendToFile( project.getSubproject(":app").buildFile, """ dependencies { implementation 'com.example.javalib:doNotJetifyLib:1.0' } """.trimIndent() ) // We created doNotJetifyLib such that Jetifier would fail to jetify it. val result = project.executor() .with(BooleanOption.USE_ANDROID_X, true) .with(BooleanOption.ENABLE_JETIFIER, true) .expectFailure() .run("assembleDebug") result.stderr.use { assertThat(it).contains( "Failed to transform artifact 'doNotJetifyLib.jar" + " (com.example.javalib:doNotJetifyLib:1.0)" ) } // Add doNotJetifyLib to a blacklist, the build should succeed TestFileUtils.appendToFile( project.gradlePropertiesFile, """android.jetifier.blacklist = doNot.*\\.jar, foo""" ) project.executor() .with(BooleanOption.USE_ANDROID_X, true) .with(BooleanOption.ENABLE_JETIFIER, true) .run("assembleDebug") } @Test fun testStripSignatures() { // It's enough to test without Kotlin (to save test execution time) assumeFalse(withKotlin) prepareProjectForAndroidX() TestFileUtils.appendToFile( project.getSubproject(":app").buildFile, """ dependencies { implementation 'com.example.javalib:libWithSignatures:1.0' } """.trimIndent() ) // Jetifier should be able to convert libWithSignatures project.executor() .with(BooleanOption.USE_ANDROID_X, true) .with(BooleanOption.ENABLE_JETIFIER, true) .run("assembleDebug") } private fun prepareProjectForAndroidX() { TestFileUtils.searchAndReplace( project.getSubproject(":app").buildFile, "compileSdkVersion rootProject.latestCompileSdk", "compileSdkVersion \"android-28\"" ) TestFileUtils.searchAndReplace( project.getSubproject(":app") .file("src/main/java/com/example/app/MainActivity.java"), "import android.support.v7.app.AppCompatActivity;", "import androidx.appcompat.app.AppCompatActivity;" ) TestFileUtils.searchAndReplace( project.getSubproject(":app") .file("src/main/java/com/example/app/DummyClassToTestAnnotationProcessing.java"), "import android.support.annotation.NonNull;", "import androidx.annotation.NonNull;" ) } }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
9,522
vmtrace
Apache License 2.0
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/JsStringConcatenationLowering.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 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.ir.backend.js.lower import org.jetbrains.kotlin.backend.common.CommonBackendContext import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.ir.backend.js.ir.JsIrBuilder import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.isNullable import org.jetbrains.kotlin.ir.util.overrides import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.filterIsInstanceAnd /** * Calls `toString` for values of some types when concatenating strings. */ class JsStringConcatenationLowering(val context: CommonBackendContext) : FileLoweringPass { override fun lower(irFile: IrFile) { irFile.transformChildrenVoid(JsStringConcatenationTransformer(context)) } } private class JsStringConcatenationTransformer(val context: CommonBackendContext) : IrElementTransformerVoid() { private val IrType.shouldExplicitlyConvertToString: Boolean get() { if (this !is IrSimpleType) return false /** * The type may have a valueOf() function, meaning that in string concatenation, * the toString() function will be ignored, and the valueOf() function will be called instead. * Therefore, we have to wrap all types except those where we are sure that they don't have the valueOf() function. * * Note, that we do not check for the existence of the valueOf() function * in the class because it would complicate incremental compilation. * * Ignore [Long] and all its supertypes ([Any], [Comparable], [Number]) since [Long] has the valueOf() method. * Ignore [Char] since it requires an explicit conversion to string. */ return when (classifier.signature) { IdSignatureValues._boolean, IdSignatureValues.string, IdSignatureValues.array, IdSignatureValues._byte, IdSignatureValues._short, IdSignatureValues._int, IdSignatureValues.uByte, IdSignatureValues.uShort, IdSignatureValues.uInt, IdSignatureValues.uLong, IdSignatureValues._float, IdSignatureValues._double, -> false else -> true } } private fun IrExpression.explicitlyConvertedToString(): IrExpression { assert(type.shouldExplicitlyConvertToString) return if (type.isNullable()) { JsIrBuilder.buildCall(context.ir.symbols.extensionToString).apply { extensionReceiver = this@explicitlyConvertedToString } } else { val anyToStringMethodSymbol = context.ir.symbols.memberToString val toStringMethodSymbol = type.classOrNull?.let { val toStringMethods = it.owner.declarations.filterIsInstanceAnd<IrSimpleFunction> { f -> f.overrides(anyToStringMethodSymbol.owner) } toStringMethods.singleOrNull()?.symbol } ?: anyToStringMethodSymbol JsIrBuilder.buildCall(toStringMethodSymbol).apply { dispatchReceiver = this@explicitlyConvertedToString } } } private val IrFunctionSymbol.isStringPlus: Boolean get() = context.ir.symbols.isStringPlus(this) override fun visitCall(expression: IrCall): IrExpression { fun explicitlyConvertToStringIfNeeded(): IrExpression { val lastArgIndex = expression.valueArgumentsCount - 1 val plusArg = expression.getValueArgument(lastArgIndex) ?: return super.visitCall(expression) if (!plusArg.type.shouldExplicitlyConvertToString) return super.visitCall(expression) expression.putValueArgument(lastArgIndex, plusArg.explicitlyConvertedToString()) return expression } if (expression.valueArgumentsCount == 0) return super.visitCall(expression) if (expression.symbol.isStringPlus) return explicitlyConvertToStringIfNeeded() if (expression.dispatchReceiver.safeAs<IrFunctionReference>()?.symbol?.isStringPlus == true) return explicitlyConvertToStringIfNeeded() return super.visitCall(expression) } override fun visitStringConcatenation(expression: IrStringConcatenation): IrExpression { expression .transformChildrenVoid(object : IrElementTransformerVoid() { override fun visitExpression(expression: IrExpression): IrExpression { if (expression.type.shouldExplicitlyConvertToString) return expression.explicitlyConvertedToString() return expression } }) return super.visitStringConcatenation(expression) } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
5,379
kotlin
Apache License 2.0
app/src/androidTest/java/com/xently/ui/demo/ExampleInstrumentedTest.kt
AndroidLib
253,798,542
false
{"Kotlin": 183823}
package com.xently.ui.demo import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) @LargeTest class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.xently.ui.demo", appContext.packageName) } }
0
null
0
0
ff5b09da5e338017ba9621101b3c05341ccf81bb
724
Xently-UI
Apache License 2.0
navi/app/src/main/java/com/naviapp/assignment/source/RepoPagingSource.kt
kunal26das
673,585,943
false
null
package com.naviapp.assignment.source import com.naviapp.assignment.Constant.INITIAL_PAGE import com.naviapp.assignment.model.Repo import com.naviapp.assignment.repo.RepoRepository class RepoPagingSource( private val repoRepository: RepoRepository, private val user: String, ) : PagingSource<Repo>() { override suspend fun load( params: LoadParams<Int> ): LoadResult<Int, Repo> { val page = params.key ?: INITIAL_PAGE val limit = params.loadSize return try { val repoList = repoRepository.getRepoList( user = user, page = page, perPage = limit, ) LoadResult.Page( repoList, if (page > INITIAL_PAGE) page - 1 else null, if (repoList.isNotEmpty()) page + 1 else null, ) } catch (e: Throwable) { LoadResult.Error(e) } } }
0
Kotlin
0
1
de0811d69435da1b902a038848b8c52a9f9e165b
946
android-assignments
Apache License 2.0
app/src/main/java/example/jllarraz/com/passportreader/ui/fragments/CameraFragment.kt
jllarraz
151,435,529
false
null
package example.jllarraz.com.passportreader.ui.fragments import android.Manifest import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.pm.PackageManager import android.hardware.camera2.CameraCharacteristics import android.os.Build import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.Surface import android.view.View import android.view.WindowManager import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import io.fotoapparat.Fotoapparat import io.fotoapparat.characteristic.LensPosition import io.fotoapparat.configuration.CameraConfiguration import io.fotoapparat.parameter.Zoom import io.fotoapparat.preview.FrameProcessor import io.fotoapparat.selector.* import io.fotoapparat.view.CameraView import io.vicknesh.passportkyc.R abstract class CameraFragment : androidx.fragment.app.Fragment(), ActivityCompat.OnRequestPermissionsResultCallback { /** * Camera Manager */ protected var fotoapparat: Fotoapparat? = null protected var hasCameraPermission: Boolean = false protected var rotation: Int = 0 private var cameraZoom: Zoom.VariableZoom? = null private var zoomProgress: Int = 0 private var mDist: Float = 0.toFloat() var configuration = CameraConfiguration( // A full configuration // ... focusMode = firstAvailable( autoFocus() ), flashMode = off() ) //////////////////////////////////////// abstract val callbackFrameProcessor: FrameProcessor abstract val cameraPreview: CameraView abstract val requestedPermissions: ArrayList<String> var initialLensPosition: LensPosition = LensPosition.Back override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_CURRENT_ZOOM_PROGRESS)) { zoomProgress = savedInstanceState.getInt(KEY_CURRENT_ZOOM_PROGRESS, 0) } } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(KEY_CURRENT_ZOOM_PROGRESS, zoomProgress) super.onSaveInstanceState(outState) } fun buildCamera(cameraView: CameraView, lensPosition: LensPosition = LensPosition.Back) { if (fotoapparat == null) { fotoapparat = Fotoapparat .with(context?.applicationContext!!) .into(cameraView) .frameProcessor( callbackFrameProcessor ) .lensPosition { lensPosition } .build() fotoapparat?.updateConfiguration(configuration) } cameraView.setOnTouchListener(object : View.OnTouchListener { override fun onTouch(v: View?, event: MotionEvent?): Boolean { return onTouchEvent(event!!) } }) } fun configureZoom() { fotoapparat?.getCapabilities() ?.whenAvailable { capabilities -> setZoomProperties(capabilities?.zoom as Zoom.VariableZoom) } } private fun setZoomProperties(zoom: Zoom.VariableZoom) { cameraZoom = zoom setZoomProgress(zoomProgress, cameraZoom!!) } private fun setZoomProgress(progress: Int, zoom: Zoom.VariableZoom) { zoomProgress = progress fotoapparat?.setZoom(progress.toFloat() / zoom.maxZoom) } /** Determine the space between the first two fingers */ private fun getFingerSpacing(event: MotionEvent): Float { // ... val x = event.getX(0) - event.getX(1) val y = event.getY(0) - event.getY(1) return Math.sqrt((x * x + y * y).toDouble()).toFloat() } protected fun setFlash(isEnable: Boolean) { configuration = configuration.copy(flashMode = if (isEnable) torch() else off()) fotoapparat?.updateConfiguration(configuration) } protected fun setFocusMode(focusModeSelector: FocusModeSelector) { configuration = configuration.copy(focusMode = focusModeSelector) fotoapparat?.updateConfiguration(configuration) } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun onResume() { super.onResume() rotation = getRotation(context!!, initialLensPosition) buildCamera(cameraPreview!!, initialLensPosition) hasCameraPermission = hasCameraPermission() if (hasCameraPermission) { checkPermissions(requestedPermissions) } else { fotoapparat?.start() configureZoom() } } override fun onPause() { hasCameraPermission = hasCameraPermission() if (!hasCameraPermission) { fotoapparat?.stop() } fotoapparat = null; super.onPause() } override fun onDestroyView() { super.onDestroyView() } override fun onAttach(context: Context) { super.onAttach(context) } override fun onDetach() { super.onDetach() } //////////////////////////////////////////////////////////////////////////////////////// // // Pinch on Zoom Functionality // //////////////////////////////////////////////////////////////////////////////////////// fun onTouchEvent(event: MotionEvent): Boolean { // Get the pointer ID val action = event.action if (event.pointerCount > 1) { // handle multi-touch events if (action == MotionEvent.ACTION_POINTER_DOWN) { mDist = getFingerSpacing(event) } else if (action == MotionEvent.ACTION_MOVE && cameraZoom != null) { handleZoom(event) } } else { // handle single touch events if (action == MotionEvent.ACTION_UP) { // setFocusMode (previousFocusMode!!) } } return true } private fun handleZoom(event: MotionEvent) { if (cameraZoom == null) { return } val maxZoom = cameraZoom?.maxZoom!! var zoom = zoomProgress val newDist = getFingerSpacing(event) if (newDist > mDist) { //zoom in if (zoom < maxZoom) zoom++ } else if (newDist < mDist) { //zoom out if (zoom > 0) zoom-- } if (zoom > maxZoom) { zoom = maxZoom } if (zoom < 0) { zoom = 0 } mDist = newDist setZoomProgress(zoom, cameraZoom!!) //zoomProgress = cameraZoom?.zoomRatios!![zoom] } //////////////////////////////////////////////////////////////////////////////////////// // // Permissions // //////////////////////////////////////////////////////////////////////////////////////// protected fun hasCameraPermission(): Boolean { return ContextCompat.checkSelfPermission(context!!, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED } protected fun checkPermissions(permissions: ArrayList<String> = ArrayList()) { //request permission val hasPermissionCamera = ContextCompat.checkSelfPermission(context!!, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED if (!hasPermissionCamera && !permissions.contains(Manifest.permission.CAMERA)) { permissions.add(Manifest.permission.CAMERA) } if (permissions.isNotEmpty()) { requestPermissions(permissions.toArray(arrayOf<String>()), REQUEST_PERMISSIONS) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { REQUEST_PERMISSIONS -> { val permissionsDenied = ArrayList<String>() val permissionsGranted = ArrayList<String>() permissions.forEachIndexed { index, element -> if (grantResults[index] != PackageManager.PERMISSION_GRANTED) { permissionsDenied.add(element) } else { permissionsGranted.add(element) } } for (permission in permissionsDenied) { when (permission) { Manifest.permission.CAMERA -> { showErrorCameraPermissionDenied() } } } for (permission in permissionsGranted) { when (permission) { Manifest.permission.CAMERA -> { hasCameraPermission = true fotoapparat?.start() } } } onRequestPermissionsResult(permissionsDenied, permissionsGranted) } else -> { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } abstract fun onRequestPermissionsResult(permissionsDenied: ArrayList<String>, permissionsGranted: ArrayList<String>) protected fun showErrorCameraPermissionDenied() { ErrorDialog.newInstance(getString(R.string.permission_camera_rationale)) .show(childFragmentManager, FRAGMENT_DIALOG) } //////////////////////////////////////////////////////////////////////////////////////// // // Dialogs UI // //////////////////////////////////////////////////////////////////////////////////////// /** * Shows a [Toast] on the UI thread. * * @param text The message to show */ private fun showToast(text: String) { val activity = activity activity?.runOnUiThread { Toast.makeText(activity, text, Toast.LENGTH_SHORT).show() } } /** * Shows an error message dialog. */ class ErrorDialog : androidx.fragment.app.DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity return AlertDialog.Builder(activity) .setMessage(arguments!!.getString(ARG_MESSAGE)) .setPositiveButton(android.R.string.ok) { dialogInterface, i -> activity!!.finish() } .create() } companion object { private val ARG_MESSAGE = "message" fun newInstance(message: String): ErrorDialog { val dialog = ErrorDialog() val args = Bundle() args.putString(ARG_MESSAGE, message) dialog.arguments = args return dialog } } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) fun getRotation(context: Context, lensPosition: LensPosition = LensPosition.Back): Int { var facingCamera = 0 when (lensPosition) { LensPosition.Front -> { facingCamera = CameraCharacteristics.LENS_FACING_FRONT } LensPosition.Back -> { facingCamera = CameraCharacteristics.LENS_FACING_BACK } LensPosition.External -> { facingCamera = CameraCharacteristics.LENS_FACING_EXTERNAL } } val manager = context.getSystemService(Context.CAMERA_SERVICE) as android.hardware.camera2.CameraManager try { for (cameraId in manager.getCameraIdList()) { val characteristics = manager.getCameraCharacteristics(cameraId) val facing = characteristics.get(CameraCharacteristics.LENS_FACING) if (facing != null && facing != facingCamera) { continue } val mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! val rotation = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation var degrees = 0 when (rotation) { Surface.ROTATION_0 -> degrees = 0 Surface.ROTATION_90 -> degrees = 90 Surface.ROTATION_180 -> degrees = 180 Surface.ROTATION_270 -> degrees = 270 } var result: Int if (facing == CameraCharacteristics.LENS_FACING_FRONT) { result = (mSensorOrientation + degrees - 360) % 360 result = (360 + result) % 360 // compensate the mirror } else { // back-facing result = (mSensorOrientation - degrees + 360) % 360 } return result } } catch (e: Exception) { } return 0 } companion object { /** * Tag for the [Log]. */ private val TAG = CameraFragment::class.java.simpleName private val KEY_CURRENT_ZOOM_PROGRESS = "KEY_CURRENT_ZOOM_PROGRESS" private val REQUEST_PERMISSIONS = 410 private val FRAGMENT_DIALOG = TAG } }
10
null
37
91
787d3d3206b4855163784ff4fc6d643bb3743830
13,655
AndroidPassportReader
Apache License 2.0
client/app/src/main/java/org/feup/cmov/acmeclient/data/event/UiEvent.kt
miguelalexbt
305,443,061
false
null
package org.feup.cmov.acmeclient.data.event data class UiState(val isLoading: Boolean, val error: Int?) class UiEvent(val isLoading: Boolean = false, val error: Int? = null) : Event<UiState>(UiState(isLoading, error))
0
Kotlin
0
0
bbd82c059b35525faf78de35c217b661ee7ad259
223
ACME-Coffee-App
MIT License
app/src/main/java/com/kilomobi/cigobox/data/di/DispatcherModule.kt
fkistner-dev
734,864,503
false
{"Kotlin": 57557}
/* * Created by fkistner. * [email protected] * Last modified on 01/01/2024 19:56. * Copyright (c) 2024. * All rights reserved. */ package com.kilomobi.cigobox.data.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import javax.inject.Qualifier @Qualifier @Retention(AnnotationRetention.BINARY) annotation class MainDispatcher @Qualifier @Retention(AnnotationRetention.BINARY) annotation class IoDispatcher @Module @InstallIn(SingletonComponent::class) object DispatcherModule { @MainDispatcher @Provides fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main @IoDispatcher @Provides fun providesIoDispatcher(): CoroutineDispatcher = Dispatchers.IO }
0
Kotlin
0
0
b0d50245d3bf1f9c37560156d0b0d3faffcb013d
872
inventory-android
MIT License
src/main/kotlin/one/devos/osuv2kt/models/event/EventType.kt
devOS-Sanity-Edition
856,181,413
false
{"Kotlin": 49164}
package one.devos.osuv2kt.models.event public data class EventType( public val achievement: AchievementEvent, public val beatmapPlayground: BeatmapPlaycountEvent, public val beatmapsetApprove: BeatmapsetApproveEvent, public val beatmapsetDelete: BeatmapsetDeleteEvent, public val beatmapsetRevive: BeatmapsetReviveEvent, public val beatmapsetUpdate: BeatmapsetUpdateEvent, public val beatmapsetUpload: BeatmapsetUploadEvent, public val rank: RankEvent, public val rankLost: RankLostEvent, public val userSupportAgain: UserSupportAgainEvent, public val userSupportFirst: UserSupportFirstEvent, public val userSupportGift: UserSupportGiftEvent, public val usernameChange: UsernameChangeEvent )
0
Kotlin
0
0
ebefb4d6ad7003c46c4e482d8229af8df6552b81
745
osuv2kt
MIT License
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre30.kt
vanyusuf1
222,714,170
false
{"Text": 3913, "XML": 4546, "Ant Build System": 14, "Shell": 466, "Markdown": 287, "Ignore List": 79, "Git Attributes": 9, "Batchfile": 29, "SVG": 1938, "Java": 63178, "C++": 15, "HTML": 2701, "Kotlin": 3809, "DTrace": 1, "Gradle": 66, "Java Properties": 92, "INI": 231, "JFlex": 27, "Groovy": 3040, "XSLT": 109, "JavaScript": 151, "CSS": 55, "JSON": 1011, "desktop": 1, "Python": 9322, "YAML": 396, "C#": 37, "Smalltalk": 17, "Diff": 125, "Rich Text Format": 2, "CoffeeScript": 3, "JSON with Comments": 42, "Vue": 8, "OpenStep Property List": 41, "Perl": 6, "Protocol Buffer": 2, "JAR Manifest": 10, "fish": 1, "EditorConfig": 214, "XML Property List": 88, "TeX": 11, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "Elixir": 2, "PHP": 43, "Ruby": 4, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "C": 42, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 6, "Microsoft Visual Studio Solution": 6, "Objective-C": 18, "VBScript": 1, "NSIS": 8, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiModifier import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ArrayUtil import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.annotator.intentions.ConvertLambdaToClosureAction import org.jetbrains.plugins.groovy.annotator.intentions.ReplaceDotFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.* import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrAssertStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil internal class GroovyAnnotatorPre30(private val holder: AnnotationHolder) : GroovyElementVisitor() { override fun visitModifierList(modifierList: GrModifierList) { val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return holder.createErrorAnnotation(modifier, GroovyBundle.message("default.modifier.in.old.versions")) } override fun visitDoWhileStatement(statement: GrDoWhileStatement) { super.visitDoWhileStatement(statement) holder.createErrorAnnotation(statement.doKeyword, message("unsupported.do.while.statement")) } override fun visitVariableDeclaration(variableDeclaration: GrVariableDeclaration) { super.visitVariableDeclaration(variableDeclaration) if (variableDeclaration.parent is GrTraditionalForClause) { if (variableDeclaration.isTuple) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.tuple.declaration.in.for")) } else if (variableDeclaration.variables.size > 1) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.multiple.variables.in.for")) } } } override fun visitExpressionList(expressionList: GrExpressionList) { super.visitExpressionList(expressionList) if (expressionList.expressions.size > 1) { holder.createErrorAnnotation(expressionList, message("unsupported.expression.list.in.for.update")) } } override fun visitTryResourceList(resourceList: GrTryResourceList) { super.visitTryResourceList(resourceList) holder.createErrorAnnotation(resourceList.firstChild, message("unsupported.resource.list")) } override fun visitBinaryExpression(expression: GrBinaryExpression) { super.visitBinaryExpression(expression) val operator = expression.operationToken val tokenType = operator.node.elementType if (tokenType === T_ID || tokenType === T_NID) { holder.createErrorAnnotation(operator, message("operator.is.not.supported.in", tokenType)) } } override fun visitInExpression(expression: GrInExpression) { super.visitInExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.in")) } } override fun visitInstanceofExpression(expression: GrInstanceOfExpression) { super.visitInstanceofExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.instanceof")) } } override fun visitAssignmentExpression(expression: GrAssignmentExpression) { super.visitAssignmentExpression(expression) val operator = expression.operationToken if (operator.node.elementType === T_ELVIS_ASSIGN) { holder.createErrorAnnotation(operator, message("unsupported.elvis.assignment")) } } override fun visitIndexProperty(expression: GrIndexProperty) { super.visitIndexProperty(expression) val safeAccessToken = expression.safeAccessToken if (safeAccessToken != null) { holder.createErrorAnnotation(safeAccessToken, message("unsupported.safe.index.access")) } } override fun visitReferenceExpression(expression: GrReferenceExpression) { super.visitReferenceExpression(expression) val dot = expression.dotToken ?: return val tokenType = dot.node.elementType if (tokenType === T_METHOD_REFERENCE) { holder.createErrorAnnotation(dot, message("operator.is.not.supported.in", tokenType)).apply { val descriptor = createDescriptor(dot) val fix = ReplaceDotFix(tokenType, T_METHOD_CLOSURE) registerFix(fix, descriptor) } } } override fun visitArrayInitializer(arrayInitializer: GrArrayInitializer) { super.visitArrayInitializer(arrayInitializer) holder.createErrorAnnotation(arrayInitializer, message("unsupported.array.initializers")) } override fun visitLambdaExpression(expression: GrLambdaExpression) { super.visitLambdaExpression(expression) holder.createErrorAnnotation(expression.arrow, message("unsupported.lambda")).apply { registerFix(ConvertLambdaToClosureAction(expression)) } } override fun visitTypeDefinitionBody(typeDefinitionBody: GrTypeDefinitionBody) { super.visitTypeDefinitionBody(typeDefinitionBody) checkAmbiguousCodeBlockInDefinition(typeDefinitionBody) } private fun checkAmbiguousCodeBlockInDefinition(typeDefinitionBody: GrTypeDefinitionBody) { val parent = typeDefinitionBody.parent as? GrAnonymousClassDefinition ?: return val prev = typeDefinitionBody.prevSibling if (!PsiUtil.isLineFeed(prev)) return val newExpression = parent.parent as? GrNewExpression ?: return val statementOwner = PsiTreeUtil.getParentOfType(newExpression, GrStatementOwner::class.java) val parenthesizedExpression = PsiTreeUtil.getParentOfType(newExpression, GrParenthesizedExpression::class.java) if (parenthesizedExpression != null && PsiTreeUtil.isAncestor(statementOwner, parenthesizedExpression, true)) return val argumentList = PsiTreeUtil.getParentOfType(newExpression, GrArgumentList::class.java) if (argumentList != null && argumentList !is GrCommandArgumentList) { if (PsiTreeUtil.isAncestor(statementOwner, argumentList, true)) return } holder.createErrorAnnotation(typeDefinitionBody, message("ambiguous.code.block")) } override fun visitBlockStatement(blockStatement: GrBlockStatement) { super.visitBlockStatement(blockStatement) if (blockStatement.parent is GrStatementOwner) { holder.createErrorAnnotation(blockStatement, message("ambiguous.code.block")) } } override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) if (!closure.hasParametersSection() && !followsError(closure) && isClosureAmbiguous(closure)) { holder.createErrorAnnotation(closure, GroovyBundle.message("ambiguous.code.block")) } } /** * for example if (!(a inst)) {} * ^ * we are here */ private fun followsError(closure: GrClosableBlock): Boolean { val prev = closure.prevSibling return prev is PsiErrorElement || prev is PsiWhiteSpace && prev.getPrevSibling() is PsiErrorElement } private fun isClosureAmbiguous(closure: GrClosableBlock): Boolean { if (mayBeAnonymousBody(closure)) return true var place: PsiElement = closure while (true) { val parent = place.parent if (parent == null || parent is GrUnAmbiguousClosureContainer) return false if (PsiUtil.isExpressionStatement(place)) return true if (parent.firstChild !== place) return false place = parent } } private fun mayBeAnonymousBody(closure: GrClosableBlock): Boolean { val parent = closure.parent as? GrMethodCallExpression ?: return false if (parent.invokedExpression !is GrNewExpression) { return false } if (!ArrayUtil.contains(closure, *parent.closureArguments)) { return false } var run: PsiElement? = parent.parent while (run != null) { if (run is GrParenthesizedExpression) return false if (run is GrReturnStatement || run is GrAssertStatement || run is GrThrowStatement) return true run = run.parent } return false } override fun visitTypeElement(typeElement: GrTypeElement) { typeElement.annotations.forEach { holder.createErrorAnnotation(it, message("unsupported.type.annotations")) } } override fun visitCodeReferenceElement(refElement: GrCodeReferenceElement) { refElement.annotations.forEach { holder.createErrorAnnotation(it, message("unsupported.type.annotations")) } } }
1
null
1
1
ac53b8c2c773034c52746c1c9e295e0427496568
10,056
intellij-community
Apache License 2.0
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre30.kt
vanyusuf1
222,714,170
false
{"Text": 3913, "XML": 4546, "Ant Build System": 14, "Shell": 466, "Markdown": 287, "Ignore List": 79, "Git Attributes": 9, "Batchfile": 29, "SVG": 1938, "Java": 63178, "C++": 15, "HTML": 2701, "Kotlin": 3809, "DTrace": 1, "Gradle": 66, "Java Properties": 92, "INI": 231, "JFlex": 27, "Groovy": 3040, "XSLT": 109, "JavaScript": 151, "CSS": 55, "JSON": 1011, "desktop": 1, "Python": 9322, "YAML": 396, "C#": 37, "Smalltalk": 17, "Diff": 125, "Rich Text Format": 2, "CoffeeScript": 3, "JSON with Comments": 42, "Vue": 8, "OpenStep Property List": 41, "Perl": 6, "Protocol Buffer": 2, "JAR Manifest": 10, "fish": 1, "EditorConfig": 214, "XML Property List": 88, "TeX": 11, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "Elixir": 2, "PHP": 43, "Ruby": 4, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "C": 42, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 6, "Microsoft Visual Studio Solution": 6, "Objective-C": 18, "VBScript": 1, "NSIS": 8, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiModifier import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ArrayUtil import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.annotator.intentions.ConvertLambdaToClosureAction import org.jetbrains.plugins.groovy.annotator.intentions.ReplaceDotFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.* import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrAssertStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil internal class GroovyAnnotatorPre30(private val holder: AnnotationHolder) : GroovyElementVisitor() { override fun visitModifierList(modifierList: GrModifierList) { val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return holder.createErrorAnnotation(modifier, GroovyBundle.message("default.modifier.in.old.versions")) } override fun visitDoWhileStatement(statement: GrDoWhileStatement) { super.visitDoWhileStatement(statement) holder.createErrorAnnotation(statement.doKeyword, message("unsupported.do.while.statement")) } override fun visitVariableDeclaration(variableDeclaration: GrVariableDeclaration) { super.visitVariableDeclaration(variableDeclaration) if (variableDeclaration.parent is GrTraditionalForClause) { if (variableDeclaration.isTuple) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.tuple.declaration.in.for")) } else if (variableDeclaration.variables.size > 1) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.multiple.variables.in.for")) } } } override fun visitExpressionList(expressionList: GrExpressionList) { super.visitExpressionList(expressionList) if (expressionList.expressions.size > 1) { holder.createErrorAnnotation(expressionList, message("unsupported.expression.list.in.for.update")) } } override fun visitTryResourceList(resourceList: GrTryResourceList) { super.visitTryResourceList(resourceList) holder.createErrorAnnotation(resourceList.firstChild, message("unsupported.resource.list")) } override fun visitBinaryExpression(expression: GrBinaryExpression) { super.visitBinaryExpression(expression) val operator = expression.operationToken val tokenType = operator.node.elementType if (tokenType === T_ID || tokenType === T_NID) { holder.createErrorAnnotation(operator, message("operator.is.not.supported.in", tokenType)) } } override fun visitInExpression(expression: GrInExpression) { super.visitInExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.in")) } } override fun visitInstanceofExpression(expression: GrInstanceOfExpression) { super.visitInstanceofExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.instanceof")) } } override fun visitAssignmentExpression(expression: GrAssignmentExpression) { super.visitAssignmentExpression(expression) val operator = expression.operationToken if (operator.node.elementType === T_ELVIS_ASSIGN) { holder.createErrorAnnotation(operator, message("unsupported.elvis.assignment")) } } override fun visitIndexProperty(expression: GrIndexProperty) { super.visitIndexProperty(expression) val safeAccessToken = expression.safeAccessToken if (safeAccessToken != null) { holder.createErrorAnnotation(safeAccessToken, message("unsupported.safe.index.access")) } } override fun visitReferenceExpression(expression: GrReferenceExpression) { super.visitReferenceExpression(expression) val dot = expression.dotToken ?: return val tokenType = dot.node.elementType if (tokenType === T_METHOD_REFERENCE) { holder.createErrorAnnotation(dot, message("operator.is.not.supported.in", tokenType)).apply { val descriptor = createDescriptor(dot) val fix = ReplaceDotFix(tokenType, T_METHOD_CLOSURE) registerFix(fix, descriptor) } } } override fun visitArrayInitializer(arrayInitializer: GrArrayInitializer) { super.visitArrayInitializer(arrayInitializer) holder.createErrorAnnotation(arrayInitializer, message("unsupported.array.initializers")) } override fun visitLambdaExpression(expression: GrLambdaExpression) { super.visitLambdaExpression(expression) holder.createErrorAnnotation(expression.arrow, message("unsupported.lambda")).apply { registerFix(ConvertLambdaToClosureAction(expression)) } } override fun visitTypeDefinitionBody(typeDefinitionBody: GrTypeDefinitionBody) { super.visitTypeDefinitionBody(typeDefinitionBody) checkAmbiguousCodeBlockInDefinition(typeDefinitionBody) } private fun checkAmbiguousCodeBlockInDefinition(typeDefinitionBody: GrTypeDefinitionBody) { val parent = typeDefinitionBody.parent as? GrAnonymousClassDefinition ?: return val prev = typeDefinitionBody.prevSibling if (!PsiUtil.isLineFeed(prev)) return val newExpression = parent.parent as? GrNewExpression ?: return val statementOwner = PsiTreeUtil.getParentOfType(newExpression, GrStatementOwner::class.java) val parenthesizedExpression = PsiTreeUtil.getParentOfType(newExpression, GrParenthesizedExpression::class.java) if (parenthesizedExpression != null && PsiTreeUtil.isAncestor(statementOwner, parenthesizedExpression, true)) return val argumentList = PsiTreeUtil.getParentOfType(newExpression, GrArgumentList::class.java) if (argumentList != null && argumentList !is GrCommandArgumentList) { if (PsiTreeUtil.isAncestor(statementOwner, argumentList, true)) return } holder.createErrorAnnotation(typeDefinitionBody, message("ambiguous.code.block")) } override fun visitBlockStatement(blockStatement: GrBlockStatement) { super.visitBlockStatement(blockStatement) if (blockStatement.parent is GrStatementOwner) { holder.createErrorAnnotation(blockStatement, message("ambiguous.code.block")) } } override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) if (!closure.hasParametersSection() && !followsError(closure) && isClosureAmbiguous(closure)) { holder.createErrorAnnotation(closure, GroovyBundle.message("ambiguous.code.block")) } } /** * for example if (!(a inst)) {} * ^ * we are here */ private fun followsError(closure: GrClosableBlock): Boolean { val prev = closure.prevSibling return prev is PsiErrorElement || prev is PsiWhiteSpace && prev.getPrevSibling() is PsiErrorElement } private fun isClosureAmbiguous(closure: GrClosableBlock): Boolean { if (mayBeAnonymousBody(closure)) return true var place: PsiElement = closure while (true) { val parent = place.parent if (parent == null || parent is GrUnAmbiguousClosureContainer) return false if (PsiUtil.isExpressionStatement(place)) return true if (parent.firstChild !== place) return false place = parent } } private fun mayBeAnonymousBody(closure: GrClosableBlock): Boolean { val parent = closure.parent as? GrMethodCallExpression ?: return false if (parent.invokedExpression !is GrNewExpression) { return false } if (!ArrayUtil.contains(closure, *parent.closureArguments)) { return false } var run: PsiElement? = parent.parent while (run != null) { if (run is GrParenthesizedExpression) return false if (run is GrReturnStatement || run is GrAssertStatement || run is GrThrowStatement) return true run = run.parent } return false } override fun visitTypeElement(typeElement: GrTypeElement) { typeElement.annotations.forEach { holder.createErrorAnnotation(it, message("unsupported.type.annotations")) } } override fun visitCodeReferenceElement(refElement: GrCodeReferenceElement) { refElement.annotations.forEach { holder.createErrorAnnotation(it, message("unsupported.type.annotations")) } } }
1
null
1
1
ac53b8c2c773034c52746c1c9e295e0427496568
10,056
intellij-community
Apache License 2.0
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/projectStructure/KaModule.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2024 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. */ @file:OptIn(KaPlatformInterface::class) package org.jetbrains.kotlin.analysis.api.projectStructure import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaPlatformInterface import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtFile import java.nio.file.Path /** * Represents a module inside a project. * * [KaModule] is a Source Set (or considering a new project model naming a Fragment). * Some examples of a module: main source set, test source set, library, JDK. */ @OptIn(ExperimentalSubclassOptIn::class) @SubclassOptInRequired(markerClass = KaPlatformInterface::class) public interface KaModule { /** * A list of Regular dependencies. Regular dependency allows the current module to see symbols from the dependent module. In the case * of a source set, it can be either the source set it depends on, a library, or an SDK. * * The dependencies list is non-transitive and does not include the current module. */ public val directRegularDependencies: List<KaModule> /** * A list of `dependsOn` dependencies. (Kotlin MPP projects only.) * * A `dependsOn` dependency expresses that the current module can provide `actual` declarations for `expect` declarations from the * dependent module, as well as see internal symbols of the dependent module. * * `dependsOn` dependencies are transitive, but the list is not a transitive closure. The list does not include the current module. */ public val directDependsOnDependencies: List<KaModule> /** * A list of [directDependsOnDependencies] and all of their parents (directly and indirectly), sorted topologically with the nearest * dependencies first in the list. The list does not include the current module. */ public val transitiveDependsOnDependencies: List<KaModule> /** * A list of Friend dependencies. Friend dependencies express that the current module may see internal symbols of the dependent module. * * The dependencies list is non-transitive and does not include the current module. */ public val directFriendDependencies: List<KaModule> /** * A [GlobalSearchScope] which belongs to a module content. * * Contract: `module.contentScope.contains(file) <=> file belongs to this module` */ public val contentScope: GlobalSearchScope /** * A platform (e.g, JVM, JS, Native) which the current module represents. * * @see [TargetPlatform] */ public val targetPlatform: TargetPlatform @Deprecated("Use 'targetPlatform' instead.", replaceWith = ReplaceWith("targetPlatform")) public val platform: TargetPlatform get() = targetPlatform /** * [Project] to which the current module belongs. * * If the current module depends on some other modules, all those modules should have the same [Project] as the current one. */ public val project: Project /** * A human-readable description of the current module. E.g, "main sources of module 'analysis-api'". */ @KaExperimentalApi public val moduleDescription: String } /** * A module which consists of a set of source declarations inside a project. * * Generally, a main or test Source Set. */ @OptIn(ExperimentalSubclassOptIn::class) @SubclassOptInRequired(markerClass = KaPlatformInterface::class) public interface KaSourceModule : KaModule { public val name: String @Deprecated("Use 'name' instead.", replaceWith = ReplaceWith("name")) public val moduleName: String get() = name /** * A stable binary name of module from the *Kotlin* point of view. * Having correct module name is critical for `internal`-visibility mangling. See [org.jetbrains.kotlin.asJava.mangleInternalName] * * NOTE: [stableModuleName] will be removed in the future and replaced with a platform interface service. */ @KaExperimentalApi public val stableModuleName: String? get() = null @KaExperimentalApi override val moduleDescription: String get() = "Sources of $name" /** * A set of Kotlin settings, like API version, supported features and flags. */ public val languageVersionSettings: LanguageVersionSettings } /** * A module which represents a binary library, e.g. JAR or KLIB. */ @OptIn(ExperimentalSubclassOptIn::class) @SubclassOptInRequired(markerClass = KaPlatformInterface::class) public interface KaLibraryModule : KaModule { public val libraryName: String /** * A list of binary files which constitute the library. The list can contain JARs, KLIBs, folders with `.class` files, and so on. * * The paths should be consistent with the [contentScope], so the following equivalence should hold: * * ``` * library.contentScope.contains(file) <=> library.binaryRoots.listRecursively().contains(file) * ``` */ public val binaryRoots: Collection<Path> /** * A library source, if any. If current module is a binary JAR, then [librarySources] corresponds to the sources JAR. */ public val librarySources: KaLibrarySourceModule? /** * Whether the module represents an SDK, such as the JDK. */ @KaPlatformInterface public val isSdk: Boolean @KaExperimentalApi override val moduleDescription: String get() { val label = if (isSdk) "SDK" else "Library" return "$label $libraryName" } } /** * Sources for some [KaLibraryModule]. */ @OptIn(ExperimentalSubclassOptIn::class) @SubclassOptInRequired(markerClass = KaPlatformInterface::class) public interface KaLibrarySourceModule : KaModule { public val libraryName: String /** * A library binary corresponding to the current library source. * If the current module is a source JAR, then [binaryLibrary] corresponds to the binaries JAR. */ public val binaryLibrary: KaLibraryModule @KaExperimentalApi override val moduleDescription: String get() = "Library sources of $libraryName" } /** * A module which contains kotlin [builtins](https://kotlinlang.org/spec/built-in-types-and-their-semantics.html) for a specific platform. * Kotlin builtins usually reside in the compiler, so [contentScope] is empty. */ @KaPlatformInterface public class KaBuiltinsModule( override val targetPlatform: TargetPlatform, override val project: Project ) : KaModule { override val directRegularDependencies: List<KaModule> get() = emptyList() override val directDependsOnDependencies: List<KaModule> get() = emptyList() override val transitiveDependsOnDependencies: List<KaModule> get() = emptyList() override val directFriendDependencies: List<KaModule> get() = emptyList() override val contentScope: GlobalSearchScope get() = GlobalSearchScope.EMPTY_SCOPE @KaExperimentalApi override val moduleDescription: String get() = "Builtins for $targetPlatform" override fun equals(other: Any?): Boolean = other is KaBuiltinsModule && this.targetPlatform == other.targetPlatform override fun hashCode(): Int = targetPlatform.hashCode() } /** * A module for a Kotlin script file. */ @KaExperimentalApi @OptIn(ExperimentalSubclassOptIn::class) @SubclassOptInRequired(markerClass = KaPlatformInterface::class) public interface KaScriptModule : KaModule { /** * A script PSI. */ public val file: KtFile /** * A set of Kotlin settings, like API version, supported features and flags. */ public val languageVersionSettings: LanguageVersionSettings override val moduleDescription: String get() = "Script " + file.name } /** * A module for Kotlin script dependencies. * Must be either a [KaLibraryModule] or [KaLibrarySourceModule]. */ @KaPlatformInterface public interface KaScriptDependencyModule : KaModule { /** * A `VirtualFile` that backs the dependent script PSI, or `null` if the module is for project-level dependencies. */ public val file: KtFile? } /** * A module for a dangling file. Such files are usually temporary and are stored in-memory. * Dangling files may be created for various purposes, such as: a code fragment for the evaluator, a sandbox for testing code modification * applicability, etc. */ @KaPlatformInterface public interface KaDanglingFileModule : KaModule { /** * A temporary file PSI. */ public val file: KtFile /** * The module against which the [file] is analyzed. */ public val contextModule: KaModule /** * A way of resolving references to non-local declarations in the dangling file. */ public val resolutionMode: KaDanglingFileResolutionMode /** * True if the [file] is a code fragment. * Useful to recognize code fragments when their PSI was collected. */ public val isCodeFragment: Boolean @KaExperimentalApi override val moduleDescription: String get() = "Temporary file" } /** * True if the dangling file module supports partial invalidation on PSI modifications. * Sessions for such modules can be cached for longer time. */ public val KaDanglingFileModule.isStable: Boolean get() = file.isPhysical && file.viewProvider.isEventSystemEnabled /** * A set of sources which live outside the project content root. E.g, testdata files or source files of some other project. */ @KaPlatformInterface public interface KaNotUnderContentRootModule : KaModule { /** * Human-readable module name. */ public val name: String /** * Module owner file. * A separate module is created for each file outside a content root. */ public val file: PsiFile? get() = null }
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
10,183
kotlin
Apache License 2.0
src/main/kotlin/array/ArrayLeftRotate.kt
alidehkhodaei
628,231,313
false
null
package array /** * Rotates an array to the left by one position. * If the array is empty, the function returns immediately without making any modifications. * * @param array The array to rotate. */ fun <T> rotateArrayLeftByOne(array: Array<T>) { if (array.isEmpty()) return val temp = array[0] for (i in 0 until array.size - 1) { array[i] = array[i + 1] } array[array.size - 1] = temp }
0
Kotlin
7
37
8d9b0e97d7e345b30e30483209c2fafc77b9c840
421
data-structures-and-algorithms
MIT License
src/main/kotlin/adventofcode2017/Day21FractalArt.kt
n81ur3
484,801,748
false
{"Kotlin": 472475, "Java": 275}
package adventofcode2017 class Day21FractalArt data class FractalRule(val original: String, val transformed: String) class FractalArt(ruleLines: List<String>) { val rules: List<FractalRule> val fractals: MutableList<Fractal> = mutableListOf() val activePixels: Int get() = fractals.sumOf { it.activePixels } val startingFractal = Fractal( mutableListOf( mutableListOf('.', '#', '.'), mutableListOf('.', '.', '#'), mutableListOf('#', '#', '#') ) ) init { rules = ruleLines.map { FractalRule(it.substringBefore(" ="), it.substringAfter("> ")) } fractals.add(startingFractal) } fun enhance() { val result = mutableListOf<Fractal>() fractals.forEach { fractal -> result.addAll(transformFractal(fractal)) } fractals.clear() fractals.addAll(result) } fun transformFractal(origin: Fractal): List<Fractal> { val result = mutableListOf<Fractal>() if (origin.size < 4) { result.add(Fractal.fromLine(transform(origin))) } else { result.add(Fractal.fromLine(transform(origin.topLeft))) result.add(Fractal.fromLine(transform(origin.topRight))) result.add(Fractal.fromLine(transform(origin.bottomLeft))) result.add(Fractal.fromLine(transform(origin.bottomRight))) } return result } fun printFractals() { fractals.forEach { print(it) } } private fun transform(origin: String): String { return transform(Fractal.fromLine(origin)) } private fun transform(origin: Fractal): String { val patterns = mutableListOf<String>() repeat(if (origin.size == 2) 4 else 8) { origin.rotateRight() patterns.add(origin.toString()) } origin.flipVertical() patterns.add(origin.toString()) origin.flipVertical() origin.flipHorizontal() patterns.add(origin.toString()) origin.flipHorizontal() val result = rules.firstOrNull { it.original in patterns }?.transformed ?: "" if (result == "") { println("No Match") } return result } } data class Fractal(var lines: List<MutableList<Char>>) { val size: Int = lines[0].size val activePixels: Int get() = lines.sumOf { line -> line.count { it == '#' } } val topLeft: String get() { return buildString { append(lines[0][0]) append(lines[0][1]) append("/") append(lines[1][0]) append(lines[1][1]) } } val topRight: String get() { return buildString { append(lines[0][2]) append(lines[0][3]) append("/") append(lines[1][2]) append(lines[1][3]) } } val bottomLeft: String get() { return buildString { append(lines[2][0]) append(lines[2][1]) append("/") append(lines[3][0]) append(lines[3][1]) } } val bottomRight: String get() { return buildString { append(lines[2][2]) append(lines[2][3]) append("/") append(lines[3][2]) append(lines[3][3]) } } fun rotateRight() { if (size == 2) { val tmp = lines[0][0] lines[0][0] = lines[1][0] lines[1][0] = lines[1][1] lines[1][1] = lines[0][1] lines[0][1] = tmp } else { val tmp = lines[0][0] lines[0][0] = lines[1][0] lines[1][0] = lines[2][0] lines[2][0] = lines[2][1] lines[2][1] = lines[2][2] lines[2][2] = lines[1][2] lines[1][2] = lines[0][2] lines[0][2] = lines[0][1] lines[0][1] = tmp } } fun rotateLeft() { if (size == 2) { val tmp = lines[0][0] lines[0][0] = lines[0][1] lines[0][1] = lines[1][1] lines[1][1] = lines[1][0] lines[1][0] = tmp } else { val tmp = lines[0][0] lines[0][0] = lines[0][1] lines[0][1] = lines[0][2] lines[0][2] = lines[1][2] lines[1][2] = lines[2][2] lines[2][2] = lines[2][1] lines[2][1] = lines[2][0] lines[2][0] = lines[1][0] lines[1][0] = tmp } } fun flipHorizontal() { if (size == 2) { var tmp = lines[0][0] lines[0][0] = lines[1][0] lines[1][0] = tmp tmp = lines[0][1] lines[0][1] = lines[1][1] lines[1][1] = tmp } else { var tmp = lines[0][0] lines[0][0] = lines[2][0] lines[2][0] = tmp tmp = lines[0][1] lines[0][1] = lines[2][1] lines[2][1] = tmp tmp = lines[0][2] lines[0][2] = lines[2][2] lines[2][2] = tmp } } fun flipVertical() { if (size == 2) { var tmp = lines[0][0] lines[0][0] = lines[0][1] lines[0][1] = tmp tmp = lines[1][0] lines[1][0] = lines[1][1] lines[1][1] = tmp } else { var tmp = lines[0][0] lines[0][0] = lines[0][2] lines[0][2] = tmp tmp = lines[1][0] lines[1][0] = lines[1][2] lines[1][2] = tmp tmp = lines[2][0] lines[2][0] = lines[2][2] lines[2][2] = tmp } } fun displayAsGrid() { lines.forEach { println(it.joinToString("")) } } override fun toString(): String { return lines.map { it.joinToString("") }.joinToString("/") } companion object { fun fromLine(input: String) = Fractal(input.split("/").map { it.toCharArray().toMutableList() }) } }
0
Kotlin
0
0
25c89cdc45121b02910da010663cd699da3fceba
6,211
kotlin-coding-challenges
MIT License
tools/weixin/src/main/kotlin/top/bettercode/summer/tools/weixin/support/offiaccount/entity/JsapiSignature.kt
top-bettercode
387,652,015
false
{"Kotlin": 2840773, "Java": 23656, "JavaScript": 22541, "CSS": 22336, "HTML": 16703}
package top.bettercode.summer.tools.weixin.support.offiaccount.entity import com.fasterxml.jackson.annotation.JsonProperty data class JsapiSignature @JvmOverloads constructor( @field:JsonProperty("signature") var signature: String? = null, @field:JsonProperty("appid") var appid: String? = null, @field:JsonProperty("nonceStr") var nonceStr: String? = null, @field:JsonProperty("timestamp") var timestamp: String? = null )
0
Kotlin
0
1
6fa7d165f9b8ff3dc8746fa4408117e84c314a51
492
summer
Apache License 2.0
conductor-dagger-sample-moshi/src/main/java/com/jshvarts/mosbymvp/di/AppComponent.kt
jshvarts
111,547,727
false
null
package com.jshvarts.mosbymvp.di import android.app.Application import com.jshvarts.mosbymvp.data.RetrofitGithubDataStore import dagger.BindsInstance import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = arrayOf(GithubModule::class)) interface AppComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } fun githubDataStore(): RetrofitGithubDataStore }
1
Kotlin
6
28
b982ee2683d8585c35090a1b9acb5ffaa61c0dd9
515
MosbyMVP
Apache License 2.0
home/src/main/java/com/kingsland/home/domain/repository/IStatisticRepository.kt
data-programmer
599,861,493
false
null
package com.kingsland.home.domain.repository import com.kingsland.home.domain.model.StatisticDomain interface IStatisticRepository { fun getAllStatistics(): List<StatisticDomain> }
0
Kotlin
0
0
bcd53b9784689e5b60d893248ccc2910b17391e0
186
ProjectTrakAndroid
MIT License
src/main/kotlin/com/dannbrown/deltaboxlib/content/block/GenericWallSignBlock.kt
danbrown
756,103,961
false
{"Kotlin": 293861, "Java": 90658}
package com.dannbrown.deltaboxlib.content.block import com.dannbrown.deltaboxlib.content.blockEntity.GenericSignBlockEntity import net.minecraft.core.BlockPos import net.minecraft.world.entity.player.Player import net.minecraft.world.item.ItemStack import net.minecraft.world.level.BlockGetter import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.WallSignBlock import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.level.block.state.properties.WoodType import net.minecraft.world.phys.HitResult import java.util.function.Supplier class GenericWallSignBlock(private val type: Supplier<BlockEntityType<GenericSignBlockEntity>>, props: Properties, woodType: WoodType, private val baseSign: Supplier<out Block>): WallSignBlock(props, woodType) { override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity { return GenericSignBlockEntity(type, blockPos, blockState) } override fun getCloneItemStack( state: BlockState?, target: HitResult?, level: BlockGetter?, pos: BlockPos?, player: Player? ): ItemStack { return ItemStack(baseSign.get()) } }
0
Kotlin
0
0
aa15bbc14a625c60ddec3e8fbbbafd9d76a6d910
1,287
deltaboxlib
MIT License
mobile/src/main/java/io/github/prefanatic/toomanysensors/data/realm/RealmFloatWrapper.kt
prefanatic
44,787,864
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 2, "XML": 41, "Kotlin": 54}
/* * Copyright 2015-2016 Cody Goldberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.prefanatic.toomanysensors.data.realm import io.realm.RealmObject public open class RealmFloatWrapper(public open var value: Float = 0f): RealmObject() { }
0
Kotlin
0
1
3b2631dc612c9fe1bf0c32bbb2539d2011e58187
778
Too-Many-Sensors
Apache License 2.0
entityit/src/main/kotlin/io/github/yushman/entityit/processor/EntityItProcessor.kt
yushman
816,771,499
false
null
package ru.tomindapps.entityit.processor import com.google.devtools.ksp.isInternal import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.validate import ru.tomindapps.entityit.annotation.Entity internal class EntityItProcessor( codeGenerator: CodeGenerator, private val logger: KSPLogger, ) : SymbolProcessor { private val generator = EntityCodeGenerator(codeGenerator, logger) override fun process(resolver: Resolver): List<KSAnnotated> { val entities = resolver.getSymbolsWithAnnotation(Entity::class.qualifiedName.toString()) val (validSymbols, invalidSymbols) = entities.partition { it.validate() } for (symbol in validSymbols) { if (symbol is KSClassDeclaration) { processInternal(symbol) } } return invalidSymbols } private fun processInternal(symbol: KSClassDeclaration) { logger.logging("Processing", symbol) val sourceMeta = symbol.getMeta() val propertiesToMeta = symbol.getAllProperties().associateWith { it.getMeta() } val mappers = propertiesToMeta.values.mapNotNull { it.mapper } generator.generateEntities(symbol, sourceMeta, propertiesToMeta, mappers) } private fun KSPropertyDeclaration.getMeta(): PropertyMeta { val nameAnnotation = this.annotations.firstOrNull { it.shortName.asString() == Entity.Named::class.simpleName } val mapperAnnotation = this.annotations.firstOrNull { it.shortName.asString() == Entity.MapWith::class.simpleName } val isNotNull = this.annotations.any { it.shortName.asString() == Entity.NotNull::class.simpleName } val name = if (nameAnnotation != null) { nameAnnotation.arguments.first().value as String } else { this.simpleName.getShortName() } val mapper = mapperAnnotation?.arguments?.first()?.value?.let { it as? KSType? }?.declaration as? KSClassDeclaration // TODO Add inheritance // val isEntity = // this.parentDeclaration?.annotations?.any { it.shortName.asString() == Entity::class.simpleName } == true return PropertyMeta( resultName = name, isNotNull = isNotNull, mapper = mapper, ) } } private fun KSClassDeclaration.getMeta(): SourceMeta { val annotation = this.annotations.first { it.shortName.asString() == Entity::class.simpleName } val params = annotation.arguments val kotlinSerializable = params.first { it.name?.asString() == "kotlinSerializable" }.value as Boolean val nullableValues = params.first { it.name?.asString() == "nullableValues" }.value as Boolean val generateMappers = params.first { it.name?.asString() == "generateMappers" }.value as Boolean return SourceMeta( kotlinSerializable = kotlinSerializable, nullableValues = nullableValues, generateMappers = generateMappers, isInternal = this.isInternal(), ) }
2
null
0
5
2fc3280413e0e18f3e64c4dd487ef9aee37d730c
3,400
EntityIt
MIT License
plugin/src/main/kotlin/com/firsttimeinforever/intellij/pdf/viewer/ui/editor/presentation/PdfPresentationModeListener.kt
FirstTimeInForever
245,457,194
false
{"Kotlin": 174520, "HTML": 794, "CSS": 460, "JavaScript": 29}
package com.firsttimeinforever.intellij.pdf.viewer.ui.editor.presentation import com.intellij.util.messages.Topic fun interface PdfPresentationModeListener { fun presentationModeChanged(controller: PdfPresentationController) companion object { val TOPIC: Topic<PdfPresentationModeListener> = Topic.create( "PdfPresentationModeListener", PdfPresentationModeListener::class.java ) } }
12
Kotlin
18
85
6c7c3b43371404aa0089429076567c83f133124e
412
intellij-pdf-viewer
MIT License
plugin-common/src/test/kotlin/samples/JvmVersionSamples.kt
itbasis
143,887,823
false
null
@file:Suppress("MatchingDeclarationName") package samples import ru.itbasis.jvmwrapper.core.downloader.RemoteArchiveFile data class JvmVersionSample( val vendor: String, val type: String, val versions: List<String>, val fullVersion: String, val cleanVersion: String, val versionMajor: Int, val versionUpdate: Int?, val versionEarlyAccess: Boolean = false, val downloadPageUrl: String, val downloadArchiveUrlPart: String, val remoteFiles: Map<String, RemoteArchiveFile> = emptyMap() ) val JvmVersionLatestSamples = listOf( OracleJvmVersionLatestSamples, OpenJDKJvmVersionLatestSamples ).flatten() val JvmVersionArchiveSamples = listOf( OracleJvmVersionArchiveSamples ).flatten() val JvmVersionEarlyAccessSamples = listOf( OpenJDKJvmVersionEarlyAccessSamples ).flatten() val JvmVersionSamples = listOf( JvmVersionLatestSamples, JvmVersionEarlyAccessSamples, JvmVersionArchiveSamples ).flatten()
8
Kotlin
0
2
c9066a0147d979b66175ae8decf82307dea7f69d
915
jvm-wrapper-ide-plugins
MIT License
packages/kuark-secret/src/test/kotlin/kuark/secret/SecretNumberTest.kt
kuark-dev
822,935,203
false
{"Kotlin": 6984}
package kuark.secret import kotlin.test.Test import kotlin.test.assertEquals class SecretNumberTest { @Test fun `toString returns 6 asterisks`() { val secret = SecretNumber(0) assertEquals("******", secret.toString()) } @Test fun `toString returns 6 asterisks for empty string`() { val secret = SecretNumber(Long.MAX_VALUE) assertEquals("******", secret.toString()) } }
2
Kotlin
0
0
f83d81235e607bcfda94512e783ff42a362b6f0a
402
kuark
MIT License
simplecloud-base/src/main/kotlin/eu/thesimplecloud/base/manager/setup/groups/ServerGroupSetup.kt
theSimpleCloud
270,085,977
false
null
/* * MIT License * * Copyright (C) 2020-2022 The SimpleCloud authors * * 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 eu.thesimplecloud.base.manager.setup.groups import eu.thesimplecloud.api.CloudAPI import eu.thesimplecloud.api.service.version.ServiceVersion import eu.thesimplecloud.api.wrapper.IWrapperInfo import eu.thesimplecloud.base.manager.setup.groups.provider.GroupTemplateSetupAnswerProvider import eu.thesimplecloud.base.manager.setup.groups.provider.GroupWrapperSetupAnswerProvider import eu.thesimplecloud.base.manager.setup.groups.provider.ServerVersionTypeSetupAnswerProvider import eu.thesimplecloud.launcher.console.setup.ISetup import eu.thesimplecloud.launcher.console.setup.annotations.SetupFinished import eu.thesimplecloud.launcher.console.setup.annotations.SetupQuestion import eu.thesimplecloud.launcher.console.setup.provider.BooleanSetupAnswerProvider import eu.thesimplecloud.launcher.startup.Launcher import kotlin.properties.Delegates open class ServerGroupSetup : DefaultGroupSetup(), ISetup { private lateinit var serviceVersion: ServiceVersion private var wrapper: IWrapperInfo? = null private var percent by Delegates.notNull<Int>() private var static by Delegates.notNull<Boolean>() private var maximumOnlineServices by Delegates.notNull<Int>() private var minimumOnlineServices by Delegates.notNull<Int>() private var maxPlayers by Delegates.notNull<Int>() private var memory by Delegates.notNull<Int>() private lateinit var name: String private lateinit var templateName: String var javaCommand: String = "java" @SetupQuestion(0, "manager.setup.service-group.question.name") fun nameQuestion(name: String): Boolean { this.name = name if (name.length > 16) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.name.too-long") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.name.success") return true } @SetupQuestion(1, "manager.setup.service-group.question.template", GroupTemplateSetupAnswerProvider::class) fun templateQuestion(templateName: String): Boolean { val template = createTemplate(templateName, this.name) if (template != null) { this.templateName = template } return template != null } @SetupQuestion(2, "manager.setup.service-group.question.type", ServerVersionTypeSetupAnswerProvider::class) fun typeQuestion(string: String) { this.serviceVersion = CloudAPI.instance.getServiceVersionHandler().getServiceVersionByName(string)!! Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.server-group.question.type.success") } @SetupQuestion(4, "manager.setup.service-group.question.memory") fun memoryQuestion(memory: Int): Boolean { if (memory < 128) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.memory.too-low") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.memory.success") this.memory = memory return true } @SetupQuestion(5, "manager.setup.service-group.question.max-players") fun maxPlayersQuestion(maxPlayers: Int): Boolean { if (maxPlayers < 0) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.max-players.too-low") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.max-players.success") this.maxPlayers = maxPlayers return true } @SetupQuestion(6, "manager.setup.service-group.question.minimum-online") fun minimumOnlineQuestion(minimumOnlineServices: Int): Boolean { if (minimumOnlineServices < 0) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.minimum-online.too-low") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.minimum-online.success") this.minimumOnlineServices = minimumOnlineServices return true } @SetupQuestion(7, "manager.setup.service-group.question.maximum-online") fun maximumOnlineQuestion(maximumOnlineServices: Int): Boolean { if (maximumOnlineServices < -1) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.maximum-online.too-low") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.maximum-online.success") this.maximumOnlineServices = maximumOnlineServices return true } @SetupQuestion(8, "manager.setup.service-group.question.static", BooleanSetupAnswerProvider::class) fun staticQuestion(static: Boolean) { this.static = static } @SetupQuestion(9, "manager.setup.server-group.question.wrapper", GroupWrapperSetupAnswerProvider::class) fun wrapperQuestion(string: String): Boolean { if (string.isBlank() && static) return false if (string.isBlank() && !static) return true val wrapper = CloudAPI.instance.getWrapperManager().getWrapperByName(string)!! this.wrapper = wrapper return true } @SetupQuestion(10, "manager.setup.service-group.question.percent") fun percentQuestion(percent: Int): Boolean { if (percent < 1 || percent > 100) { Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.percent.out-of-range") return false } Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.question.percent.success") this.percent = percent return true } @SetupQuestion(11, "manager.setup.service-group.question.permission") fun permissionQuestion(permission: String) { handlePermission(permission) } @SetupFinished fun finished() { CloudAPI.instance.getCloudServiceGroupManager().createServerGroup( name, templateName, memory, maxPlayers, minimumOnlineServices, maximumOnlineServices, false, static, percent, wrapper?.getName(), serviceVersion, 0, permission, javaCommand ) Launcher.instance.consoleSender.sendPropertyInSetup("manager.setup.service-group.finished", name) } }
8
null
49
98
8f10768e2be523e9b2e7c170965ca4f52a99bf09
7,782
SimpleCloud
MIT License
kontrakter/src/main/kotlin/no/nav/pleiepengerbarn/uttak/kontrakter/Uttaksgrunnlag.kt
navikt
237,293,174
false
null
package no.nav.pleiepengerbarn.uttak.kontrakter import com.fasterxml.jackson.annotation.JsonAutoDetect import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import java.math.BigDecimal import java.time.Duration import java.time.LocalDate @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class Uttaksgrunnlag ( @JsonProperty("ytelseType") val ytelseType: YtelseType = YtelseType.PSB, @JsonProperty("barn") val barn: Barn, @JsonProperty("søker") val søker: Søker, @JsonProperty("saksnummer") val saksnummer: Saksnummer, @JsonProperty("behandlingUUID") val behandlingUUID: BehandlingUUID, @JsonProperty("søktUttak") val søktUttak: List<SøktUttak>, @JsonProperty("trukketUttak") val trukketUttak: List<LukketPeriode> = listOf(), @JsonProperty("arbeid") val arbeid: List<Arbeid>, @JsonProperty("pleiebehov") val pleiebehov: Map<LukketPeriode, Pleiebehov>, @JsonProperty("nyeReglerUtbetalingsgrad") val nyeReglerUtbetalingsgrad: LocalDate? = null, @JsonProperty("overstyrtInput") val overstyrtInput: Map<LukketPeriode, OverstyrtInput> = mapOf(), @JsonProperty("inntektsgradering") val inntektsgradering: Map<LukketPeriode, Inntektsgradering> = mapOf(), @JsonProperty("lovbestemtFerie") val lovbestemtFerie: List<LukketPeriode> = listOf(), @JsonProperty("inngangsvilkår") val inngangsvilkår: Map<String, List<Vilkårsperiode>> = mapOf(), @JsonProperty("tilsynsperioder") val tilsynsperioder: Map<LukketPeriode, Duration> = mapOf(), @JsonProperty("beredskapsperioder") val beredskapsperioder: Map<LukketPeriode, Utfall> = mapOf(), @JsonProperty("nattevåksperioder") val nattevåksperioder: Map<LukketPeriode, Utfall> = mapOf(), @JsonProperty("kravprioritetForBehandlinger") val kravprioritetForBehandlinger: Map<LukketPeriode, List<BehandlingUUID>> = mapOf(), @JsonProperty("sisteVedtatteUttaksplanForBehandling") val sisteVedtatteUttaksplanForBehandling: Map<BehandlingUUID, BehandlingUUID?> = mapOf(), @JsonProperty("utenlandsoppholdperioder") val utenlandsoppholdperioder: Map<LukketPeriode, UtenlandsoppholdInfo> = mapOf() ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class Vilkårsperiode( @JsonProperty("periode") val periode: LukketPeriode, @JsonProperty("utfall") val utfall: Utfall ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class SøktUttak( @JsonProperty("periode") val periode: LukketPeriode, @JsonProperty("oppgittTilsyn") val oppgittTilsyn: Duration? = null ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class UtenlandsoppholdInfo( @JsonProperty("utenlandsoppholdÅrsak") val utenlandsoppholdÅrsak: UtenlandsoppholdÅrsak, @JsonProperty("landkode") val landkode: String? ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class OverstyrtInput( @JsonProperty("overstyrtUttaksgrad") val overstyrtUttaksgrad: BigDecimal?, @JsonProperty("overstyrtUtbetalingsgradPerArbeidsforhold") val overstyrtUtbetalingsgradPerArbeidsforhold: List<OverstyrtUtbetalingsgradPerArbeidsforhold>, ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class OverstyrtUtbetalingsgradPerArbeidsforhold( @JsonProperty("overstyrtUtbetalingsgrad") val overstyrtUtbetalingsgrad: BigDecimal, @JsonProperty("arbeidsforhold") val arbeidsforhold: Arbeidsforhold ) @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.ANY) data class Inntektsgradering( @JsonProperty("uttaksgrad") val uttaksgrad: BigDecimal, )
7
Kotlin
2
0
c4d3fb034cd432e6d900d5c83230e6ef83230fd1
5,009
pleiepenger-barn-uttak
MIT License
sample-core/src/main/java/screenswitchersample/core/activity/ForActivity.kt
JayNewstrom
48,964,076
false
null
package screenswitchersample.core.activity import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ForActivity
1
Kotlin
2
2
565a513435ba6c1935ca8c3586aee183fd2d7b17
147
ScreenSwitcher
Apache License 2.0
sample-core/src/main/java/screenswitchersample/core/activity/ForActivity.kt
JayNewstrom
48,964,076
false
null
package screenswitchersample.core.activity import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ForActivity
1
Kotlin
2
2
565a513435ba6c1935ca8c3586aee183fd2d7b17
147
ScreenSwitcher
Apache License 2.0
floid/src/main/java/com/jeremyfox/floid/ui/view_model/StatefulViewModel.kt
atljeremy
313,165,724
false
null
package com.jeremyfox.floid.ui.view_model import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.jeremyfox.floid.delegate.StatefulViewModelDelegate import com.jeremyfox.floid.delegate.StatefulViewModelImpl import com.jeremyfox.floid.reducer.Reducer import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.* @FlowPreview abstract class AndroidStatefulViewModel<Action, Data, State>( application: Application, delegate: StatefulViewModelDelegate<Action, Data, State> = StatefulViewModelImpl() ) : AndroidViewModel(application), StatefulViewModelDelegate<Action, Data, State> by delegate { private val _state: State get() = state.value ?: this.reducer().initialState init { bindActions() } abstract fun reducer(): Reducer<Action, Data, State> abstract fun bind(flow: Flow<State>): Flow<State> private fun bindActions() { val flow = actions.filterNotNull() .flatMapConcat(this.reducer()::perform) .map { this.reducer().reduce(it.action, _state, it.data) } bind(flow) .onEach(state::setValue) .launchIn(viewModelScope) } }
0
Kotlin
0
1
f1e52e77b55f24f2e2184b276f9e31ba97a569c3
1,301
Floid
MIT License
aesthetics/color/compose/src/jvmAndAndroidMain/kotlin/color/ComposeColor.kt
aSoft-Ltd
432,233,181
false
{"Kotlin": 1026412, "Java": 5544, "JavaScript": 2900}
package color import androidx.compose.ui.graphics.Color actual class ComposeColor(val value: Color)
0
Kotlin
0
0
490e03ace4c08a7fbb6e121e3b415a32ff52aa3e
101
kotlin-stdlib
MIT License
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/ChannelEpg.kt
RayBa82
29,094,366
false
null
/* * Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments import android.content.Context import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.* import android.view.View.OnClickListener import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.PopupMenu import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.squareup.picasso.Picasso import okhttp3.ResponseBody import org.apache.commons.lang3.StringUtils import org.dvbviewer.controller.R import org.dvbviewer.controller.data.entities.DVBViewerPreferences import org.dvbviewer.controller.data.entities.EpgEntry import org.dvbviewer.controller.data.entities.IEPG import org.dvbviewer.controller.data.entities.Timer import org.dvbviewer.controller.data.epg.ChannelEpgViewModel import org.dvbviewer.controller.data.epg.EPGRepository import org.dvbviewer.controller.data.epg.EpgViewModelFactory import org.dvbviewer.controller.data.remote.RemoteRepository import org.dvbviewer.controller.data.timer.TimerRepository import org.dvbviewer.controller.ui.base.BaseListFragment import org.dvbviewer.controller.ui.phone.IEpgDetailsActivity import org.dvbviewer.controller.ui.phone.TimerDetailsActivity import org.dvbviewer.controller.utils.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* /** * The Class ChannelEpg. * * @author RayBa */ class ChannelEpg : BaseListFragment(), OnItemClickListener, OnClickListener, PopupMenu.OnMenuItemClickListener { private var mAdapter: ChannelEPGAdapter? = null private var clickListener: IEpgDetailsActivity.OnIEPGClickListener? = null private var channel: String? = null private var channelId: Long = 0 private var epgId: Long = 0 private var logoUrl: String? = null private var channelPos: Int = 0 private var favPos: Int = 0 private var selectedPosition: Int = 0 private var channelLogo: ImageView? = null private var channelName: TextView? = null private var dayIndicator: TextView? = null private var mDateInfo: EpgDateInfo? = null private var lastRefresh: Date? = null private var header: View? = null private lateinit var timerRepository: TimerRepository private lateinit var remoteRepository: RemoteRepository private lateinit var epgRepository: EPGRepository private lateinit var epgViewModel: ChannelEpgViewModel override val layoutRessource: Int get() = R.layout.fragment_channel_epg override fun onAttach(context: Context) { super.onAttach(context) if (context is EpgDateInfo) { mDateInfo = context } if (context is IEpgDetailsActivity.OnIEPGClickListener) { clickListener = context } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) timerRepository = TimerRepository(getDmsInterface()) remoteRepository = RemoteRepository(getDmsInterface()) epgRepository = EPGRepository(getDmsInterface()) } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) fillFromBundle(arguments!!) mAdapter = ChannelEPGAdapter() listAdapter = mAdapter setListShown(false) listView!!.onItemClickListener = this if (header != null && channel != null) { channelLogo!!.setImageBitmap(null) val url = ServerConsts.REC_SERVICE_URL + "/" + logoUrl Picasso.get() .load(url) .into(channelLogo) channelName!!.text = channel if (DateUtils.isToday(mDateInfo!!.epgDate)) { dayIndicator!!.setText(R.string.today) } else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) { dayIndicator!!.setText(R.string.tomorrow) } else { dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY) } } setEmptyText(resources.getString(R.string.no_epg)) val epgObserver = Observer<List<EpgEntry>> { response -> onEpgChanged(response!!) } val epgViewModelFactory = EpgViewModelFactory(epgRepository) epgViewModel = ViewModelProvider(this, epgViewModelFactory) .get(ChannelEpgViewModel::class.java) val now = Date(mDateInfo!!.epgDate) val tommorrow = DateUtils.addDay(now) epgViewModel.getChannelEPG(epgId, now, tommorrow).observe(this, epgObserver) } private fun onEpgChanged(response: List<EpgEntry>) { mAdapter = ChannelEPGAdapter() listView?.adapter = mAdapter mAdapter!!.items = response mAdapter!!.notifyDataSetChanged() setSelection(0) val dateText: String if (DateUtils.isToday(mDateInfo!!.epgDate)) { dateText = getString(R.string.today) } else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) { dateText = getString(R.string.tomorrow) } else { dateText = DateUtils.formatDateTime(context, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY) } if (header != null) { if (DateUtils.isToday(mDateInfo!!.epgDate)) { dayIndicator!!.setText(R.string.today) } else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) { dayIndicator!!.setText(R.string.tomorrow) } else { dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY) } dayIndicator!!.text = dateText } else { val activity = activity as AppCompatActivity? activity!!.supportActionBar!!.subtitle = dateText } lastRefresh = Date(mDateInfo!!.epgDate) setListShown(true) } private fun fillFromBundle(savedInstanceState: Bundle) { channel = savedInstanceState.getString(KEY_CHANNEL_NAME) channelId = savedInstanceState.getLong(KEY_CHANNEL_ID) epgId = savedInstanceState.getLong(KEY_EPG_ID) logoUrl = savedInstanceState.getString(KEY_CHANNEL_LOGO) channelPos = savedInstanceState.getInt(KEY_CHANNEL_POS) favPos = savedInstanceState.getInt(KEY_FAV_POS) } /* (non-Javadoc) * @see org.dvbviewer.controller.ui.base.BaseListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = super.onCreateView(inflater, container, savedInstanceState) if (v != null) { header = v.findViewById(R.id.epg_header) channelLogo = v.findViewById(R.id.icon) channelName = v.findViewById(R.id.title) dayIndicator = v.findViewById(R.id.dayIndicator) } return v } /** * The Class ViewHolder. * * @author RayBa */ private class ViewHolder { internal var startTime: TextView? = null internal var title: TextView? = null internal var description: TextView? = null internal var contextMenu: ImageView? = null } /* (non-Javadoc) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) */ override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { val entry = mAdapter!!.getItem(position) if (clickListener != null) { clickListener!!.onIEPGClick(entry) return } val i = Intent(context, IEpgDetailsActivity::class.java) i.putExtra(IEPG::class.java.simpleName, entry) startActivity(i) } /** * The Class ChannelEPGAdapter. * * @author RayBa */ inner class ChannelEPGAdapter /** * Instantiates a new channel epg adapter. */ : ArrayListAdapter<EpgEntry>() { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var convertView = convertView val holder: ViewHolder if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_row_epg, parent, false) holder = ViewHolder() holder.startTime = convertView.findViewById(R.id.startTime) holder.title = convertView.findViewById(R.id.title) holder.description = convertView.findViewById(R.id.description) holder.contextMenu = convertView.findViewById(R.id.contextMenu) holder.contextMenu!!.setOnClickListener(this@ChannelEpg) convertView.tag = holder } else { holder = convertView.tag as ViewHolder } val epgEntry = getItem(position) holder.contextMenu!!.tag = position val flags = DateUtils.FORMAT_SHOW_TIME val date = DateUtils.formatDateTime(context, epgEntry.start.time, flags) holder.startTime!!.text = date holder.title!!.text = epgEntry.title val subTitle = epgEntry.subTitle val desc = epgEntry.description holder.description!!.text = if (TextUtils.isEmpty(subTitle)) desc else subTitle holder.description!!.visibility = if (TextUtils.isEmpty(holder.description!!.text)) View.GONE else View.VISIBLE return convertView!! } } /** * Refreshs the data * */ fun refresh() { setListShown(false) val start = Date(mDateInfo!!.epgDate) val end = DateUtils.addDay(start) epgViewModel.getChannelEPG(epgId, start, end, true) } /** * Refresh date. * */ private fun refreshDate() { if (lastRefresh != null && lastRefresh!!.time != mDateInfo!!.epgDate) { refresh() } } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onSaveInstanceState(android.os.Bundle) */ override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(KEY_CHANNEL_NAME, channel) outState.putLong(KEY_CHANNEL_ID, channelId) outState.putLong(KEY_EPG_ID, epgId) outState.putString(KEY_CHANNEL_LOGO, logoUrl) outState.putInt(KEY_CHANNEL_POS, channelPos) outState.putInt(KEY_FAV_POS, favPos) outState.putLong(KEY_EPG_DAY, mDateInfo!!.epgDate) } /* (non-Javadoc) * @see com.actionbarsherlock.app.SherlockFragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater) */ override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.channel_epg, menu) menu.findItem(R.id.menuPrev).isEnabled = !DateUtils.isToday(mDateInfo!!.epgDate) } /* (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ override fun onClick(v: View) { when (v.id) { R.id.contextMenu -> { selectedPosition = v.tag as Int val popup = PopupMenu(context!!, v) popup.menuInflater.inflate(R.menu.context_menu_epg, popup.menu) popup.setOnMenuItemClickListener(this) popup.show() } else -> { } } } override fun onMenuItemClick(item: MenuItem): Boolean { val c = mAdapter!!.getItem(selectedPosition) val timer: Timer when (item.itemId) { R.id.menuRecord -> { timer = cursorToTimer(c) val call = timerRepository.saveTimer(timer) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { sendMessage(R.string.timer_saved) logEvent(EVENT_TIMER_CREATED) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { sendMessage(R.string.error_common) } }) return true } R.id.menuTimer -> { timer = cursorToTimer(c) if (UIUtils.isTablet(context!!)) { val timerdetails = TimerDetails.newInstance() val args = TimerDetails.buildBundle(timer) timerdetails.arguments = args timerdetails.show(activity!!.supportFragmentManager, TimerDetails::class.java.name) } else { val timerIntent = Intent(context, TimerDetailsActivity::class.java) val extras = TimerDetails.buildBundle(timer) timerIntent.putExtras(extras) startActivity(timerIntent) } return true } R.id.menuDetails -> { val details = Intent(context, IEpgDetailsActivity::class.java) details.putExtra(IEPG::class.java.simpleName, c) startActivity(details) return true } R.id.menuSwitch -> { val prefs = DVBViewerPreferences(context!!) val target = prefs.getString(DVBViewerPreferences.KEY_SELECTED_CLIENT) remoteRepository.switchChannel(target, channelId.toString()).enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { sendMessage(R.string.channel_switched) } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { sendMessage(R.string.error_common) } }) return true } else -> { } } return false } /** * The Interface EpgDateInfo. * * @author RayBa */ interface EpgDateInfo { var epgDate: Long } /** * Cursor to timer. * * @param c the c * @return the timer© */ private fun cursorToTimer(c: EpgEntry): Timer { val epgTitle = if (StringUtils.isNotBlank(c.title)) c.title else channel val prefs = DVBViewerPreferences(context!!) val epgBefore = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, DVBViewerPreferences.DEFAULT_TIMER_TIME_BEFORE) val epgAfter = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, DVBViewerPreferences.DEFAULT_TIMER_TIME_AFTER) val timer = Timer() timer.title = epgTitle timer.channelId = channelId timer.channelName = channel timer.start = c.start timer.end = c.end timer.pre = epgBefore timer.post = epgAfter timer.eventId = c.eventId timer.pdc = c.pdc timer.timerAction = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0) return timer } companion object { val KEY_CHANNEL_NAME = ChannelEpg::class.java.name + "KEY_CHANNEL_NAME" val KEY_CHANNEL_ID = ChannelEpg::class.java.name + "KEY_CHANNEL_ID" val KEY_CHANNEL_LOGO = ChannelEpg::class.java.name + "KEY_CHANNEL_LOGO" val KEY_CHANNEL_POS = ChannelEpg::class.java.name + "KEY_CHANNEL_POS" val KEY_FAV_POS = ChannelEpg::class.java.name + "KEY_FAV_POS" val KEY_EPG_ID = ChannelEpg::class.java.name + "KEY_EPG_ID" val KEY_EPG_DAY = ChannelEpg::class.java.name + "EPG_DAY" } }
5
Kotlin
2
11
419c94ef1ee2ad124ece7f3c0e98b7a89f006a1c
16,880
DVBViewerController
Apache License 2.0
app/src/main/java/com/dinaraparanid/prima/fragments/FavouriteArtistListFragment.kt
dinaraparanid
365,311,683
false
null
package com.dinaraparanid.prima.fragments import com.dinaraparanid.prima.databases.repositories.FavouriteRepository import com.dinaraparanid.prima.utils.polymorphism.AbstractArtistListFragment import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch /** * [AbstractArtistListFragment] for user's favourite artists */ class FavouriteArtistListFragment : AbstractArtistListFragment() { override suspend fun loadAsync(): Job = coroutineScope { launch(Dispatchers.IO) { try { val task = FavouriteRepository.instance.getArtistsAsync() itemList.run { clear() addAll(task.await()) } } catch (ignored: Exception) { } } } }
0
Kotlin
0
5
02d189f64e28d3c9b56b2172ef17d475e952f083
853
PrimaMobile
Apache License 2.0
src/main/kotlin/uno/rebellious/emeraldorsilverfishbot/database/RoundsDAO.kt
RebelliousUno
201,096,368
false
null
package uno.rebellious.emeraldorsilverfishbot.database import com.gikk.twirk.types.users.TwitchUser import uno.rebellious.emeraldorsilverfishbot.model.VoteEligibility import uno.rebellious.emeraldorsilverfishbot.model.VoteRecorded import uno.rebellious.emeraldorsilverfishbot.model.VoteType import java.sql.Connection import java.sql.Timestamp import java.time.Instant class RoundsDAO(private val connectionList: HashMap<String, Connection>) : IGame { private fun isPlayerEligibleForRound( channel: String, gameId: Int, currentRound: Int, user: TwitchUser ): VoteEligibility { return when { currentRound == 1 -> VoteEligibility.ELIGIBLE user.userName in getUsersForGameRound(channel, gameId, currentRound) -> VoteEligibility.ALREADY_VOTED user.userName in getCorrectUsersOfGameRound(channel, gameId, currentRound - 1) -> VoteEligibility.ELIGIBLE else -> VoteEligibility.NOT_ELIGIBLE } } private fun getUsersForGameRound(channel: String, gameId: Int, roundNumber: Int): List<String> { val users = ArrayList<String>() val usersSQL = """select user from rounds JOIN entries USING(roundId) where rounds.gameId = ? and rounds.roundNum = ? """ val connection = connectionList[channel] connection?.prepareStatement(usersSQL)?.run { setInt(1, gameId) setInt(2, roundNumber) executeQuery() }?.run { while (next()) { users.add(getString(1)) } } return users } override fun getLastGameWinnersURL(channel: String): String { val sql = "select max(gameId), winnersUrl from games where games.endTime is not null" return connectionList[channel]?.createStatement()?.executeQuery(sql)?.run { if (next()) getString(2) ?: "" else "" } ?: "" } override fun getWinners(channel: String): List<Winner> { val sql = """select roundNum, games.gameId, entries.user, games.startTime, games.endTime from (select roundId, max(roundNum) as roundNum, gameId, result from rounds GROUP by gameId) as r natural join entries join games on games.gameId == r.gameId where r.result = entries.vote""" val connection = connectionList[channel] val winners = ArrayList<Winner>() connection?.createStatement()?.run { executeQuery(sql) }?.run { while (next()) { val roundNum = getInt(1) val gameId = getInt(2) val user = getString(3) val startTime = getTimestamp(4) val endTime = getTimestamp(5) winners.add(Winner(gameId, roundNum, user, startTime, endTime)) } } return winners } override fun getCorrectUsersOfGameRound(channel: String, gameId: Int, roundNumber: Int): List<String> { val correctUsers = ArrayList<String>() val usersSQL = """select user from rounds JOIN entries USING(roundId) where rounds.gameId = ? and rounds.roundNum = ? and entries.vote = rounds.result""" val connection = connectionList[channel] connection?.prepareStatement(usersSQL)?.run { setInt(1, gameId) setInt(2, roundNumber) executeQuery() }?.run { while (next()) { correctUsers.add(getString(1)) } } return correctUsers } override fun playerVote(channel: String, vote: VoteType, user: TwitchUser): VoteRecorded { val gameList = getOpenGames(channel) val game = if (gameList.isNotEmpty()) gameList.first() else return VoteRecorded.NO_GAME_RUNNING val currentRound = getRoundForGame(channel, game) return when (isPlayerEligibleForRound(channel, game, currentRound.first, user)) { VoteEligibility.ELIGIBLE -> if (recordVote( channel, vote, user, currentRound.second ) ) VoteRecorded.RECORDED else VoteRecorded.ERROR VoteEligibility.NOT_ELIGIBLE -> VoteRecorded.INELLIGIBLE VoteEligibility.ALREADY_VOTED -> VoteRecorded.ALREADY_VOTED } } private fun recordVote(channel: String, vote: VoteType, user: TwitchUser, currentRoundId: Int): Boolean { val voteSQL = "INSERT into entries (roundId, user, vote) VALUES (?, ?, ?)" val connection = connectionList[channel] return connection?.prepareStatement(voteSQL)?.run { setInt(1, currentRoundId) setString(2, user.userName) setString(3, vote.name) executeUpdate() } ?: -1 > 0 } override fun found(channel: String, found: VoteType): Int { val game = getOpenGames(channel).maxOrNull() ?: return -1 val round = getRoundForGame(channel, game) return found(channel, game, round.first, found) } private fun found(channel: String, gameId: Int, roundNumber: Int, found: VoteType): Int { val connection = connectionList[channel] val updateSQL = "Update rounds SET result = ? where gameId = ? AND roundNum = ?" val rowsAffected = connection?.prepareStatement(updateSQL)?.run { setString(1, found.name) setInt(2, gameId) setInt(3, roundNumber) executeUpdate() } ?: -1 return if (rowsAffected > 0) { startRound(channel, gameId, roundNumber + 1) getRoundForGame(channel, gameId).first } else { -1 } } override fun startRound(channel: String, gameId: Int, roundNumber: Int): Int { val startRoundSQL = "insert into rounds (gameId, roundNum) VALUES (?, ?)" val connections = connectionList[channel] return connections?.prepareStatement(startRoundSQL)?.run { setInt(1, gameId) setInt(2, roundNumber) executeUpdate() } ?: -1 } override fun startGame(channel: String): Int { val startGameSQL = "insert into games (startTime) VALUES (?)" val connection = connectionList[channel] return connection?.prepareStatement(startGameSQL)?.run { setTimestamp(1, Timestamp.from(Instant.now())) executeUpdate() val id = generatedKeys if (id.next()) id.getInt(1) else -1 } ?: -1 } override fun getRoundForGame(channel: String, gameId: Int): Pair<Int, Int> { val roundSQL = "SELECT MAX(roundNum), roundId from rounds where gameId = ? " val connection = connectionList[channel] return connection?.prepareStatement(roundSQL)?.run { setInt(1, gameId) executeQuery() }?.run { if (next()) { Pair(getInt(1), getInt(2)) } else { Pair(-1, -1) } } ?: Pair(-1, -1) } override fun getOpenGames(channel: String): List<Int> { val openGames = ArrayList<Int>() val sql = "SELECT gameId from games where endTime is null" val connection = connectionList[channel] connection?.createStatement()?.run { executeQuery(sql) }?.run { while (next()) { openGames.add(getInt(1)) } } return openGames } private fun closeRounds(channel: String, gameId: Int): Int { val removeOpenRoundSQL = "DELETE from rounds WHERE gameId = ? and result is NULL" val connection = connectionList[channel] return connection?.prepareStatement(removeOpenRoundSQL)?.run { setInt(1, gameId) executeUpdate() } ?: 0 } override fun endGame(channel: String): Int { val games = getOpenGames(channel) return if (games.isNotEmpty()) { val affectedRows = endGame(channel, games.first()) if (affectedRows == 1) { //close open rounds closeRounds(channel, games.first()) games.first() } else { -1 } } else { -1 } } override fun endGame(channel: String, gameId: Int): Int { val endGameSQL = "update games set endtime = ? where gameid = ?" val connection = connectionList[channel] return connection?.prepareStatement(endGameSQL)?.run { setTimestamp(1, Timestamp.from(Instant.now())) setInt(2, gameId) executeUpdate() } ?: -1 } fun createGameTable(connection: Connection) { val gameTableSQL = "CREATE TABLE IF NOT EXISTS games (gameId INTEGER PRIMARY KEY AUTOINCREMENT, startTime INT, endTime INT, winnersUrl TEXT)" connection.createStatement()?.apply { queryTimeout = 30 executeUpdate(gameTableSQL) } } fun createRoundsTable(connection: Connection) { val roundsTableSQL = """CREATE TABLE IF NOT EXISTS "rounds" ( "roundId" INTEGER PRIMARY KEY AUTOINCREMENT, "gameId" INTEGER, "roundNum" INT, "result" TEXT, FOREIGN KEY("gameId") REFERENCES "games"("gameId") )""" connection.createStatement()?.apply { queryTimeout = 30 executeUpdate(roundsTableSQL) } } fun createEntryTable(connection: Connection) { val entryTableSQL = """CREATE TABLE IF NOT EXISTS "entries" ( "roundId" INTEGER NOT NULL, "user" TEXT NOT NULL, "vote" TEXT, PRIMARY KEY("user","roundId"), FOREIGN KEY("roundId") REFERENCES "rounds"("roundId") )""" connection.createStatement()?.apply { queryTimeout = 30 executeUpdate(entryTableSQL) } } override fun setLastGameWinnersURL(channel: String, url: String) { val updateSQL = "UPDATE games SET winnersUrl = ? where gameId in(select max(gameId) from games where endTime is not null)" connectionList[channel]?.prepareStatement(updateSQL)?.run { setString(1, url) executeUpdate() } } }
6
Kotlin
0
3
db66470e042865cc712c981b0fd06e2e9eafaa91
10,267
EmeraldOrSilverfish
MIT License
app/src/main/java/com/battlelancer/seriesguide/SgApp.kt
UweTrottmann
1,990,682
false
null
package com.battlelancer.seriesguide import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.os.Build import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import android.os.StrictMode.VmPolicy import androidx.annotation.RequiresApi import com.battlelancer.seriesguide.modules.AppModule import com.battlelancer.seriesguide.modules.DaggerServicesComponent import com.battlelancer.seriesguide.modules.HttpClientModule import com.battlelancer.seriesguide.modules.ServicesComponent import com.battlelancer.seriesguide.modules.TmdbModule import com.battlelancer.seriesguide.modules.TraktModule import com.battlelancer.seriesguide.modules.TvdbModule import com.battlelancer.seriesguide.service.NotificationService import com.battlelancer.seriesguide.settings.AppSettings import com.battlelancer.seriesguide.settings.DisplaySettings import com.battlelancer.seriesguide.util.SgPicassoRequestHandler import com.battlelancer.seriesguide.util.ThemeUtils import com.crashlytics.android.core.CrashlyticsCore import com.google.android.gms.security.ProviderInstaller import com.jakewharton.threetenabp.AndroidThreeTen import com.squareup.picasso.OkHttp3Downloader import com.squareup.picasso.Picasso import io.fabric.sdk.android.Fabric import io.palaima.debugdrawer.timber.data.LumberYard import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.newSingleThreadContext import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.EventBusException import timber.log.Timber import java.util.ArrayList /** * Initializes logging and services. */ class SgApp : Application() { companion object { const val JOB_ID_EXTENSION_AMAZON = 1001 const val JOB_ID_EXTENSION_GOOGLE_PLAY = 1002 const val JOB_ID_EXTENSION_VODSTER = 1003 const val JOB_ID_EXTENSION_WEBSEARCH = 1004 const val JOB_ID_EXTENSION_YOUTUBE = 1005 const val JOB_ID_EXTENSION_ACTIONS_SERVICE = 1006 const val NOTIFICATION_EPISODE_ID = 1 const val NOTIFICATION_SUBSCRIPTION_ID = 2 const val NOTIFICATION_TRAKT_AUTH_ID = 3 const val NOTIFICATION_JOB_ID = 4 const val NOTIFICATION_CHANNEL_EPISODES = "episodes" const val NOTIFICATION_CHANNEL_ERRORS = "errors" /** * Time calculation has changed, all episodes need re-calculation. */ const val RELEASE_VERSION_12_BETA5 = 218 /** * Requires legacy cache clearing due to switch to Picasso for posters. */ const val RELEASE_VERSION_16_BETA1 = 15010 /** * Requires trakt watched movie (re-)download. */ const val RELEASE_VERSION_23_BETA4 = 15113 /** * Requires full show update due to switch to locally stored trakt ids. */ const val RELEASE_VERSION_26_BETA3 = 15142 /** * Populate shows last watched field from activity table. */ const val RELEASE_VERSION_34_BETA4 = 15223 /** * Switched to Google Sign-In: notify existing Cloud users to sign in again. */ const val RELEASE_VERSION_36_BETA2 = 15241 /** * Extensions API v2, old extensions no longer work. */ const val RELEASE_VERSION_40_BETA4 = 1502803 /** * ListWidgetProvider alarm intent is now explicit. */ const val RELEASE_VERSION_40_BETA6 = 1502805 /** * For trakt and hexagon sync movies were not added in all cases, reset sync times. */ const val RELEASE_VERSION_50_1 = 2105008 const val RELEASE_VERSION_51_BETA4 = 2105103 /** * The content authority used to identify the SeriesGuide [android.content.ContentProvider]. */ const val CONTENT_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider" /** Executes one coroutine at a time. But does not guarantee order if they suspend. */ @Suppress("EXPERIMENTAL_API_USAGE") val SINGLE = newSingleThreadContext("SingleThread") private var servicesComponent: ServicesComponent? = null @JvmStatic @Synchronized fun getServicesComponent(context: Context): ServicesComponent { if (servicesComponent == null) { servicesComponent = DaggerServicesComponent.builder() .appModule(AppModule(context)) .httpClientModule(HttpClientModule()) .tmdbModule(TmdbModule()) .traktModule(TraktModule()) .tvdbModule(TvdbModule()) .build() } return servicesComponent!! } } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { enableStrictMode() } // set up logging first so crashes during initialization are caught initializeLogging() // get latest TZDB.dat from // https://github.com/ThreeTen/threetenbp/blob/master/src/main/resources/org/threeten/bp/TZDB.dat // (switch to tagged version!) // current version: v1.4.2 AndroidThreeTen.init(this, "org/threeten/bp/TZDB.dat") initializeEventBus() initializePicasso() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { initializeNotificationChannels() } // Load the current theme into a global variable ThemeUtils.updateTheme(DisplaySettings.getThemeIndex(this)) // Tell Google Play Services to update the security provider. // This is not technically required, but might improve connection issues // due to encryption on some devices. ProviderInstaller.installIfNeededAsync(applicationContext, providerInstallListener) } private val providerInstallListener = object : ProviderInstaller.ProviderInstallListener { override fun onProviderInstallFailed(errorCode: Int, recoveryIntent: Intent?) { Timber.e("Failed to install GMS provider $errorCode") } override fun onProviderInstalled() { Timber.v("Successfully installed GMS provider") } } private fun initializeLogging() { // set up reporting tools first if (!Fabric.isInitialized()) { // use core kit only, Crashlytics kit also adds Answers and Beta kit Fabric.with(this, CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) } if (AppSettings.isUserDebugModeEnabled(this)) { // debug drawer logging val lumberYard = LumberYard.getInstance(this) GlobalScope.launch(Dispatchers.IO) { lumberYard.cleanUp() } Timber.plant(lumberYard.tree()) // detailed logcat logging Timber.plant(Timber.DebugTree()) } // crash and error reporting Timber.plant(AnalyticsTree()) } private fun initializeEventBus() { try { EventBus.builder() .logNoSubscriberMessages(BuildConfig.DEBUG) .addIndex(SgEventBusIndex()) .installDefaultEventBus() } catch (ignored: EventBusException) { // instance was already set } } private fun initializePicasso() { val downloader = OkHttp3Downloader(this) val picasso = Picasso.Builder(this) .downloader(downloader) .addRequestHandler(SgPicassoRequestHandler(downloader, this)) .build() try { Picasso.setSingletonInstance(picasso) } catch (ignored: IllegalStateException) { // instance was already set } } @RequiresApi(api = Build.VERSION_CODES.O) private fun initializeNotificationChannels() { // note: sound is on by default val channels = ArrayList<NotificationChannel>() val colorAccent = getColor(R.color.sg_color_primary) val channelEpisodes = NotificationChannel(NOTIFICATION_CHANNEL_EPISODES, getString(R.string.episodes), NotificationManager.IMPORTANCE_DEFAULT) channelEpisodes.description = getString(R.string.pref_notificationssummary) channelEpisodes.enableLights(true) channelEpisodes.lightColor = colorAccent channelEpisodes.vibrationPattern = NotificationService.VIBRATION_PATTERN channels.add(channelEpisodes) val channelJobs = NotificationChannel(NOTIFICATION_CHANNEL_ERRORS, getString(R.string.pref_notification_channel_errors), NotificationManager.IMPORTANCE_HIGH) channelJobs.enableLights(true) channelEpisodes.lightColor = colorAccent channels.add(channelJobs) val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? manager?.createNotificationChannels(channels) } /** * Used to enable [StrictMode] for debug builds. */ private fun enableStrictMode() { // Enable StrictMode with(ThreadPolicy.Builder()) { penaltyLog() // exclude disk reads detectDiskWrites() detectNetwork() detectCustomSlowCalls() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { detectResourceMismatches() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { detectUnbufferedIo() } StrictMode.setThreadPolicy(build()) } // custom config to disable detecting untagged sockets with(VmPolicy.Builder()) { penaltyLog() detectLeakedSqlLiteObjects() detectActivityLeaks() detectLeakedClosableObjects() detectLeakedRegistrationObjects() detectFileUriExposure() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { detectContentUriWithoutPermission() } // Policy applied to all threads in the virtual machine's process StrictMode.setVmPolicy(build()) } } }
56
null
405
1,966
c7bc6445ecc58b841c1887a56146dc2d2f817007
10,390
SeriesGuide
Apache License 2.0
platform/script-debugger/protocol/protocol-model-generator/src/org/jetbrains/protocolReader/TypeMap.kt
stanislas
33,140,696
true
{"Java": 145558378, "Python": 21577356, "Groovy": 2209781, "HTML": 1666336, "C++": 269853, "Kotlin": 220171, "C": 214180, "Shell": 126751, "JavaScript": 125292, "XSLT": 113040, "CSS": 108843, "NSIS": 85922, "TeX": 60798, "Groff": 35232, "Objective-C": 27614, "Protocol Buffer": 20765, "Gherkin": 14382, "Scala": 11698, "TypeScript": 6152, "J": 5050, "Makefile": 2352, "CoffeeScript": 1759, "C#": 1538, "Ruby": 1213, "AspectJ": 182, "Smalltalk": 64, "FLUX": 57, "Perl 6": 26, "Erlang": 10}
package org.jetbrains.protocolReader /** * Keeps track of all referenced types. * A type may be used and resolved (generated or hard-coded). */ class TypeMap { private val map = THashMap<Pair<String, String>, TypeData>() private var domainGeneratorMap: Map<String, DomainGenerator>? = null private val typesToGenerate = ArrayList<StandaloneTypeBinding>() fun setDomainGeneratorMap(domainGeneratorMap: Map<String, DomainGenerator>) { this.domainGeneratorMap = domainGeneratorMap } fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? { val domainGenerator = domainGeneratorMap!!.get(domainName) if (domainGenerator == null) { throw RuntimeException("Failed to find domain generator: " + domainName) } return getTypeData(domainName, typeName).get(direction).resolve(this, domainGenerator) } fun addTypeToGenerate(binding: StandaloneTypeBinding) { typesToGenerate.add(binding) } throws(javaClass<IOException>()) public fun generateRequestedTypes() { // Size may grow during iteration. //noinspection ForLoopReplaceableByForEach for (i in typesToGenerate.indices) { typesToGenerate.get(i).generate() } for (typeData in map.values()) { typeData.checkComplete() } } fun getTypeData(domainName: String, typeName: String): TypeData { val key = Pair.create<String, String>(domainName, typeName) var result: TypeData? = map.get(key) if (result == null) { result = TypeData(typeName) map.put(key, result) } return result!! } }
0
Java
0
0
64a451775a620abf46d55483f347e03d663de7c7
1,594
intellij-community
Apache License 2.0
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/friendships/NoRetweets.kt
MeilCli
51,423,644
false
null
package com.twitter.meil_mitu.twitter4hk.api.friendships import com.twitter.meil_mitu.twitter4hk.AbsGet import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.ResponseData import com.twitter.meil_mitu.twitter4hk.converter.IIDsConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class NoRetweets<TIDs>( oauth: AbsOauth, protected val json: IIDsConverter<TIDs>) : AbsGet<ResponseData<TIDs>>(oauth) { /** * must not use in JsonConverter for CursorIDs */ var stringifyIds: Boolean? by booleanParam("stringify_ids") override val url = "https://api.twitter.com/1.1/friendships/no_retweets/ids.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true @Throws(Twitter4HKException::class) override fun call(): ResponseData<TIDs> { return json.toIDsResponseData(oauth.get(this)) } }
0
Kotlin
0
0
818e42ea417c326e3d50024decce4c7e70641a73
987
Twitter4HK
MIT License
kt/godot-library/src/main/kotlin/godot/gen/godot/StyleBoxTexture.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.CoreTypeHelper import godot.`annotation`.CoreTypeLocalCopy import godot.`annotation`.GodotBaseType import godot.core.Color import godot.core.Rect2 import godot.core.TypeManager import godot.core.VariantType.BOOL import godot.core.VariantType.COLOR import godot.core.VariantType.DOUBLE import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.OBJECT import godot.core.VariantType.RECT2 import godot.core.memory.TransferContext import godot.util.VoidPtr import kotlin.Boolean import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.Long import kotlin.Suppress import kotlin.Unit /** * A texture-based nine-patch [StyleBox], in a way similar to [NinePatchRect]. This stylebox * performs a 3×3 scaling of a texture, where only the center cell is fully stretched. This makes it * possible to design bordered styles regardless of the stylebox's size. */ @GodotBaseType public open class StyleBoxTexture : StyleBox() { /** * The texture to use when drawing this style box. */ public var texture: Texture2D? get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getTexturePtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as Texture2D?) } set(`value`) { TransferContext.writeArguments(OBJECT to value) TransferContext.callMethod(rawPtr, MethodBindings.setTexturePtr, NIL) } /** * Increases the left margin of the 3×3 texture box. * A higher value means more of the source texture is considered to be part of the left border of * the 3×3 box. * This is also the value used as fallback for [StyleBox.contentMarginLeft] if it is negative. */ public var textureMarginLeft: Float get() { TransferContext.writeArguments(LONG to 0L) TransferContext.callMethod(rawPtr, MethodBindings.getTextureMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 0L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setTextureMarginPtr, NIL) } /** * Increases the top margin of the 3×3 texture box. * A higher value means more of the source texture is considered to be part of the top border of * the 3×3 box. * This is also the value used as fallback for [StyleBox.contentMarginTop] if it is negative. */ public var textureMarginTop: Float get() { TransferContext.writeArguments(LONG to 1L) TransferContext.callMethod(rawPtr, MethodBindings.getTextureMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 1L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setTextureMarginPtr, NIL) } /** * Increases the right margin of the 3×3 texture box. * A higher value means more of the source texture is considered to be part of the right border of * the 3×3 box. * This is also the value used as fallback for [StyleBox.contentMarginRight] if it is negative. */ public var textureMarginRight: Float get() { TransferContext.writeArguments(LONG to 2L) TransferContext.callMethod(rawPtr, MethodBindings.getTextureMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 2L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setTextureMarginPtr, NIL) } /** * Increases the bottom margin of the 3×3 texture box. * A higher value means more of the source texture is considered to be part of the bottom border * of the 3×3 box. * This is also the value used as fallback for [StyleBox.contentMarginBottom] if it is negative. */ public var textureMarginBottom: Float get() { TransferContext.writeArguments(LONG to 3L) TransferContext.callMethod(rawPtr, MethodBindings.getTextureMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 3L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setTextureMarginPtr, NIL) } /** * Expands the left margin of this style box when drawing, causing it to be drawn larger than * requested. */ public var expandMarginLeft: Float get() { TransferContext.writeArguments(LONG to 0L) TransferContext.callMethod(rawPtr, MethodBindings.getExpandMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 0L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setExpandMarginPtr, NIL) } /** * Expands the top margin of this style box when drawing, causing it to be drawn larger than * requested. */ public var expandMarginTop: Float get() { TransferContext.writeArguments(LONG to 1L) TransferContext.callMethod(rawPtr, MethodBindings.getExpandMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 1L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setExpandMarginPtr, NIL) } /** * Expands the right margin of this style box when drawing, causing it to be drawn larger than * requested. */ public var expandMarginRight: Float get() { TransferContext.writeArguments(LONG to 2L) TransferContext.callMethod(rawPtr, MethodBindings.getExpandMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 2L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setExpandMarginPtr, NIL) } /** * Expands the bottom margin of this style box when drawing, causing it to be drawn larger than * requested. */ public var expandMarginBottom: Float get() { TransferContext.writeArguments(LONG to 3L) TransferContext.callMethod(rawPtr, MethodBindings.getExpandMarginPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(LONG to 3L, DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setExpandMarginPtr, NIL) } /** * Controls how the stylebox's texture will be stretched or tiled horizontally. See * [AxisStretchMode] for possible values. */ public var axisStretchHorizontal: AxisStretchMode get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getHAxisStretchModePtr, LONG) return StyleBoxTexture.AxisStretchMode.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setHAxisStretchModePtr, NIL) } /** * Controls how the stylebox's texture will be stretched or tiled vertically. See * [AxisStretchMode] for possible values. */ public var axisStretchVertical: AxisStretchMode get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getVAxisStretchModePtr, LONG) return StyleBoxTexture.AxisStretchMode.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setVAxisStretchModePtr, NIL) } /** * Species a sub-region of the texture to use. * This is equivalent to first wrapping the texture in an [AtlasTexture] with the same region. * If empty (`Rect2(0, 0, 0, 0)`), the whole texture will be used. */ @CoreTypeLocalCopy public var regionRect: Rect2 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getRegionRectPtr, RECT2) return (TransferContext.readReturnValue(RECT2, false) as Rect2) } set(`value`) { TransferContext.writeArguments(RECT2 to value) TransferContext.callMethod(rawPtr, MethodBindings.setRegionRectPtr, NIL) } /** * Modulates the color of the texture when this style box is drawn. */ @CoreTypeLocalCopy public var modulateColor: Color get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getModulatePtr, COLOR) return (TransferContext.readReturnValue(COLOR, false) as Color) } set(`value`) { TransferContext.writeArguments(COLOR to value) TransferContext.callMethod(rawPtr, MethodBindings.setModulatePtr, NIL) } /** * If `true`, the nine-patch texture's center tile will be drawn. */ public var drawCenter: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isDrawCenterEnabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setDrawCenterPtr, NIL) } public override fun new(scriptIndex: Int): Unit { callConstructor(ENGINECLASS_STYLEBOXTEXTURE, scriptIndex) } /** * Species a sub-region of the texture to use. * This is equivalent to first wrapping the texture in an [AtlasTexture] with the same region. * If empty (`Rect2(0, 0, 0, 0)`), the whole texture will be used. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = styleboxtexture.regionRect * //Your changes * styleboxtexture.regionRect = myCoreType * `````` */ @CoreTypeHelper public open fun regionRectMutate(block: Rect2.() -> Unit): Rect2 = regionRect.apply{ block(this) regionRect = this } /** * Modulates the color of the texture when this style box is drawn. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = styleboxtexture.modulateColor * //Your changes * styleboxtexture.modulateColor = myCoreType * `````` */ @CoreTypeHelper public open fun modulateColorMutate(block: Color.() -> Unit): Color = modulateColor.apply{ block(this) modulateColor = this } /** * Sets the margin to [size] pixels for all sides. */ public fun setTextureMarginAll(size: Float): Unit { TransferContext.writeArguments(DOUBLE to size.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setTextureMarginAllPtr, NIL) } /** * Sets the expand margin to [size] pixels for all sides. */ public fun setExpandMarginAll(size: Float): Unit { TransferContext.writeArguments(DOUBLE to size.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setExpandMarginAllPtr, NIL) } public enum class AxisStretchMode( id: Long, ) { /** * Stretch the stylebox's texture. This results in visible distortion unless the texture size * matches the stylebox's size perfectly. */ AXIS_STRETCH_MODE_STRETCH(0), /** * Repeats the stylebox's texture to match the stylebox's size according to the nine-patch * system. */ AXIS_STRETCH_MODE_TILE(1), /** * Repeats the stylebox's texture to match the stylebox's size according to the nine-patch * system. Unlike [AXIS_STRETCH_MODE_TILE], the texture may be slightly stretched to make the * nine-patch texture tile seamlessly. */ AXIS_STRETCH_MODE_TILE_FIT(2), ; public val id: Long init { this.id = id } public companion object { public fun from(`value`: Long): AxisStretchMode = entries.single { it.id == `value` } } } public companion object internal object MethodBindings { public val setTexturePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_texture") public val getTexturePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_texture") public val setTextureMarginPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_texture_margin") public val setTextureMarginAllPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_texture_margin_all") public val getTextureMarginPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_texture_margin") public val setExpandMarginPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_expand_margin") public val setExpandMarginAllPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_expand_margin_all") public val getExpandMarginPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_expand_margin") public val setRegionRectPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_region_rect") public val getRegionRectPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_region_rect") public val setDrawCenterPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_draw_center") public val isDrawCenterEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "is_draw_center_enabled") public val setModulatePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_modulate") public val getModulatePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_modulate") public val setHAxisStretchModePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_h_axis_stretch_mode") public val getHAxisStretchModePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_h_axis_stretch_mode") public val setVAxisStretchModePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "set_v_axis_stretch_mode") public val getVAxisStretchModePtr: VoidPtr = TypeManager.getMethodBindPtr("StyleBoxTexture", "get_v_axis_stretch_mode") } }
64
null
39
580
fd1af79075e7b918200aba3302496b70c76a2028
15,448
godot-kotlin-jvm
MIT License
data/settings/src/main/java/com/google/jetpackcamera/settings/model/ImageOutputFormat.kt
google
591,101,391
false
{"Kotlin": 640681, "C++": 2189, "CMake": 1010, "Shell": 724}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jetpackcamera.settings.model import com.google.jetpackcamera.settings.ImageOutputFormat as ImageOutputFormatProto enum class ImageOutputFormat { JPEG, JPEG_ULTRA_HDR; companion object { /** returns the DynamicRangeType enum equivalent of a provided DynamicRangeTypeProto */ fun fromProto(imageOutputFormatProto: ImageOutputFormatProto): ImageOutputFormat { return when (imageOutputFormatProto) { ImageOutputFormatProto.IMAGE_OUTPUT_FORMAT_JPEG_ULTRA_HDR -> JPEG_ULTRA_HDR // Treat unrecognized as JPEG as a fallback ImageOutputFormatProto.IMAGE_OUTPUT_FORMAT_JPEG, ImageOutputFormatProto.UNRECOGNIZED -> JPEG } } fun ImageOutputFormat.toProto(): ImageOutputFormatProto { return when (this) { JPEG -> ImageOutputFormatProto.IMAGE_OUTPUT_FORMAT_JPEG JPEG_ULTRA_HDR -> ImageOutputFormatProto.IMAGE_OUTPUT_FORMAT_JPEG_ULTRA_HDR } } } }
39
Kotlin
26
141
f79336788a80bf2d7e35393bde6470db3ea548e7
1,677
jetpack-camera-app
Apache License 2.0
lib/src/main/kotlin/it/scoppelletti/spaceship/app/AppExt.kt
dscoppelletti
89,261,768
false
null
/* * Copyright (C) 2013-2021 <NAME>, <http://www.scoppelletti.it/>. * * 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. */ @file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier", "unused") package it.scoppelletti.spaceship.app import android.app.Activity import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import androidx.annotation.UiThread import it.scoppelletti.spaceship.inject.AppComponent import it.scoppelletti.spaceship.inject.AppComponentProvider import it.scoppelletti.spaceship.inject.StdlibComponent import it.scoppelletti.spaceship.inject.StdlibComponentProvider /** * Application model extensions. * * @since 1.0.0 */ public object AppExt { /** * Tag of `AlertDialogFragment` fragment. * * @see it.scoppelletti.spaceship.app.AlertDialogFragment */ public const val TAG_ALERTDIALOG = "it.scoppelletti.spaceship.1" /** * Tag of `ExceptionDialogFragment` fragment. * * @see it.scoppelletti.spaceship.app.ExceptionDialogFragment */ public const val TAG_EXCEPTIONDIALOG = "it.scoppelletti.spaceship.2" /** * Tag of `BottomSheetDialogFragmentEx` fragment. * * @see it.scoppelletti.spaceship.app.BottomSheetDialogFragmentEx */ public const val TAG_BOTTOMSHEETDIALOG = "it.scoppelletti.spaceship.3" /** * Property containing an item. */ public const val PROP_ITEM = "it.scoppelletti.spaceship.1" /** * Property containing a message. */ public const val PROP_MESSAGE = "it.scoppelletti.spaceship.2" /** * Property containing a result. */ public const val PROP_RESULT = "it.scoppelletti.spaceship.3" } /** * Returns the `UIComponent` component. * * @receiver Activity. * @return The object. * @since 1.0.0 */ public fun Activity.appComponent(): AppComponent = (this.application as AppComponentProvider).appComponent() /** * Returns the `StdlibComponent` component. * * @receiver Activity. * @return The object. * @since 1.0.0 */ public fun Activity.stdlibComponent(): StdlibComponent = (this.application as StdlibComponentProvider).stdlibComponent() /** * Tries to finish an activity. * * @receiver Activity. * @return Returns `true` if the finish process has been started, `false` if * this activity was already finishing. * @since 1.0.0 */ @UiThread public fun Activity.tryFinish(): Boolean { if (this.isFinishing) { return false } this.finish() return true } /** * Hides the soft keyboard. * * @receiver Activity. * @since 1.0.0 */ @UiThread public fun Activity.hideSoftKeyboard() { val view: View? val inputMgr: InputMethodManager view = this.currentFocus if (view != null) { inputMgr = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMgr.hideSoftInputFromWindow(view.windowToken, 0) } }
0
Kotlin
1
2
8fcb1aed3bf81045274361404dc3da1b40de2142
3,523
spaceship
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/kotlinTargets.kt
arrow-kt
109,678,056
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.plugin.mpp import groovy.lang.Closure import org.gradle.api.Action import org.gradle.api.DomainObjectSet import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.artifacts.Dependency import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.AttributeContainer import org.gradle.api.internal.component.UsageContext import org.gradle.api.plugins.JavaPlugin import org.gradle.api.publish.maven.MavenPublication import org.gradle.util.ConfigureUtil import org.gradle.util.WrapUtil import org.jetbrains.kotlin.gradle.plugin.* import org.jetbrains.kotlin.gradle.utils.isGradleVersionAtLeast import org.jetbrains.kotlin.gradle.utils.lowerCamelCaseName import org.jetbrains.kotlin.konan.target.KonanTarget abstract class AbstractKotlinTarget ( final override val project: Project ) : KotlinTarget { private val attributeContainer = HierarchyAttributeContainer(parent = null) override fun getAttributes(): AttributeContainer = attributeContainer override val defaultConfigurationName: String get() = disambiguateName("default") override val apiElementsConfigurationName: String get() = disambiguateName("apiElements") override val runtimeElementsConfigurationName: String get() = disambiguateName("runtimeElements") override val artifactsTaskName: String get() = disambiguateName("jar") override fun toString(): String = "target $name ($platformType)" override val publishable: Boolean get() = true override val component: KotlinTargetComponent by lazy { if (isGradleVersionAtLeast(4, 7)) KotlinVariantWithCoordinates(this) else KotlinVariant(this) } override fun createUsageContexts(): Set<UsageContext> = setOf( KotlinPlatformUsageContext( project, this, KotlinSoftwareComponent.kotlinApiUsage(project), apiElementsConfigurationName ) ) + if (compilations.getByName(KotlinCompilation.MAIN_COMPILATION_NAME) is KotlinCompilationToRunnableFiles) setOf( KotlinPlatformUsageContext( project, this, KotlinSoftwareComponent.kotlinRuntimeUsage(project), runtimeElementsConfigurationName ) ) else emptyList() @Suppress("UNCHECKED_CAST") internal val publicationConfigureActions = WrapUtil.toDomainObjectSet(Action::class.java) as DomainObjectSet<Action<MavenPublication>> override fun mavenPublication(action: Action<MavenPublication>) { publicationConfigureActions.add(action) } override fun mavenPublication(action: Closure<Unit>) = mavenPublication(ConfigureUtil.configureUsing(action)) } internal fun KotlinTarget.disambiguateName(simpleName: String) = lowerCamelCaseName(targetName, simpleName) open class KotlinAndroidTarget( override val targetName: String, project: Project ) : AbstractKotlinTarget(project) { override var disambiguationClassifier: String? = null internal set override val platformType: KotlinPlatformType get() = KotlinPlatformType.androidJvm private val compilationFactory = KotlinJvmAndroidCompilationFactory(project, this) override val compilations: NamedDomainObjectContainer<out KotlinJvmAndroidCompilation> = project.container(compilationFactory.itemClass, compilationFactory) override fun createUsageContexts(): Set<UsageContext> { //TODO setup Android libraries publishing. This will likely require new API in the Android Gradle plugin return emptySet() } } open class KotlinWithJavaTarget( project: Project, override val platformType: KotlinPlatformType, override val targetName: String ) : AbstractKotlinTarget(project) { override var disambiguationClassifier: String? = null internal set override val defaultConfigurationName: String get() = Dependency.DEFAULT_CONFIGURATION override val apiElementsConfigurationName: String get() = JavaPlugin.API_ELEMENTS_CONFIGURATION_NAME override val runtimeElementsConfigurationName: String get() = JavaPlugin.RUNTIME_ELEMENTS_CONFIGURATION_NAME override val artifactsTaskName: String get() = JavaPlugin.JAR_TASK_NAME override val compilations: NamedDomainObjectContainer<KotlinWithJavaCompilation> = project.container(KotlinWithJavaCompilation::class.java, KotlinWithJavaCompilationFactory(project, this) ) } open class KotlinOnlyTarget<T : KotlinCompilation>( project: Project, override val platformType: KotlinPlatformType ) : AbstractKotlinTarget(project) { override lateinit var compilations: NamedDomainObjectContainer<T> internal set override lateinit var targetName: String internal set override var disambiguationClassifier: String? = null internal set } class KotlinNativeTarget( project: Project, val konanTarget: KonanTarget ) : KotlinOnlyTarget<KotlinNativeCompilation>(project, KotlinPlatformType.native) { init { attributes.attribute(konanTargetAttribute, konanTarget.name) } // TODO: Should binary files be output of a target or a compilation? override val artifactsTaskName: String get() = disambiguateName("link") override val publishable: Boolean get() = konanTarget.enabledOnCurrentHost companion object { val konanTargetAttribute = Attribute.of( "org.jetbrains.kotlin.native.target", String::class.java ) // TODO: Can we do it better? // User-visible constants val DEBUG = NativeBuildType.DEBUG val RELEASE = NativeBuildType.RELEASE val EXECUTABLE = NativeOutputKind.EXECUTABLE val FRAMEWORK = NativeOutputKind.FRAMEWORK val DYNAMIC = NativeOutputKind.DYNAMIC val STATIC = NativeOutputKind.STATIC } }
12
null
1
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
6,249
kotlin
Apache License 2.0
src/main/java/com/maddin/echtzeyt/fragments/echtzeyt/RealtimeFragment.kt
maddinkunze
673,250,698
false
{"Kotlin": 199982}
package com.maddin.echtzeyt.fragments.echtzeyt import android.annotation.SuppressLint import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.MeasureSpec import android.view.animation.Interpolator import android.view.inputmethod.InputMethodManager import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.ImageButton import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.ViewCompat import androidx.core.view.children import androidx.core.view.doOnLayout import androidx.interpolator.view.animation.FastOutSlowInInterpolator import com.maddin.echtzeyt.ECHTZEYT_CONFIGURATION import com.maddin.echtzeyt.R import com.maddin.echtzeyt.components.InstantAutoCompleteTextView import com.maddin.echtzeyt.components.RealtimeInfo import com.maddin.echtzeyt.fragments.EchtzeytForegroundFragment import com.maddin.echtzeyt.randomcode.ActivityResultSerializable import com.maddin.echtzeyt.randomcode.ClassifiedException import com.maddin.transportapi.LocatableStation import com.maddin.transportapi.RealtimeConnection import com.maddin.transportapi.Station import org.json.JSONObject import java.lang.IndexOutOfBoundsException import java.text.SimpleDateFormat import java.util.Calendar import kotlin.concurrent.thread class RealtimeFragment : EchtzeytForegroundFragment(R.layout.fragment_realtime) { private var shouldUpdateSearch = false private var nextUpdateConnections = 0L private var currentStationSearch = "" // Elements/Views private val edtSearch by lazy { safeView.findViewById<InstantAutoCompleteTextView>(R.id.edtSearch) } private val btnSearch by lazy { safeView.findViewById<ImageButton>(R.id.btnSearch) } private val btnMap by lazy { safeView.findViewById<ImageButton>(R.id.btnMap) } private val btnLike by lazy { safeView.findViewById<ImageButton>(R.id.btnLike) } private val btnBookmarks by lazy { safeView.findViewById<ImageButton>(R.id.btnBookmarks) } private val layoutConnections by lazy { safeView.findViewById<LinearLayout>(R.id.layoutScroll) } // Bookmark variables private var bookmarksOpened = false private var currentStationName = "" private var currentStation: Station? = null private var savedStations: MutableSet<String> = mutableSetOf() private val adapterSearch by lazy { ArrayAdapter<String>(safeContext, R.layout.support_simple_spinner_dropdown_item) } protected val transportSearchStationAPI by lazy { ECHTZEYT_CONFIGURATION.realtimeStationAPI!! } protected val transportRealtimeAPI by lazy { ECHTZEYT_CONFIGURATION.realtimeRealtimeAPI!! } // Everything related to other activities (such as the settings or a station selection map) protected val activitySettings by lazy { ECHTZEYT_CONFIGURATION.activitySettings } protected val activityMap by lazy { if (!ECHTZEYT_CONFIGURATION.mapsSupportLocateStations) { return@lazy null }; ECHTZEYT_CONFIGURATION.activityMap } private val activityMapLauncher by lazy { registerForActivityResult(ActivityResultSerializable<LocatableStation>(activityMap!!)) { commitToStation(it) } } // Notifications and exceptions private var currentNotification: JSONObject? = null private var lastClosedNotification = "" private var exceptions: MutableList<ClassifiedException> = mutableListOf() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initVariables() initSettings() initHandlers() initApp() initThreads() } override fun onResume() { updateConnectionsIn(0, true) super.onResume() } private fun initVariables() { // the launcher has to be registered before the activity has been started // by explicitly stating activityMapLauncher, we force lazy to initialize activityMapLauncher if (activityMap != null) { activityMapLauncher } toggleBookmarks(true) } private fun initSettings() { // Save last station? if (!preferences.contains("saveStation")) { preferences.edit().putBoolean("saveStation", true).apply() } if (preferences.getBoolean("saveStation", true)) { currentStationName = preferences.getString("station", "")?:"" } // Saved stations if (!preferences.contains("savedStations")) { preferences.edit().putStringSet("savedStations", savedStations).apply() } val savedStationsTemp = preferences.getStringSet("savedStations", savedStations) if (savedStationsTemp != null) { savedStations = savedStationsTemp } // Notifications (last closed notification -> do not show a notification that is already closed) if (!preferences.contains("lastClosedNotification")) { preferences.edit().putString("lastClosedNotification", lastClosedNotification).apply() } lastClosedNotification = preferences.getString("lastClosedNotification", lastClosedNotification).toString() } private fun initHandlers() { // Set adapter (dropdown) for the station search -> autocomplete edtSearch.setAdapter(adapterSearch) edtSearch.threshold = 0 // Show dropdown after the first character entered edtSearch.setDropDownBackgroundResource(R.drawable.dropdown) // Change background resource of the dropdown to match the rest // Listener when the main search input changes edtSearch.addOnTextChangedListener { text -> val search = text.toString() if (search == currentStationName) { edtSearch.clearFocus(); return@addOnTextChangedListener } currentStationSearch = search shouldUpdateSearch = true } // When selecting an item of the search dropdown edtSearch.addOnItemSelectedListener { clearFocus(); commitToStation() } // Update station times and close the dropdown when clicking on the search button btnSearch.setOnClickListener { clearFocus(); commitToStation() } // Open map (for selecting a station) when the map button is clicked btnMap.setOnClickListener { openStationMap() } // Toggle like when clicking the star/like button btnLike.setOnClickListener { toggleLike() } // Toggle the bookmarks/favorites menu when clicking the bookmarks button btnBookmarks.setOnClickListener { toggleBookmarks() } } private fun initThreads() { // Theoretically these threads could be combined into one, however this can be laggy, especially on older hardware // Search thread thread(start=true, isDaemon=true) { while (true) { if (!isInForeground.block(15000)) { continue } if (isDestroyed) { return@thread } if (shouldUpdateSearch) { ntUpdateSearch() } Thread.sleep(20) } } // Connections thread thread(start=true, isDaemon=true) { while (true) { if (!isInForeground.block(15000)) { continue } if (isDestroyed) { return@thread } val time = System.currentTimeMillis() if (time > nextUpdateConnections) { ntUpdateConnections() } Thread.sleep(50) } } } private fun initApp() { safeView.findViewById<View>(R.id.layoutBookmarks).alpha = 0f edtSearch.setText(currentStationName) if (currentStationName.isNotEmpty()) { edtSearch.clearFocus() } commitToStation() updateBookmarks() } /* Update all the connections for the currently selected station */ @Suppress("DEPRECATION") @SuppressLint("SetTextI18n", "SimpleDateFormat") private fun ntUpdateConnections() { // Schedule the next update // Usually the next update would be in 5 seconds val delayNextUpdate = preferences.getInt("updateEvery", 5000).toLong() // only force the update when nothing else has requested an update in the meantime (-> curUpdateTime would not be equal to nextUpdateConnections anymore) val plannedNextUpdateTime = updateConnectionsIn(delayNextUpdate, true) // Select all necessary views val txtLastUpdated = safeView.findViewById<TextView>(R.id.txtLastUpdated) val txtEmpty = safeView.findViewById<TextView>(R.id.txtEmpty) currentStationSearch = edtSearch.text.toString() val connections: List<RealtimeConnection> try { if ((currentStation == null) || (currentStation!!.name != currentStationSearch)) { val stations = transportSearchStationAPI.searchStations(currentStationSearch) if (stations.isEmpty()) { return } currentStation = stations[0] } connections = transportRealtimeAPI.getRealtimeInformation(currentStation!!).connections } catch (e: Exception) { activity?.runOnUiThread { txtLastUpdated.setTextColor(resources.getColor(R.color.error)) txtLastUpdated.alpha = 1f txtLastUpdated.animate().alpha(0.4f).setDuration(300).setStartDelay(300).start() } val classification = classifyExceptionDefault(e) exceptions.add(ClassifiedException(e, classification)) // Error -> next connection update in 1 second instead of whatever was planned updateConnectionsIn(1000, plannedNextUpdateTime == nextUpdateConnections) return } // TODO: maybe optimize this by reusing already existing RealtimeInfo views val views = connections.mapIndexed { i, it -> RealtimeInfo(safeContext, it, (i%2)>0) } activity?.runOnUiThread { txtEmpty.visibility = if (connections.isEmpty()) { View.VISIBLE } else { View.GONE } var maxLineNumberWidth = 0 var maxMinWidth = 0 var maxSecWidth = 0 layoutConnections.removeAllViews() for (view in views) { view.measureForMaximumWidth(layoutConnections) maxLineNumberWidth = maxLineNumberWidth.coerceAtLeast(view.getMaxLineNumberWidth()) maxMinWidth = maxMinWidth.coerceAtLeast(view.getMaxMinutesWidth()) maxSecWidth = maxSecWidth.coerceAtLeast(view.getMaxSecondsWidth()) } for (view in views) { view.setLineNumberMinWidth(maxLineNumberWidth) view.setMinutesMinWidth(maxMinWidth) view.setSecondsMinWidth(maxSecWidth) layoutConnections.addView(view) } txtLastUpdated.text = "${resources.getString(R.string.updateLast)} ${ SimpleDateFormat("HH:mm:ss").format( Calendar.getInstance().time ) }" txtLastUpdated.setTextColor(resources.getColor(R.color.success)) txtLastUpdated.alpha = 1f txtLastUpdated.animate().alpha(0.4f).setDuration(300).setStartDelay(300).start() } } private fun ntUpdateSearch() { try { currentStationSearch = edtSearch.text.toString() } catch (_: IndexOutOfBoundsException) { } // quite normal due to threading try { var stations = emptyList<Station>() if (currentStationSearch.isNotEmpty()) { stations = transportSearchStationAPI.searchStations(currentStationSearch) } activity?.runOnUiThread { adapterSearch.clear() if (stations.isEmpty()) { adapterSearch.notifyDataSetChanged() edtSearch.dismissDropDown() return@runOnUiThread } for (station in stations) { val stationName = station.name if (stationName == currentStationSearch) { clearFocus(); return@runOnUiThread } adapterSearch.add(stationName) } adapterSearch.notifyDataSetChanged() edtSearch.post { edtSearch.showSuggestions() } } } catch (e: Exception) { val classification = classifyExceptionDefault(e) exceptions.add(ClassifiedException(e, classification)) } shouldUpdateSearch = false } private fun sendFeedback(sendLogs: Boolean) { val i = Intent(Intent.ACTION_SEND); i.type = "message/rfc822" i.putExtra(Intent.EXTRA_EMAIL, arrayOf(resources.getString(R.string.contactEmail))) val contactSubject = "${resources.getString(R.string.appName)} - ${resources.getString(R.string.contactSubject)}" i.putExtra(Intent.EXTRA_SUBJECT, contactSubject) var contactBody = resources.getString(R.string.contactBody) if (sendLogs) { contactBody += resources.getString(R.string.contactBodyError) for (exception in exceptions) { contactBody += exception.toString() + "\n\n" } } i.putExtra(Intent.EXTRA_TEXT, contactBody) try { startActivity(Intent.createChooser(i, resources.getString(R.string.contactTitle))) } catch (e: ActivityNotFoundException) { Toast.makeText(safeContext, resources.getString(R.string.contactError), Toast.LENGTH_SHORT).show() } } private fun sendFeedback() { if (exceptions.isEmpty()) { sendFeedback(false) return } // If errors occurred, ask the user whether or not he wants to report it AlertDialog.Builder(safeContext, R.style.Theme_Echtzeyt_AlertDialog) .setTitle(R.string.sendLogsTitle) .setMessage(R.string.sendLogsText) .setIcon(R.drawable.ic_error) .setPositiveButton(R.string.sendLogsYes) { _, _ -> sendFeedback(true) } .setNegativeButton(R.string.sendLogsNo) { _, _ -> sendFeedback(false) } .show() } private fun toggleLike() { val btnLike = safeView.findViewById<ImageButton>(R.id.btnLike) if (savedStations.contains(currentStationName)) { savedStations.remove(currentStationName) btnLike.setImageResource(R.drawable.ic_star) } else { savedStations.add(currentStationName) btnLike.setImageResource(R.drawable.ic_star_filled) } preferences.edit().remove("savedStations").apply() preferences.edit().putStringSet("savedStations", savedStations).apply() updateBookmarks() } private fun toggleBookmarks() { toggleBookmarks(false) } private fun toggleBookmarks(forceClose: Boolean) { val duration = 150L val bookmarksLayout = safeView.findViewById<View>(R.id.layoutBookmarks) if (forceClose || bookmarksOpened) { ViewCompat.animate(bookmarksLayout).alpha(0f).translationY(20f).setDuration(duration).withEndAction { if (bookmarksOpened) { return@withEndAction } bookmarksLayout.visibility = View.GONE }.start() bookmarksOpened = false } else { bookmarksLayout.visibility = View.VISIBLE bookmarksLayout.animate().alpha(1f).translationY(0f).setInterpolator(FastOutSlowInInterpolator()).setDuration(duration).start() bookmarksOpened = true } } @SuppressLint("SetTextI18n") private fun updateBookmarks() { val items = safeView.findViewById<LinearLayout>(R.id.bookmarksItems) val itemsScroll = items.parent as View items.removeAllViews() val txtEmpty = safeView.findViewById<TextView>(R.id.bookmarksEmpty) if (savedStations.isEmpty()) { txtEmpty.visibility = View.VISIBLE itemsScroll.visibility = View.GONE return } txtEmpty.visibility = View.GONE itemsScroll.visibility = View.VISIBLE val inflater = LayoutInflater.from(safeContext) for (savedStation in savedStations) { val root = inflater.inflate(R.layout.comp_button_bookmark, items, false) val itemButton = root.findViewById<Button>(R.id.btnBookmarkItem) itemButton.text = " • $savedStation" itemButton.setOnClickListener { commitToStation(savedStation) } items.addView(itemButton) } } private fun commitToStation(stationName: String? = null) { val edtSearch = safeView.findViewById<TextView>(R.id.edtSearch) if (!stationName.isNullOrEmpty()) { edtSearch.text = stationName } currentStationName = edtSearch.text.toString() preferences.edit().putString("station", currentStationName).apply() safeView.findViewById<ImageButton>(R.id.btnLike).setImageResource(if (savedStations.contains(currentStationName)) { R.drawable.ic_star_filled } else { R.drawable.ic_star }) toggleBookmarks(true) updateConnections() } private fun commitToStation(station: Station?) { if (station == null) { return } currentStation = station commitToStation(station.name) } private fun scheduleNextConnectionsUpdate(next: Long, force: Boolean = false) { if ((next > nextUpdateConnections) && !force) { return } nextUpdateConnections = next } private fun updateConnectionsIn(deltaTime: Long, force: Boolean = false): Long { val now = System.currentTimeMillis() val next = (nextUpdateConnections + deltaTime).coerceIn(now, now + deltaTime) scheduleNextConnectionsUpdate(next, force) return next } private fun updateConnections() { // schedule the next connection update to be now scheduleNextConnectionsUpdate(0, true) } private fun clearFocus() { val edtSearch = safeView.findViewById<AutoCompleteTextView>(R.id.edtSearch) val focusLayout = safeView.findViewById<LinearLayout>(R.id.focusableLayout) edtSearch.dismissDropDown() focusLayout.requestFocus() (activity?.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(safeView.findViewById<View>(R.id.dividerSearch).windowToken, 0) } private fun classifyExceptionDefault(e: Exception) : String { if (e is java.net.UnknownHostException) { return "No internet connection" } return "" } protected fun openStationMap() { if (activityMap == null) { return } var station: LocatableStation? = null if (currentStation is LocatableStation) { station = currentStation as LocatableStation } activityMapLauncher.launch(station) } }
0
Kotlin
0
0
86476bcfe1a218ef281aca95a3f258b5055fc6e3
19,197
echtzeyt
MIT License
app/src/main/java/in/technowolf/ipscanner/ui/customViews/LabelValueView.kt
daksh7011
461,987,434
false
{"Kotlin": 43133, "Ruby": 956}
package `in`.technowolf.ipscanner.ui.customViews import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import androidx.annotation.DrawableRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import `in`.technowolf.ipscanner.R import `in`.technowolf.ipscanner.databinding.LabelValueViewBinding class LabelValueView @JvmOverloads constructor( context: Context, private val attrs: AttributeSet? = null, private val defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private val binding: LabelValueViewBinding = LabelValueViewBinding.inflate(LayoutInflater.from(context), this, true) @Suppress("MemberVisibilityCanBePrivate") var labelText: String = "Label" set(value) { field = value invalidate() } @Suppress("MemberVisibilityCanBePrivate") var valueText: String = "Content" set(value) { field = value invalidate() } @Suppress("MemberVisibilityCanBePrivate") @DrawableRes var startImageSrc: Int = 0 set(value) { field = value invalidate() } init { obtainAttributes() setupViews() } private fun obtainAttributes() { val typedArray = context.obtainStyledAttributes( attrs, R.styleable.LabelValueView, defStyleAttr, 0 ) labelText = typedArray.getString(R.styleable.LabelValueView_labelText).orEmpty() valueText = typedArray.getString(R.styleable.LabelValueView_valueText).orEmpty() startImageSrc = typedArray.getResourceId(R.styleable.LabelValueView_startImageSrc, 0) typedArray.recycle() } private fun setupViews() { if (startImageSrc == 0) { binding.ivStartIcon.visibility = View.GONE } else { binding.ivStartIcon.visibility = View.VISIBLE binding.ivStartIcon.setImageDrawable(ContextCompat.getDrawable(context, startImageSrc)) } binding.tvLabel.text = labelText if (valueText.isEmpty()) { binding.tvValue.visibility = View.GONE } else { binding.tvValue.visibility = View.VISIBLE binding.tvValue.text = valueText } } @Suppress("unused") fun setLabel(labelText: String) { this.labelText = labelText binding.tvLabel.text = labelText } @Suppress("unused") fun setValue(valueText: String) { this.valueText = valueText binding.tvValue.text = valueText } @Suppress("unused") fun setStartImage( @DrawableRes startImageSrc: Int ) { this.startImageSrc = startImageSrc binding.ivStartIcon.setImageDrawable(ContextCompat.getDrawable(context, startImageSrc)) } }
0
Kotlin
0
0
48eeae8fbb7f7d237a338f829c40bf6188f8deff
3,277
ip-scanner
MIT License
door-runtime/src/commonMain/kotlin/com/ustadmobile/door/replication/ReplicationSubscriptionSupervisor.kt
UstadMobile
344,538,858
false
null
package com.ustadmobile.door.replication import com.ustadmobile.door.DoorDatabaseRepository /** * Platform dependent class which will manage switching replication automatically when connectivity is gained or lost */ expect class ReplicationSubscriptionSupervisor( replicationSubscriptionManager: ReplicationSubscriptionManager, repository: DoorDatabaseRepository ) { }
0
Kotlin
0
89
58f93d9057ece78cc3f8be3d4d235c0204a15f11
381
door
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/PlaneSlash.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.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.rounded.Icons public val Icons.Bold.PlaneSlash: ImageVector get() { if (_planeSlash != null) { return _planeSlash!! } _planeSlash = Builder(name = "PlaneSlash", defaultWidth = 24.0.dp, defaultHeight = 24.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) { moveToRelative(14.802f, 21.233f) lineToRelative(-0.555f, 0.97f) curveToRelative(-0.599f, 1.098f, -1.776f, 1.797f, -3.058f, 1.797f) curveToRelative(-1.024f, 0.0f, -1.992f, -0.497f, -2.589f, -1.329f) curveToRelative(-0.598f, -0.832f, -0.758f, -1.907f, -0.431f, -2.878f) lineToRelative(0.995f, -2.796f) curveToRelative(0.277f, -0.78f, 1.135f, -1.19f, 1.916f, -0.91f) curveToRelative(0.781f, 0.277f, 1.188f, 1.136f, 0.91f, 1.916f) lineToRelative(-0.987f, 2.772f) reflectiveCurveToRelative(-0.033f, 0.225f, 0.186f, 0.225f) curveToRelative(0.183f, 0.0f, 0.352f, -0.1f, 0.439f, -0.261f) lineToRelative(0.57f, -0.996f) curveToRelative(0.411f, -0.72f, 1.327f, -0.969f, 2.047f, -0.557f) curveToRelative(0.719f, 0.411f, 0.968f, 1.328f, 0.557f, 2.047f) close() moveTo(9.0f, 14.5f) curveToRelative(0.0f, -0.828f, -0.671f, -1.5f, -1.5f, -1.5f) horizontalLineToRelative(-1.5f) verticalLineToRelative(-2.051f) lineTo(1.191f, 6.14f) curveToRelative(-0.906f, 0.356f, -1.439f, 1.383f, -1.074f, 2.372f) lineToRelative(1.883f, 3.488f) lineTo(0.125f, 15.492f) curveToRelative(-0.446f, 1.218f, 0.456f, 2.508f, 1.753f, 2.508f) horizontalLineToRelative(0.007f) curveToRelative(0.809f, 0.0f, 1.563f, -0.407f, 2.006f, -1.083f) lineToRelative(0.663f, -0.917f) horizontalLineToRelative(2.947f) curveToRelative(0.829f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f) close() moveTo(23.561f, 23.561f) curveToRelative(-0.293f, 0.293f, -0.677f, 0.439f, -1.061f, 0.439f) reflectiveCurveToRelative(-0.768f, -0.146f, -1.061f, -0.439f) lineTo(0.439f, 2.561f) curveTo(-0.146f, 1.975f, -0.146f, 1.025f, 0.439f, 0.439f) reflectiveCurveTo(1.975f, -0.146f, 2.561f, 0.439f) lineToRelative(6.625f, 6.625f) lineToRelative(-1.009f, -2.834f) curveToRelative(-0.335f, -0.994f, -0.175f, -2.069f, 0.423f, -2.901f) curveToRelative(0.597f, -0.832f, 1.565f, -1.329f, 2.589f, -1.329f) curveToRelative(1.282f, 0.0f, 2.459f, 0.699f, 3.073f, 1.823f) lineToRelative(3.536f, 6.177f) horizontalLineToRelative(2.069f) curveToRelative(2.016f, 0.0f, 3.77f, 1.436f, 4.08f, 3.339f) curveToRelative(0.19f, 1.171f, -0.137f, 2.356f, -0.898f, 3.252f) reflectiveCurveToRelative(-1.873f, 1.409f, -3.048f, 1.409f) horizontalLineToRelative(-1.879f) lineToRelative(5.439f, 5.439f) curveToRelative(0.586f, 0.586f, 0.586f, 1.535f, 0.0f, 2.121f) close() moveTo(12.87f, 10.366f) curveToRelative(-0.053f, 0.075f, -0.112f, 0.144f, -0.176f, 0.207f) lineToRelative(3.032f, 3.032f) curveToRelative(0.281f, -0.377f, 0.726f, -0.604f, 1.202f, -0.604f) horizontalLineToRelative(3.072f) curveToRelative(0.294f, 0.0f, 0.572f, -0.129f, 0.763f, -0.354f) curveToRelative(0.112f, -0.131f, 0.29f, -0.413f, 0.223f, -0.825f) curveToRelative(-0.075f, -0.461f, -0.566f, -0.821f, -1.119f, -0.821f) horizontalLineToRelative(-2.938f) curveToRelative(-0.538f, 0.0f, -1.035f, -0.288f, -1.302f, -0.755f) lineToRelative(-3.983f, -6.958f) curveToRelative(-0.103f, -0.188f, -0.271f, -0.287f, -0.454f, -0.287f) curveToRelative(-0.229f, 0.0f, -0.186f, 0.226f, -0.178f, 0.248f) lineToRelative(2.046f, 5.749f) curveToRelative(0.164f, 0.459f, 0.094f, 0.97f, -0.188f, 1.368f) close() } } .build() return _planeSlash!! } private var _planeSlash: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,329
icons
MIT License
app/src/main/java/io/github/emusute1212/makasetechoice/data/db/dao/MembersDao.kt
emusute1212
264,396,740
false
{"Kotlin": 93804}
package io.github.emusute1212.makasetechoice.data.db.dao import androidx.annotation.WorkerThread import androidx.room.* import io.github.emusute1212.makasetechoice.data.entity.Member import kotlinx.coroutines.flow.Flow @Dao interface MembersDao { @WorkerThread @Query("SELECT * FROM members") fun loadMembers(): Flow<List<Member>> @WorkerThread @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertMember(name: Member) @WorkerThread @Delete fun deleteMember(member: Member) }
3
Kotlin
0
0
1d87b045a125771f22916dd6b8d02af60ed3113a
521
MakaseteChoiceForAndroid
MIT License
src/main/kotlin/moe/irony/main/Main.kt
kokoro-aya
391,633,875
false
null
package moe.irony.main import kotlinx.cli.ArgParser import kotlinx.cli.ArgType import kotlinx.cli.default import kotlinx.cli.required import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import moe.irony.client.TorrentClient import java.nio.file.Files import java.nio.file.Paths const val PROGRAM_NAME = "./client" const val LOG_PATH_KEY = "LOG_PATH" fun main(args: Array<String>) { println("Tiny KTorrent - A simple multi-thread BitTorrent client written in Kotlin") val optionsParser = ArgParser(PROGRAM_NAME) val seed by optionsParser .option(ArgType.String, shortName = "s", description = "Path to the Torrent Seed file") .required() val output by optionsParser .option(ArgType.String, shortName = "o", description = "The output directory to which the file will be downloaded") .required() val threadnum by optionsParser .option(ArgType.Int, shortName = "n", description = "Number of downloading threads to use") .default(8) val logging by optionsParser .option(ArgType.Boolean, shortName = "l", description = "Enable logging") .default(false) val logfile by optionsParser .option(ArgType.String, shortName = "f", description = "Path to the log directory") .default("./logs/ktorrent") optionsParser.parse(args) System.setProperty(LOG_PATH_KEY, logfile) Files.createDirectories(Paths.get(output)) val client = TorrentClient( workersNum = threadnum, enableLogging = logging, ) runBlocking { client.downloadFile( torrentFilePath = seed, downloadDirectory = output ) } }
0
Kotlin
0
1
86e254087bb0d3a5ef09adef8833c146bfaeab42
1,766
Tiny-KTorrent
MIT License
ground/src/main/java/com/google/android/ground/ui/map/gms/FeatureClusterManager.kt
google
127,777,820
false
null
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.ui.map.gms import android.content.Context import com.google.android.gms.maps.GoogleMap import com.google.android.ground.model.geometry.Point import com.google.android.ground.ui.map.Feature import com.google.android.ground.ui.map.FeatureType import com.google.maps.android.clustering.ClusterManager import kotlinx.collections.immutable.toPersistentSet import timber.log.Timber /** Manages clusters of map [Feature]s. */ class FeatureClusterManager(context: Context?, map: GoogleMap) : ClusterManager<FeatureClusterItem>(context, map) { var activeLocationOfInterest: String? = null /** Manage a given map feature and add it to an appropriate cluster. */ fun addOrUpdateLocationOfInterestFeature(feature: Feature) { // TODO(#1152): Add support for polygons. if (feature.geometry !is Point) { Timber.d("can't manage a non-point") return } // TODO(#1352): Re-evaluate the rendering of points for non LOI tag types. if ( feature.tag.type == FeatureType.LOCATION_OF_INTEREST.ordinal || feature.tag.type == FeatureType.USER_POINT.ordinal ) { val clusterItem = algorithm.items.find { it.feature.tag.id == feature.tag.id } if (clusterItem != null) { updateItem(clusterItem) } else { Timber.d("adding loi to cluster manager: $feature") addItem(FeatureClusterItem(feature)) } } } /** Removes stale features from this manager's clusters. */ fun removeStaleFeatures(features: Set<Feature>) { val deletedIds = algorithm.items.map { it.feature.tag.id } - features.map { it.tag.id }.toSet() val deletedFeatures = algorithm.items.filter { deletedIds.contains(it.feature.tag.id) } Timber.d("removing points: $deletedFeatures") removeItems(deletedFeatures) } /** Removes all features from this manager's clusters. */ fun removeAllFeatures() { val deletedFeatures = algorithm.items Timber.d("removing points: $deletedFeatures") removeItems(deletedFeatures) } /** Returns all of the map [Feature]s currently managed by this cluster manager. */ fun getManagedFeatures() = algorithm.items.map { it.feature }.toPersistentSet() }
180
Kotlin
109
196
22f0ffaf532d2700bcfcec78573a5949a5cdc357
2,798
ground-android
Apache License 2.0
src/main/kotlin/io/vlang/ide/run/VlangBuildTaskRunner.kt
vlang
754,996,747
false
null
package org.vlang.ide.run import com.intellij.build.BuildViewManager import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.task.* import com.intellij.util.execution.ParametersListUtil import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.rejectedPromise import org.jetbrains.concurrency.resolvedPromise import org.vlang.configurations.VlangConfigurationUtil import org.vlang.configurations.VlangProjectSettingsConfigurable import org.vlang.debugger.runconfig.VlangDebugRunner import org.vlang.notifications.VlangErrorNotification import org.vlang.notifications.VlangNotification import org.vlang.toolchain.VlangToolchainService.Companion.toolchainSettings import java.io.File @Suppress("UnstableApiUsage") class VlangBuildTaskRunner : ProjectTaskRunner() { override fun run(project: Project, context: ProjectTaskContext, vararg tasks: ProjectTask): Promise<Result> { if (project.isDisposed) { return rejectedPromise("Project is already disposed") } val resultPromise = AsyncPromise<Result>() tasks.forEach { task -> if (task !is ProjectModelBuildTask<*>) { return resolvedPromise(TaskRunnerResults.ABORTED) } val conf = task.buildableElement as? VlangBuildConfiguration ?: return@forEach val env = conf.environment val configuration = conf.configuration invokeLater { val buildId = Any() startProcess( VlangBuildContext( project, env, "Build", buildId, buildId, ), configuration, resultPromise ) } } return resultPromise } private fun startProcess( ctx: VlangBuildContext, conf: VlangRunConfiguration, resultPromise: AsyncPromise<Result>, ) { val workingDir = File(conf.workingDir) val outputDir = if (conf.outputDir.isEmpty()) null else File(conf.outputDir) if (outputDir != null && !outputDir.exists()) { outputDir.mkdirs() } val pathToBuild = if (conf.runKind == VlangRunConfigurationEditor.RunKind.Directory) { conf.directory } else { conf.fileName } val project = conf.project val buildProgressListener = project.service<BuildViewManager>() val exe = project.toolchainSettings.toolchain().compiler() if (exe == null) { VlangErrorNotification(VlangConfigurationUtil.TOOLCHAIN_NOT_SETUP) .withTitle("Can't build V project") .withActions(VlangNotification.Action("Setup V toolchain") { _, notification -> VlangProjectSettingsConfigurable.show(project) notification.expire() }) .show() resultPromise.setResult(TaskRunnerResults.FAILURE) return } val commandLine = GeneralCommandLine() .withExePath(exe.path) .withEnvironment(conf.envs) .withParameters(pathToBuild) .withParameters("-color") .withWorkDirectory(workingDir) if (conf.production) { commandLine.withParameters("-prod") } val isDebug = ctx.environment.runner is VlangDebugRunner if (isDebug) { commandLine.withParameters("-g") // Debugging with TCC not working on Windows and Linux for some reasons if (SystemInfo.isLinux) { commandLine.withParameters("-cc", "gcc") } else if (SystemInfo.isWindows) { commandLine.withParameters("-cc", "msvc") } } val binName = binaryName(conf) if (outputDir != null) { commandLine.withParameters("-o", File(outputDir, binName).absolutePath) } else { commandLine.withParameters("-o", File(workingDir, binName).absolutePath) } val additionalArguments = ParametersListUtil.parse(conf.buildArguments) commandLine.addParameters(additionalArguments) val handler = VlangProcessHandler(commandLine) ctx.processHandler = handler ctx.workingDirectory = workingDir.toPath() handler.addProcessListener(VlangBuildAdapter(ctx, buildProgressListener)) handler.addProcessListener(object : ProcessAdapter() { override fun processTerminated(event: ProcessEvent) { if (event.exitCode == 0) { resultPromise.setResult(TaskRunnerResults.SUCCESS) } else { resultPromise.setResult(TaskRunnerResults.FAILURE) } } }) handler.startNotify() } override fun canRun(projectTask: ProjectTask): Boolean { return when (projectTask) { is ModuleBuildTask -> true is ProjectModelBuildTask<*> -> true else -> false } } companion object { fun binaryName(conf: VlangRunConfiguration): String { val name = File(conf.fileName).nameWithoutExtension if (SystemInfo.isWindows) { return "$name.exe" } return name } fun debugSymbolDir(conf: VlangRunConfiguration): String { val name = File(conf.fileName).nameWithoutExtension return "$name.dSYM" } } }
55
null
5
33
a0d2cbfa63b995d93aaca3c80676f0c2f9bef117
5,894
intellij-v
MIT License
backend/src/main/kotlin/org/example/kotlin/multiplatform/backend/Application.kt
wiyarmir
200,658,517
false
null
package org.example.kotlin.multiplatform.backend import freemarker.cache.ClassTemplateLoader import io.ktor.application.Application import io.ktor.application.call import io.ktor.application.install import io.ktor.features.CallLogging import io.ktor.features.Compression import io.ktor.features.ConditionalHeaders import io.ktor.features.ContentNegotiation import io.ktor.features.DefaultHeaders import io.ktor.features.PartialContent import io.ktor.features.StatusPages import io.ktor.freemarker.FreeMarker import io.ktor.http.HttpStatusCode import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Locations import io.ktor.response.respond import io.ktor.routing.Routing import io.ktor.serialization.json import io.ktor.util.error @UseExperimental(KtorExperimentalLocationsAPI::class) fun Application.helloworld() { install(DefaultHeaders) install(CallLogging) install(ConditionalHeaders) install(PartialContent) install(Compression) install(Locations) install(StatusPages) { exception<Throwable> { cause -> environment.log.error(cause) call.respond(HttpStatusCode.InternalServerError) } } install(ContentNegotiation) { json() } install(FreeMarker) { templateLoader = ClassTemplateLoader(javaClass.classLoader, "") } install(Routing) { index() hello() } }
6
Kotlin
18
225
e82a8db80952e860979fe5c7f6f49d49683db602
1,414
kotlin-multiplatform-template
Apache License 2.0
backend/src/test/kotlin/metrik/project/domain/repository/CommitRepositoryTest.kt
thoughtworks
351,856,572
false
{"Kotlin": 554181, "TypeScript": 146367, "Shell": 6226, "JavaScript": 6197, "Dockerfile": 2452, "HTML": 354, "Less": 341}
package metrik.project.domain.repository import metrik.infrastructure.utlils.toTimestamp import metrik.project.domain.model.Commit import metrik.project.domain.service.githubactions.GithubCommit import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest import org.springframework.context.annotation.Import import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.test.context.junit.jupiter.SpringExtension import java.time.ZoneId import java.time.ZonedDateTime @DataMongoTest @ExtendWith(SpringExtension::class) @Import(CommitRepository::class) internal class CommitRepositoryTest { @Autowired private lateinit var mongoTemplate: MongoTemplate @Autowired private lateinit var commitRepository: CommitRepository private val collectionName = "commit" @BeforeEach fun setUp(@Autowired mongoTemplate: MongoTemplate) { mongoTemplate.dropCollection(collectionName) } @Test internal fun `should get latest commit given there are records in DB`() { val pipelineId = "test pipeline" val earlyTimeStamp = ZonedDateTime.of(2021, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp() val lateTimeStamp = ZonedDateTime.of(2021, 1, 2, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp() mongoTemplate.save( Commit( timestamp = earlyTimeStamp, pipelineId = pipelineId ), collectionName ) mongoTemplate.save( Commit( timestamp = lateTimeStamp, pipelineId = pipelineId ), collectionName ) assertThat(commitRepository.getTheLatestCommit(pipelineId)!!.timestamp).isEqualTo(lateTimeStamp) } @Test internal fun `should find commit by time period`() { val pipelineId = "test pipeline" for (day in 1..5) { mongoTemplate.save( Commit( timestamp = ZonedDateTime.of(2021, 1, day, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp(), pipelineId = pipelineId ), collectionName ) } assertThat( commitRepository.findByTimePeriod( pipelineId, ZonedDateTime.of(2021, 1, 2, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp(), ZonedDateTime.of(2021, 1, 4, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp() ).size ).isEqualTo(3) } @Test internal fun `should detect duplication`() { val pipelineId = "test pipeline" mongoTemplate.save( Commit( commitId = "2", timestamp = ZonedDateTime.of(2021, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()).toTimestamp(), pipelineId = pipelineId ), collectionName ) val commitsToCheck = (1..3).map { GithubCommit(it.toString(), ZonedDateTime.now()) } assertTrue(commitRepository.hasDuplication(commitsToCheck)) } @Test internal fun `should save or replace commits`() { val pipelineId = "test pipeline" mongoTemplate.save(Commit(pipelineId = pipelineId, commitId = "1")) val commitsToSave = (1..3).map { GithubCommit(it.toString(), ZonedDateTime.now()) } commitRepository.save(pipelineId, commitsToSave.toMutableList()) assertThat(mongoTemplate.findAll(Commit::class.java).size).isEqualTo(3) } }
19
Kotlin
86
348
def6a52cb7339f6a422451710083177b9c79689a
3,811
metrik
MIT License
app/src/main/java/com/ahrenswett/pillminder/util/Navigation.kt
ahrenswett
493,091,110
false
{"Kotlin": 56201}
package com.ahrenswett.pillminder import android.util.Log import androidx.compose.runtime.Composable import androidx.navigation.NavArgument import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.ahrenswett.pillminder.ui.add_edit_bottle.AddEditBottleScreen import com.ahrenswett.pillminder.ui.add_edit_cabinet.AddEditCabinetScreen import com.ahrenswett.pillminder.ui.cabinet_list.CabinetListViewModel import com.ahrenswett.pillminder.ui.cabinet_view.CabinetViewScreen //import com.ahrenswett.pillminder.ui.composables.AddConsumableBottle import com.ahrenswett.pillminder.ui.composables.CabinetListScreen import com.ahrenswett.pillminder.util.Route import com.ahrenswett.pillminder.util.UiEvent import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.lifecycle.HiltViewModel @Composable fun Navigation(){ val navController = rememberNavController() NavHost( navController = navController, startDestination = Route.CABINET_LIST.route ){ // Navigation to CabinetList composable(Route.CABINET_LIST.route){ CabinetListScreen( onNavigate = { navController.navigate(it.route) } ) } // Navigation to AddEditCabinet composable(route = Route.ADD_EDIT_CABINET.route + "?cabinetID={cabinetID}", arguments = listOf( navArgument( name = "cabinetID"){ type = NavType.StringType defaultValue = "" } ) ){ AddEditCabinetScreen(onPopBackStack = { navController.popBackStack()}) } // Navigation to CabinetView composable(route = Route.CABINET_VIEW.route + "?cabinetID={cabinetID}", arguments = listOf( navArgument(name = "cabinetID"){ type = NavType.StringType defaultValue = "" } ) ){ Log.i("Navigation", "CabinetView") CabinetViewScreen(onPopBackStack = {navController.popBackStack()}) } // Navigate to AddEditBottle composable(route = Route.ADD_EDIT_BOTTLE.route + "?bottleID={bottleID", arguments = listOf( navArgument( name = "bottleID"){ type = NavType.StringType defaultValue = "" } ) ){ AddEditBottleScreen(onPopBackStack = { /*TODO*/ }) } // Navigate to BottleView } }
2
Kotlin
0
1
0d843ce9b0a837095de1fa8a96d4b7c5a7815c38
2,728
PillMinder
MIT License
branches/dcc/src/main/java/dgca/verifier/app/android/dcc/ui/verification/mapper/RuleValidationResultMapper.kt
eu-digital-green-certificates
355,126,967
false
null
/* * ---license-start * eu-digital-green-certificates / dgca-verifier-app-android * --- * Copyright (C) 2022 T-Systems International GmbH and all other contributors * --- * 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. * ---license-end * * Created by osarapulov on 3/17/22, 2:26 PM */ package dgca.verifier.app.android.dcc.ui.verification.mapper import dgca.verifier.app.android.dcc.model.rules.RuleValidationResultModel import dgca.verifier.app.android.dcc.ui.verification.model.RuleValidationResultCard import java.util.* fun RuleValidationResultModel.toRuleValidationResultCard(): RuleValidationResultCard { return RuleValidationResultCard( this.rule.getDescriptionFor(Locale.getDefault().language), this.result, this.current, this.rule.countryCode ) }
20
null
118
103
1e88269edf98650a17984106a7d002569fdd4031
1,332
dgca-verifier-app-android
Apache License 2.0
utilities/src/main/java/fr/jhelp/utilities/extensions/Binaries.kt
jhelpgg
264,682,891
false
null
/* * <h1>License :</h1> <br/> * The following code is deliver as is. <br/> * You can use, modify, the code as your need for any usage.<br/> * But you can't do any action that avoid me or other person use, modify this code.<br/> * The code is free for usage and modification, you can't change that fact. */ package fr.jhelp.utilities.extensions import android.util.Base64 /** * Shortcut for transform ByteArray to its base 64 version */ fun ByteArray.toBase64(): String = Base64.encodeToString(this, Base64.DEFAULT) /** * Shortcut to retrieve ByteArray serialized to base 64 */ fun String.fromBase64(): ByteArray = Base64.decode(this, Base64.DEFAULT) /** * Shortcut to read ByteArray as UTF-8 String */ fun ByteArray.fromUtf8(): String = String(this, Charsets.UTF_8) /** * Shortcut to convert String to UTF-8 ByteArray */ fun String.toUtf8(): ByteArray = this.toByteArray(Charsets.UTF_8)
4
Kotlin
0
0
d912fedb330027216113f8af9f8974e8d2b1b7b6
931
AndroidEngine3D
Apache License 2.0
utilities/src/main/java/fr/jhelp/utilities/extensions/Binaries.kt
jhelpgg
264,682,891
false
null
/* * <h1>License :</h1> <br/> * The following code is deliver as is. <br/> * You can use, modify, the code as your need for any usage.<br/> * But you can't do any action that avoid me or other person use, modify this code.<br/> * The code is free for usage and modification, you can't change that fact. */ package fr.jhelp.utilities.extensions import android.util.Base64 /** * Shortcut for transform ByteArray to its base 64 version */ fun ByteArray.toBase64(): String = Base64.encodeToString(this, Base64.DEFAULT) /** * Shortcut to retrieve ByteArray serialized to base 64 */ fun String.fromBase64(): ByteArray = Base64.decode(this, Base64.DEFAULT) /** * Shortcut to read ByteArray as UTF-8 String */ fun ByteArray.fromUtf8(): String = String(this, Charsets.UTF_8) /** * Shortcut to convert String to UTF-8 ByteArray */ fun String.toUtf8(): ByteArray = this.toByteArray(Charsets.UTF_8)
4
Kotlin
0
0
d912fedb330027216113f8af9f8974e8d2b1b7b6
931
AndroidEngine3D
Apache License 2.0
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/RecursionAwareSafePublicationLazy.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.util import com.intellij.openapi.util.RecursionManager import com.intellij.util.ObjectUtils import org.jetbrains.annotations.NonNls import java.util.concurrent.atomic.AtomicReference /** * Same as [SafePublicationLazyImpl], but doesn't cache value in case of computation recursion occurred. */ class RecursionAwareSafePublicationLazy<T>(initializer: () -> T) : Lazy<T> { @Volatile private var initializer: (() -> T)? = initializer @Suppress("UNCHECKED_CAST") private val valueRef: AtomicReference<T> = AtomicReference(UNINITIALIZED_VALUE as T) override val value: T get() { val computedValue = valueRef.get() if (computedValue !== UNINITIALIZED_VALUE) { return computedValue } val initializerValue = initializer if (initializerValue === null) { // Some thread managed to clear the initializer => it managed to set the value. return valueRef.get() } val stamp = RecursionManager.markStack() val newValue = initializerValue() if (!stamp.mayCacheNow()) { // In case of recursion don't update [valueRef] and don't clear [initializer]. return newValue } if (!valueRef.compareAndSet(UNINITIALIZED_VALUE, newValue)) { // Some thread managed to set the value. return valueRef.get() } initializer = null return newValue } override fun isInitialized(): Boolean = valueRef.get() !== UNINITIALIZED_VALUE @NonNls override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." companion object { private val UNINITIALIZED_VALUE: Any = ObjectUtils.sentinel("RecursionAwareSafePublicationLazy initial value") } }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,908
intellij-community
Apache License 2.0
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangahub/MangaHubGenerator.kt
kevin01523
612,636,298
false
null
package eu.kanade.tachiyomi.multisrc.mangahub import generator.ThemeSourceData.SingleLang import generator.ThemeSourceGenerator class MangaHubGenerator : ThemeSourceGenerator { override val themePkg = "mangahub" override val themeClass = "MangaHub" override val baseVersionCode: Int = 18 override val sources = listOf( // SingleLang("1Manga.co", "https://1manga.co", "en", isNsfw = true, className = "OneMangaCo"), // SingleLang("MangaFox.fun", "https://mangafox.fun", "en", isNsfw = true, className = "MangaFoxFun"), // SingleLang("MangaHere.onl", "https://mangahere.onl", "en", isNsfw = true, className = "MangaHereOnl"), SingleLang("MangaHub", "https://mangahub.io", "en", isNsfw = true, overrideVersionCode = 10, className = "MangaHubIo"), // SingleLang("Mangakakalot.fun", "https://mangakakalot.fun", "en", isNsfw = true, className = "MangakakalotFun"), // SingleLang("MangaNel", "https://manganel.me", "en", isNsfw = true), // SingleLang("MangaOnline.fun", "https://mangaonline.fun", "en", isNsfw = true, className = "MangaOnlineFun"), SingleLang("MangaPanda.onl", "https://mangapanda.onl", "en", className = "MangaPandaOnl"), SingleLang("MangaReader.site", "https://mangareader.site", "en", className = "MangaReaderSite"), // SingleLang("MangaToday", "https://mangatoday.fun", "en", isNsfw = true), // SingleLang("MangaTown (unoriginal)", "https://manga.town", "en", isNsfw = true, className = "MangaTownHub"), // SingleLang("MF Read Online", "https://mangafreereadonline.com", "en", isNsfw = true), // different pageListParse logic // SingleLang("OneManga.info", "https://onemanga.info", "en", isNsfw = true, className = "OneMangaInfo"), // Some chapters link to 1manga.co, hard to filter ) companion object { @JvmStatic fun main(args: Array<String>) { MangaHubGenerator().createAll() } } }
587
null
963
9
8ca7f06a4fdfbfdd66520a4798c8636274263428
1,966
tachiyomi-extensions
Apache License 2.0
android/app/src/main/kotlin/com/v2ray/ang/service/V2RayProxyOnlyService.kt
PsrkGrmez
759,525,035
false
null
package com.v2ray.ang.service import android.app.Service import android.content.Context import android.content.Intent import android.os.Build import android.os.IBinder import androidx.annotation.RequiresApi import com.v2ray.ang.util.MyContextWrapper import com.v2ray.ang.util.Utils import java.lang.ref.SoftReference class V2RayProxyOnlyService : Service(), ServiceControl { override fun onCreate() { super.onCreate() V2RayServiceManager.serviceControl = SoftReference(this) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { V2RayServiceManager.startV2rayPoint() return START_STICKY } override fun onDestroy() { super.onDestroy() V2RayServiceManager.stopV2rayPoint() } override fun getService(): Service { return this } override fun startService() { // do nothing } override fun stopService() { stopSelf() } override fun vpnProtect(socket: Int): Boolean { return true } override fun onBind(intent: Intent?): IBinder? { return null } @RequiresApi(Build.VERSION_CODES.N) override fun attachBaseContext(newBase: Context?) { val context = newBase?.let { MyContextWrapper.wrap(newBase, Utils.getLocale(newBase)) } super.attachBaseContext(context) } }
2
null
7
85
1a6d3d8e6c6edcfd3be8f23bee339e1c83ab9346
1,387
ChiselBox
MIT License
app/src/main/java/org/hsbp/androsphinx/SphinxApplication.kt
dnet
211,101,707
false
null
// SPDX-FileCopyrightText: 2019, <NAME> <<EMAIL>> // SPDX-License-Identifier: MIT package org.hsbp.androsphinx import android.app.Application @Suppress("UNUSED") class SphinxApplication : Application() { init { System.loadLibrary("sphinx") // and transitively, (lib)sodium } }
10
null
2
7
a71a0462e01998d5d391bd69b24dc87d03158e8a
296
androsphinx
BSD 3-Clause No Nuclear Warranty
src/main/kotlin/icu/windea/pls/ep/color/ParadoxColorSupport.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.lang.color import com.intellij.openapi.extensions.* import com.intellij.psi.* import icu.windea.pls.script.editor.* import java.awt.* /** * 提供对颜色的支持。(显示颜色装订线图标) * * 备注:alpha值可以小于0或者大于255(对于浮点数写法则是小于0.0或者大于1.0),表示粒子外溢的光照强度。 * * @see ParadoxScriptColorProvider */ interface ParadoxColorSupport { fun getColor(element: PsiElement): Color? fun setColor(element: PsiElement, color: Color): Boolean companion object INSTANCE { @JvmField val EP_NAME = ExtensionPointName.create<ParadoxColorSupport>("icu.windea.pls.colorSupport") fun getColor(element: PsiElement): Color? { return EP_NAME.extensionList.firstNotNullOfOrNull { it.getColor(element) } } fun setColor(element: PsiElement, color: Color) { EP_NAME.extensionList.any { it.setColor(element, color) } } } }
4
null
5
41
99e8660a23f19642c7164c6d6fcafd25b5af40ee
946
Paradox-Language-Support
MIT License
app/src/main/java/com/dreamsoftware/fitflextv/ui/screens/app/AppScreenContent.kt
sergio11
534,529,261
false
{"Kotlin": 615931}
package com.dreamsoftware.saborytv.ui.screens.app import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.navigation.NavHostController import com.dreamsoftware.saborytv.R import com.dreamsoftware.saborytv.ui.navigation.AppNavHost import com.dreamsoftware.saborytv.ui.theme.LocalNavigationProvider import com.dreamsoftware.fudge.component.FudgeTvLostNetworkConnectivityDialog import com.dreamsoftware.fudge.component.FudgeTvScreenContent @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) @Composable internal fun AppScreenContent( uiState: AppUiState, navController: NavHostController, actionListener: IAppScreenActionListener ) { with(uiState) { FudgeTvScreenContent( error = errorMessage, onErrorAccepted = actionListener::onErrorMessageCleared ) { Box { CompositionLocalProvider(LocalNavigationProvider provides navController) { AppNavHost( navController = navController ) FudgeTvLostNetworkConnectivityDialog( isVisible = !hasNetworkConnectivity, mainLogoRes = R.drawable.main_logo, onOpenSettings = actionListener::onOpenSettingsPressed, onRestartAppPressed = actionListener::onRestartAppPressed ) } } } } }
0
Kotlin
3
40
4452dcbcf3d4388144a949c65c216de5547c82a6
1,607
fitflextv_android
Apache License 2.0