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/kotlin/MainActivity2.kt
sitepoint-editors
77,063,124
true
{"Kotlin": 1583, "Java": 361}
package com.kotlineffiecienttechniques import android.support.v7.app.ActionBarActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import kotlinx.android.synthetic.main.activity_main_activity2.* public class MainActivity2 : ActionBarActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main_activity2) maintextview.text = "Hello Static Import!" val book1 = Book("123456", 43.0f, 4, "Kotlin for you", "Book on Kotlin") book1.ISBN = "998"; val book2 = Book2("12345", 45.0f, 5, "", "") book2.description = "desc"; maintextview.setOnClickListener({ view -> Toast.makeText(this, "Showing Toast", Toast.LENGTH_SHORT).show(); }) } }
0
Kotlin
0
0
f44719973c40e9f988cc6897612ebe82bef2971b
850
kotlinefficienttechniques
MIT License
app/src/main/java/net/kibotu/androiddatabases/objectbox/model/Node.kt
kibotu
189,729,497
false
null
package net.kibotu.androiddatabases.objectbox.model import net.kibotu.androiddatabases.room.model.Node /** * Tree Structure */ data class Node(var id: Int? = null, var children: List<Node>? = null)
0
Kotlin
0
0
68bd7a4e38412bf99d420c1b24987f05a7bbc64f
202
AndroidDatabases
Apache License 2.0
src/main/kotlin/com/fobgochod/git/commit/settings/GitSettingsConfigurable.kt
fobgochod
575,902,387
false
null
package com.fobgochod.git.commit.settings import com.fobgochod.git.commit.domain.option.ComponentType import com.fobgochod.git.commit.domain.option.SkipCI import com.fobgochod.git.commit.domain.option.ViewMode import com.fobgochod.git.commit.util.GitBundle import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.openapi.options.BoundSearchableConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import javax.swing.DefaultComboBoxModel /** * Git Settings Configurable * * See [Settings](https://plugins.jetbrains.com/docs/intellij/settings.html) * * See [Kotlin UI DSL Version 2](https://plugins.jetbrains.com/docs/intellij/kotlin-ui-dsl-version-2.html) * * See [Sample usages in IntelliJ Platform IDEs](https://plugins.jetbrains.com/docs/intellij/kotlin-ui-dsl.html#examples) * * @author fobgochod * @since 2023/5/24 23:43 */ internal class GitSettingsConfigurable : BoundSearchableConfigurable( GitBundle.message("configurable.display.name"), "git.commit.message" ) { private val state: GitSettings get() = GitSettings.instance private val hideTypeGroup get() = CheckboxDescriptor(ComponentType.TypeGroup.name, state::hideTypeGroup) private val hideType get() = CheckboxDescriptor(ComponentType.Type.name, state::hideType) private val hideScope get() = CheckboxDescriptor(ComponentType.Scope.name, state::hideScope) private val hideSubject get() = CheckboxDescriptor(ComponentType.Subject.name, state::hideSubject) private val hideBody get() = CheckboxDescriptor(ComponentType.Body.name, state::hideBody) private val hideWrapText get() = CheckboxDescriptor(ComponentType.WrapText.name, state::hideWrapText) private val hideBreaking get() = CheckboxDescriptor(ComponentType.Breaking.name, state::hideBreaking) private val hideIssues get() = CheckboxDescriptor(ComponentType.Issues.name, state::hideIssues) private val hideSkipCI get() = CheckboxDescriptor(ComponentType.SkipCI.name, state::hideSkipCI) override fun createPanel(): DialogPanel { return panel { row { val typeToolbar = TypeToolbarDecorator() cell(typeToolbar.decorator.createPanel()) .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) .onIsModified { typeToolbar.isModified() } .onApply { typeToolbar.apply() } .onReset { typeToolbar.reset() } }.resizableRow() group(GitBundle.message("settings.group.hidden.options")) { row { checkBox(hideTypeGroup).applyToComponent { this.toolTipText = ComponentType.TypeGroup.description() }.gap(RightGap.SMALL) checkBox(hideType).applyToComponent { this.toolTipText = ComponentType.Type.description() }.gap(RightGap.SMALL) checkBox(hideScope).applyToComponent { this.toolTipText = ComponentType.Scope.description() }.gap(RightGap.SMALL) checkBox(hideSubject).applyToComponent { this.isEnabled = false this.toolTipText = ComponentType.Subject.description() }.gap(RightGap.SMALL) checkBox(hideBody).applyToComponent { this.toolTipText = ComponentType.Body.description() }.gap(RightGap.SMALL) checkBox(hideWrapText).applyToComponent { this.toolTipText = ComponentType.WrapText.description() }.gap(RightGap.SMALL) checkBox(hideBreaking).applyToComponent { this.toolTipText = ComponentType.Breaking.description() }.gap(RightGap.SMALL) checkBox(hideIssues).applyToComponent { this.toolTipText = ComponentType.Issues.description() }.gap(RightGap.SMALL) checkBox(hideSkipCI).applyToComponent { this.toolTipText = ComponentType.SkipCI.description() }.gap(RightGap.SMALL) } } group(GitBundle.message("settings.group.common.settings")) { row { intTextField() .label(GitBundle.message("settings.common.type.count")) .bindIntText(state::typeCount).columns(5) comboBox<SkipCI>( DefaultComboBoxModel(SkipCI.values()), renderer = SimpleListCellRenderer.create("") { it.label }) .label(GitBundle.message("settings.common.skip.ci.word")) .bindItem(state::skipCI.toNullableProperty()) comboBox(ViewMode.values().toList()) .label(GitBundle.message("settings.common.view.mode")) .bindItem(state::viewMode.toNullableProperty()) } } } } }
1
Kotlin
1
4
455f4e0811843b3e3897d7ef3006b503547a5381
5,440
git-commit-message-format
Apache License 2.0
quote/src/main/java/com/pyamsoft/tickertape/quote/dig/DigViewState.kt
pyamsoft
371,196,339
false
null
package com.pyamsoft.tickertape.quote.dig import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.pyamsoft.pydroid.arch.UiViewState import com.pyamsoft.tickertape.quote.Ticker import com.pyamsoft.tickertape.stocks.api.StockChart import com.pyamsoft.tickertape.stocks.api.StockMoneyValue import com.pyamsoft.tickertape.stocks.api.StockSymbol import java.time.LocalDateTime interface DigViewState : UiViewState { val ticker: Ticker val range: StockChart.IntervalRange val currentDate: LocalDateTime val currentPrice: StockMoneyValue? } abstract class MutableDigViewState protected constructor( symbol: StockSymbol, ) : DigViewState { final override var range by mutableStateOf(StockChart.IntervalRange.ONE_DAY) final override var currentDate by mutableStateOf<LocalDateTime>(LocalDateTime.now()) final override var currentPrice by mutableStateOf<StockMoneyValue?>(null) final override var ticker by mutableStateOf( Ticker( symbol = symbol, quote = null, chart = null, ), ) }
5
Kotlin
0
1
fa630755b2f2f7f81b5df592541d22b7ea35ac76
1,154
tickertape
Apache License 2.0
save-backend/src/main/kotlin/com/saveourtool/save/backend/service/TestsSourceVersionService.kt
saveourtool
300,279,336
false
null
package com.saveourtool.save.backend.service import com.saveourtool.save.backend.repository.TestSuitesSourceRepository import com.saveourtool.save.backend.repository.TestsSourceSnapshotRepository import com.saveourtool.save.backend.repository.TestsSourceVersionRepository import com.saveourtool.save.backend.repository.UserRepository import com.saveourtool.save.backend.storage.TestsSourceSnapshotStorage import com.saveourtool.save.entities.TestsSourceSnapshot import com.saveourtool.save.entities.TestsSourceVersion import com.saveourtool.save.entities.TestsSourceVersion.Companion.toEntity import com.saveourtool.save.test.* import com.saveourtool.save.test.TestsSourceVersionInfo import com.saveourtool.save.utils.* import org.slf4j.Logger import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional /** * Service for [TestsSourceVersionInfo] */ @Service class TestsSourceVersionService( private val snapshotRepository: TestsSourceSnapshotRepository, private val versionRepository: TestsSourceVersionRepository, private val userRepository: UserRepository, private val snapshotStorage: TestsSourceSnapshotStorage, private val sourceRepository: TestSuitesSourceRepository, ) { /** * @param snapshotId [TestsSourceSnapshot.id] * @return [TestsSourceSnapshot] found by provided values */ fun getSnapshotEntity( snapshotId: Long, ): TestsSourceSnapshot = snapshotRepository.getByIdOrNotFound(snapshotId) /** * @param sourceId ID of [com.saveourtool.save.entities.TestSuitesSource] * @param commitId [TestsSourceSnapshot.commitId] * @return [TestsSourceSnapshotDto] found by provided values */ fun findSnapshot( sourceId: Long, commitId: String, ): TestsSourceSnapshotDto? = snapshotRepository.findBySourceIdAndCommitId(sourceId, commitId)?.toDto() /** * @param sourceId * @param version * @return true if there is [TestsSourceVersionDto] with provided values, otherwise -- false */ @Suppress("FUNCTION_BOOLEAN_PREFIX") fun doesVersionExist( sourceId: Long, version: String, ): Boolean = versionRepository.findBySnapshot_SourceIdAndName(sourceId, version) != null /** * @param organizationName * @param sourceName * @return list of [TestsSourceVersionInfo] found by provided values */ fun getAllAsInfo( organizationName: String, sourceName: String? = null, ): List<TestsSourceVersionInfo> { val testsSourceVersions = sourceName ?.let { versionRepository.findAllBySnapshot_Source_OrganizationNameAndSnapshot_SourceName(organizationName, it) } ?: versionRepository.findAllBySnapshot_Source_OrganizationName(organizationName) return testsSourceVersions.map(TestsSourceVersion::toInfo) } /** * @param organizationName * @param sourceName * @return all fetched version of [TestsSourceVersion] found by provided values */ fun getAllVersions( organizationName: String, sourceName: String, ): Set<String> = versionRepository.findAllBySnapshot_Source_OrganizationNameAndSnapshot_SourceName( organizationName, sourceName ).mapTo(LinkedHashSet(), TestsSourceVersion::name) /** * @param snapshotId * @return all fetched version of [TestsSourceVersion] found by provided values */ fun getAllVersions( snapshotId: Long, ): Set<String> = versionRepository.findAllBySnapshotId(snapshotId).mapTo(LinkedHashSet(), TestsSourceVersion::name) /** * Deletes [TestsSourceVersionDto] and [TestsSourceSnapshotDto] if there are no another [TestsSourceVersionDto] related to it * * @param organizationName * @param sourceName * @param version */ @Transactional fun delete( organizationName: String, sourceName: String, version: String, ) { val versionEntity = versionRepository.findBySnapshot_Source_OrganizationNameAndSnapshot_SourceNameAndName( organizationName = organizationName, sourceName = sourceName, version = version, ).orNotFound { "Not found ${TestsSourceVersion::class.simpleName} with version $version in $organizationName/$sourceName" } doDelete(versionEntity) } private fun doDelete(versionEntity: TestsSourceVersion) { versionRepository.delete(versionEntity) val snapshotEntity = versionEntity.snapshot if (versionRepository.findAllBySnapshotId(snapshotEntity.requiredId()).isEmpty()) { val snapshot = snapshotEntity.toDto() snapshotStorage.delete(snapshot) .map { deleted -> if (!deleted) { log.warn { "Failed to delete snapshot: $snapshot" } } } .subscribe() } } /** * Saves [TestsSourceVersion] created from provided [TestsSourceVersionDto] * * @param version the version to save. * @return `true` if the [version] was saved, `false` if the version with * the same [name][TestsSourceVersionDto.name] and numeric * [snapshot id][TestsSourceVersionDto.snapshotId] already exists. */ @Suppress("FUNCTION_BOOLEAN_PREFIX") @Transactional fun save( version: TestsSourceVersionDto, ): Boolean { versionRepository.findBySnapshotIdAndName(version.snapshotId, version.name)?.run { require(snapshot.requiredId() == version.snapshotId) { "Try to save a new $version, but already existed another one linked to another snapshotId: ${toDto()}" } return false } val entity = version.toEntity( snapshotResolver = snapshotRepository::getByIdOrNotFound, userResolver = userRepository::getByIdOrNotFound ) val savedEntity = versionRepository.save(entity) // need to update latestFetchedVersion in source savedEntity.snapshot.source .apply { latestFetchedVersion = savedEntity.name } .let { sourceRepository.save(it) } return true } companion object { private val log: Logger = getLogger<TestsSourceVersionService>() } }
201
null
3
38
e101105f8e449253d5fbe81ece2668654d08639f
6,558
save-cloud
MIT License
src/test/kotlin/no/nav/syfo/api/JobApiSpek.kt
navikt
303,972,532
false
null
package no.nav.syfo.api import io.ktor.application.* import io.ktor.features.* import io.ktor.http.* import io.ktor.routing.* import io.ktor.server.testing.* import io.mockk.coEvery import io.mockk.mockk import io.mockk.verify import no.nav.syfo.api.job.registerJobTriggerApi import no.nav.syfo.api.job.urlPathJobTrigger import no.nav.syfo.consumer.narmesteLeder.NarmesteLederService import no.nav.syfo.consumer.syfomotebehov.SyfoMotebehovConsumer import no.nav.syfo.db.domain.PlanlagtVarsel import no.nav.syfo.db.domain.VarselType import no.nav.syfo.db.storePlanlagtVarsel import no.nav.syfo.getTestEnv import no.nav.syfo.job.VarselSender import no.nav.syfo.kafka.producers.brukernotifikasjoner.BeskjedKafkaProducer import no.nav.syfo.kafka.producers.dinesykmeldte.DineSykmeldteHendelseKafkaProducer import no.nav.syfo.service.AccessControl import no.nav.syfo.service.ArbeidsgiverNotifikasjonService import no.nav.syfo.service.SendVarselService import no.nav.syfo.testutil.EmbeddedDatabase import no.nav.syfo.testutil.mocks.* import no.nav.syfo.util.contentNegotationFeature import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.LocalDate object JobApiSpek : Spek({ defaultTimeout = 20000L val testEnv = getTestEnv() describe("JobTriggerApi test") { val embeddedDatabase by lazy { EmbeddedDatabase() } val accessControl = mockk<AccessControl>() val beskjedKafkaProducer = mockk<BeskjedKafkaProducer>() val arbeidsgiverNotifikasjonService = mockk<ArbeidsgiverNotifikasjonService>() val dineSykmeldteHendelseKafkaProducer = mockk<DineSykmeldteHendelseKafkaProducer>() val narmesteLederService = mockk<NarmesteLederService>() val syfoMotebeovConsumer = mockk<SyfoMotebehovConsumer>() coEvery { accessControl.getFnrIfUserCanBeNotified(aktorId) } returns fnr1 coEvery { accessControl.getFnrIfUserCanBeNotified(aktorId2) } returns fnr2 coEvery { accessControl.getFnrIfUserCanBeNotified(aktorId3) } returns null coEvery { beskjedKafkaProducer.sendBeskjed(any(), any(), any(), any()) } returns Unit val sendVarselService = SendVarselService( beskjedKafkaProducer, dineSykmeldteHendelseKafkaProducer, narmesteLederService, accessControl, testEnv.urlEnv, syfoMotebeovConsumer, arbeidsgiverNotifikasjonService, ) val varselSender = VarselSender(embeddedDatabase, sendVarselService, testEnv.toggleEnv, testEnv.appEnv) with(TestApplicationEngine()) { start() application.install(ContentNegotiation, contentNegotationFeature()) application.routing { registerJobTriggerApi(varselSender) } it("esyfovarsel-job trigger utsending av 2 varsler") { listOf( PlanlagtVarsel(fnr1, aktorId, orgnummer, setOf("1"), VarselType.MER_VEILEDNING), PlanlagtVarsel(fnr2, aktorId2, orgnummer, setOf("2"), VarselType.AKTIVITETSKRAV), PlanlagtVarsel(fnr2, aktorId2, orgnummer, setOf("3"), VarselType.MER_VEILEDNING, LocalDate.now().plusDays(1)), PlanlagtVarsel(fnr3, aktorId3, orgnummer, setOf("4"), VarselType.AKTIVITETSKRAV) ).forEach { embeddedDatabase.storePlanlagtVarsel(it) } with(handleRequest(HttpMethod.Post, urlPathJobTrigger)) { response.status()?.isSuccess() shouldBeEqualTo true verify(exactly = 2) { beskjedKafkaProducer.sendBeskjed(any(), any(), any(), any()) } } } } } })
2
Kotlin
0
0
687dc87cc4bb54740bf83569d6bd4cd1269cc23f
3,810
esyfovarsel
MIT License
app/src/main/java/com/example/inventory/ui/item/ItemEntryScreen.kt
BrunoCRezende
862,005,793
false
{"Kotlin": 74437}
/* * Copyright (C) 2023 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 * * 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.example.inventory.ui.item import android.app.DatePickerDialog import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.viewmodel.compose.viewModel import com.example.inventory.InventoryTopAppBar import com.example.inventory.R import com.example.inventory.ui.AppViewModelProvider import com.example.inventory.ui.navigation.NavigationDestination import com.example.inventory.ui.theme.InventoryTheme import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* object ItemEntryDestination : NavigationDestination { override val route = "item_entry" override val titleRes = R.string.item_entry_title } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ItemEntryScreen( navigateBack: () -> Unit, onNavigateUp: () -> Unit, canNavigateBack: Boolean = true, viewModel: ItemEntryViewModel = viewModel(factory = AppViewModelProvider.Factory) ) { val coroutineScope = rememberCoroutineScope() Scaffold( topBar = { InventoryTopAppBar( title = stringResource(ItemEntryDestination.titleRes), canNavigateBack = canNavigateBack, navigateUp = onNavigateUp ) } ) { innerPadding -> ItemEntryBody( itemUiState = viewModel.itemUiState, onItemValueChange = viewModel::updateUiState, onSaveClick = { coroutineScope.launch { viewModel.saveItem() navigateBack() } }, modifier = Modifier .padding( start = innerPadding.calculateStartPadding(LocalLayoutDirection.current), top = innerPadding.calculateTopPadding(), end = innerPadding.calculateEndPadding(LocalLayoutDirection.current), ) .verticalScroll(rememberScrollState()) .fillMaxWidth() ) } } @Composable fun ItemEntryBody( itemUiState: ItemUiState, onItemValueChange: (ItemDetails) -> Unit, onSaveClick: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier.padding(dimensionResource(id = R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_large)) ) { ItemInputForm( itemDetails = itemUiState.itemDetails, onValueChange = onItemValueChange, modifier = Modifier.fillMaxWidth() ) Button( onClick = onSaveClick, enabled = itemUiState.isEntryValid, shape = MaterialTheme.shapes.small, modifier = Modifier.fillMaxWidth() ) { Text(text = stringResource(R.string.save_action)) } } } @Composable fun ItemInputForm( itemDetails: ItemDetails, modifier: Modifier = Modifier, onValueChange: (ItemDetails) -> Unit = {}, enabled: Boolean = true ) { val context = LocalContext.current val dateFormat = remember { SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) } val formattedDate = remember(itemDetails.data) { itemDetails.data?.let { dateFormat.format(it) } ?: "" } Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_medium)) ) { OutlinedTextField( value = itemDetails.name, onValueChange = { onValueChange(itemDetails.copy(name = it)) }, label = { Text(stringResource(R.string.item_name_req)) }, colors = OutlinedTextFieldDefaults.colors( focusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, unfocusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, ), modifier = Modifier.fillMaxWidth(), enabled = enabled, singleLine = true ) OutlinedTextField( value = itemDetails.descricao, onValueChange = { onValueChange(itemDetails.copy(descricao = it)) }, label = { Text(stringResource(R.string.item_descricao_req)) }, colors = OutlinedTextFieldDefaults.colors( focusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, unfocusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, ), modifier = Modifier.fillMaxWidth(), enabled = enabled, singleLine = false ) OutlinedTextField( value = formattedDate, onValueChange = { }, label = { Text(stringResource(R.string.item_data_req)) }, colors = OutlinedTextFieldDefaults.colors( focusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, unfocusedContainerColor = MaterialTheme.colorScheme.secondaryContainer, disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, ), modifier = Modifier .fillMaxWidth() .clickable { val calendar = Calendar.getInstance() val datePicker = DatePickerDialog( context, { _, year, month, dayOfMonth -> val selectedDate = Calendar.getInstance() selectedDate.set(year, month, dayOfMonth) onValueChange(itemDetails.copy(data = selectedDate.time)) }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) datePicker.show() }, enabled = enabled, singleLine = true, readOnly = true ) if (enabled) { Text( text = stringResource(R.string.required_fields), modifier = Modifier.padding(start = dimensionResource(id = R.dimen.padding_medium)) ) } } } @Preview(showBackground = true) @Composable private fun ItemEntryScreenPreview() { InventoryTheme { ItemEntryBody(itemUiState = ItemUiState( ItemDetails( name = "Item name", descricao = "blablablabla", data = Date() ) ), onItemValueChange = {}, onSaveClick = {}) } }
0
Kotlin
0
0
8a87e1e263901a5b2c8f63031d95be9208ddf2e6
8,033
App-SQLite---Android-Developer
Apache License 2.0
client/core/persistence/src/commonTest/kotlin/com/oztechan/ccc/client/core/persistence/PersistenceTest.kt
Oztechan
102,633,334
false
null
package com.oztechan.ccc.client.core.persistence import com.oztechan.ccc.client.core.persistence.error.UnsupportedPersistenceException import com.oztechan.ccc.client.core.persistence.fakes.Fakes.KEY import com.oztechan.ccc.client.core.persistence.fakes.Fakes.mockBoolean import com.oztechan.ccc.client.core.persistence.fakes.Fakes.mockFloat import com.oztechan.ccc.client.core.persistence.fakes.Fakes.mockInt import com.oztechan.ccc.client.core.persistence.fakes.Fakes.mockLong import com.oztechan.ccc.client.core.persistence.fakes.Fakes.mockString import com.russhwolf.settings.Settings import io.mockative.Mock import io.mockative.classOf import io.mockative.configure import io.mockative.every import io.mockative.mock import io.mockative.verify import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith internal class PersistenceTest { private val persistence: Persistence by lazy { PersistenceImpl(settings) } @Mock private val settings = configure(mock(classOf<Settings>())) { stubsUnitByDefault = true } @Test fun `getValue returns the same type`() { every { settings.getFloat(KEY, mockFloat) } .returns(mockFloat) every { settings.getBoolean(KEY, mockBoolean) } .returns(mockBoolean) every { settings.getInt(KEY, mockInt) } .returns(mockInt) every { settings.getString(KEY, mockString) } .returns(mockString) every { settings.getLong(KEY, mockLong) } .returns(mockLong) assertEquals(mockFloat, persistence.getValue(KEY, mockFloat)) assertEquals(mockBoolean, persistence.getValue(KEY, mockBoolean)) assertEquals(mockInt, persistence.getValue(KEY, mockInt)) assertEquals(mockString, persistence.getValue(KEY, mockString)) assertEquals(mockLong, persistence.getValue(KEY, mockLong)) verify { settings.getFloat(KEY, mockFloat) } .wasInvoked() verify { settings.getBoolean(KEY, mockBoolean) } .wasInvoked() verify { settings.getInt(KEY, mockInt) } .wasInvoked() verify { settings.getString(KEY, mockString) } .wasInvoked() verify { settings.getLong(KEY, mockLong) } .wasInvoked() } @Test fun `setValue sets the same type`() { persistence.setValue(KEY, mockFloat) persistence.setValue(KEY, mockBoolean) persistence.setValue(KEY, mockInt) persistence.setValue(KEY, mockString) persistence.setValue(KEY, mockLong) verify { settings.putFloat(KEY, mockFloat) } .wasInvoked() verify { settings.putBoolean(KEY, mockBoolean) } .wasInvoked() verify { settings.putInt(KEY, mockInt) } .wasInvoked() verify { settings.putString(KEY, mockString) } .wasInvoked() verify { settings.putLong(KEY, mockLong) } .wasInvoked() } @Test fun `setValue throw UnsupportedPersistenceException when unsupported type tried to saved or read`() { val mockObject = object {} assertFailsWith(UnsupportedPersistenceException::class) { persistence.setValue(KEY, mockObject) } assertFailsWith(UnsupportedPersistenceException::class) { persistence.getValue(KEY, mockObject) } } }
29
null
30
331
6e693e802e78b411051be9c4398df2bd60023c46
3,393
CCC
Apache License 2.0
urbanairship-debug/src/main/java/com/urbanairship/debug/event/BindingAdapters.kt
tmckeown-rsc
193,259,287
false
{"INI": 1, "Markdown": 12, "Shell": 3, "Batchfile": 1, "Proguard": 6, "Java": 621, "Kotlin": 49, "Python": 1, "Java Properties": 3, "C#": 2, "CSS": 1}
/* Copyright Airship and Contributors */ package com.urbanairship.debug.event import android.databinding.BindingAdapter import android.graphics.drawable.ColorDrawable import android.support.annotation.ColorInt import android.support.design.chip.Chip import android.support.design.widget.FloatingActionButton import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.text.format.DateUtils import android.view.View import android.widget.TextView @BindingAdapter("fabVisibility") fun bindFabVisibility(fab: FloatingActionButton, visible: Boolean) { if (visible) { fab.show() } else { fab.hide() } } @BindingAdapter("visible") fun showHide(view: View, show: Boolean) { view.visibility = if (show) View.VISIBLE else View.GONE } @BindingAdapter("backgroundTint") fun bindBackgroundTint(view: View, @ColorInt color: Int) { DrawableCompat.setTint(view.background, color) } @BindingAdapter("formatTime") fun bindFormatTime(view: TextView, time: Long) { view.text = DateUtils.formatDateTime(view.context, time, DateUtils.FORMAT_ABBREV_ALL or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE) } @BindingAdapter("chipIconColor") fun bindChipIconColor(view: Chip, @ColorInt color: Int) { view.chipIcon = ColorDrawable(color) } @BindingAdapter("eventFilter") fun bindEventFilter(view: Chip, eventFilter: EventFilter) { view.text = EventInfo.getEventName(view.context, eventFilter.type) view.chipBackgroundColor = ContextCompat.getColorStateList(view.context, EventInfo.getColorRes(eventFilter.type)) } @BindingAdapter("eventName") fun bindEventName(view: TextView, item: EventItem) { view.text = EventInfo.getDetailedEventName(view.context, item.type, item.payload) } @BindingAdapter("checkedIconTint") fun bindChipFilterIconTint(view: Chip, @ColorInt color: Int) { view.checkedIcon?.let { DrawableCompat.setTint(it, color) } }
1
null
1
1
5f672d6669f2191c73f5dde5071e1a7bab09579c
1,968
android-library
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/contactdiary/model/ContactDiaryPerson.kt
si-covid-19
286,833,811
false
null
package de.rki.coronawarnapp.contactdiary.model import de.rki.coronawarnapp.util.lists.HasStableId import java.util.Locale interface ContactDiaryPerson : HasStableId { val personId: Long var fullName: String val phoneNumber: String? val emailAddress: String? } fun List<ContactDiaryPerson>.sortByNameAndIdASC(): List<ContactDiaryPerson> = this.sortedWith(compareBy({ it.fullName.toLowerCase(Locale.ROOT) }, { it.personId }))
6
null
8
15
5a3b4be63b5b030da49216a0132a3979cad89af1
448
ostanizdrav-android
Apache License 2.0
api/src/main/kotlin/de/axelrindle/pocketknife/PocketConfig.kt
axelrindle
136,759,008
false
{"Kotlin": 78917, "Java": 185}
package de.axelrindle.pocketknife import org.apache.commons.io.IOUtils import org.bukkit.configuration.InvalidConfigurationException import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.java.JavaPlugin import java.io.* import java.nio.charset.StandardCharsets /** * A helper class for easily managing and accessing config files. * Eliminates the need for manually handling loading and saving. * * @see YamlConfiguration * @since 1.0.0 */ class PocketConfig( private val plugin: JavaPlugin ) { private val configFiles: HashMap<String, String> = HashMap() private val configInstances: HashMap<String, YamlConfiguration> = HashMap() private fun createDefaultFile(name: String, file: File, defaults: InputStream?) { if (file.exists()) return plugin.logger.info("Creating new config file '$name' at ${file.absolutePath}") if (plugin.dataFolder.exists().not() && plugin.dataFolder.mkdirs().not()) { plugin.logger.severe("Failed to create the directory '${plugin.dataFolder.absolutePath}'!") return } // check whether to create parent directories if (plugin.dataFolder.absolutePath != file.parentFile?.absolutePath) { file.parentFile.mkdirs() } if (file.createNewFile().not()) { plugin.logger.severe("Failed to create a config file for '$name'!") return } if (defaults != null) { val string = IOUtils.toString(defaults, StandardCharsets.UTF_8) FileWriter(file).use { IOUtils.write(string, it) } } } @JvmSynthetic internal fun register(directory: File, name: String, defaults: InputStream? = null) { // we don't want duplicated or overwritten data if (configFiles.containsKey(name)) throw IllegalArgumentException("A config named '$name' is already registered!") // store pathname val file = File(directory, "$name.yml") configFiles[name] = file.absolutePath // create a new config instance val config = YamlConfiguration() config.options().apply { indent(2) copyDefaults(true) } // create default file if given createDefaultFile(name, file, defaults) // apply defaults to the config instance if (defaults != null) { InputStreamReader(defaults).use { config.addDefaults(YamlConfiguration.loadConfiguration(it)) } defaults.close() } // load and store config instance try { config.load(file) configInstances[name] = config } catch (e: IOException) { plugin.logger.severe("Failed to load the configuration from file '${file.absolutePath}'!") e.printStackTrace() } catch (e: InvalidConfigurationException) { plugin.logger.severe("The configuration file '${file.absolutePath}' is invalid!") } } /** * Registers a new config file. * * @param name The name of the file. * @param defaults An optional [InputStream] from which default config entries can be read. * * @throws IllegalArgumentException If a config is already registered. * @throws IOException If an I/O error occurs. */ fun register(name: String, defaults: InputStream? = null) { register(plugin.dataFolder, name, defaults) } /** * Retrieves a list of all registered config files. * * @return An [ArrayList] holding a list of registered config file names. * @since 2.2.0 */ fun list(): ArrayList<String> { return ArrayList(configFiles.keys) } /** * @return A [YamlConfiguration] instance for the given config, or `null`. */ fun access(name: String): YamlConfiguration? { return configInstances[name] } /** * Reloads a configuration from the disk. * * @param name The config to reload. * * @throws IllegalArgumentException If the given config was not found. */ fun reload(name: String) { // make sure the given config exists if (!configInstances.containsKey(name)) throw IllegalArgumentException("No config '$name' is registered!") // load from the disk and overwrite the mapped value val config = YamlConfiguration.loadConfiguration(File(configFiles[name])) val defaults = configInstances[name]?.defaults // preserve initially loaded defaults if (defaults != null) config.setDefaults(defaults) configInstances[name] = config } /** * Reloads all config files from the disk. * * @see reload * @since 1.3.0 */ fun reloadAll() { configFiles.keys.forEach(this::reload) } /** * Edit a configuration. Saving is done automatically. * * @param name The config to edit. * * @throws IllegalArgumentException If the given config was not found. * @throws IOException If an I/O error occurs while saving the changes to disk. */ fun edit(name: String, handler: (config: YamlConfiguration) -> Unit) { // make sure the given config exists if (!configInstances.containsKey(name)) throw IllegalArgumentException("No config '$name' is registered!") // apply changes val config = configInstances[name]!! handler(config) // save to disk val file = configFiles[name]!! config.save(file) } }
1
Kotlin
1
1
6b7537fee337d8403cec7030116b3068636b95ae
5,564
PocketKnife
Apache License 2.0
app/src/main/java/ajar/huzefa/olaplay/data/PlaylistDao.kt
huzefaraja
115,239,147
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 38, "XML": 29, "Java": 1}
package ajar.huzefa.olaplay.data import android.arch.persistence.room.* /** * This item is not currently in use */ @Dao interface PlaylistDao { @Query("SELECT * FROM playlist") fun all(): List<Playlist> @Query("SELECT * FROM playlist WHERE id=(:id)") fun byId(id: Long): List<Playlist> @Insert(onConflict = OnConflictStrategy.ABORT) fun insert(vararg Histories: Playlist): Array<Long> @Insert(onConflict = OnConflictStrategy.ABORT) fun insert(Histories: Playlist): Long @Update(onConflict = OnConflictStrategy.REPLACE) fun update(vararg Histories: Playlist) @Delete fun delete(Playlist: Playlist) }
1
null
1
1
779098baaf99b5a31389ec08ef33dff4a959f19e
657
ola_play
MIT License
app/src/main/java/ir/esmaeili/stopcar/ui/fragments/newcar/NewCarViewModel.kt
BasetEsmaeili
250,985,369
false
null
package ir.esmaeili.stopcar.ui.fragments.newcar import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.observers.DisposableSingleObserver import io.reactivex.schedulers.Schedulers import ir.esmaeili.stopcar.models.Car import ir.esmaeili.stopcar.models.Response import ir.esmaeili.stopcar.repository.RepositoryManager import ir.esmaeili.stopcar.ui.base.BaseViewModel import ir.esmaeili.stopcar.utils.Constants class NewCarViewModel( repositoryManager: RepositoryManager, private val savedStateHandle: SavedStateHandle ) : BaseViewModel(repositoryManager) { private val newCarNavigatorLiveData: MutableLiveData<NewCarNavigator> = MutableLiveData() private val newCarLiveData: MutableLiveData<Response<Boolean>> = MutableLiveData() fun getCarPlaquePartTwo(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_PART_TWO, "") } fun getNewCarNavigator(): MutableLiveData<NewCarNavigator> { return newCarNavigatorLiveData } fun setNewCarNavigator(action: NewCarNavigator) { this.newCarNavigatorLiveData.value = action } fun getCarColor(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_CAR_COLOR, "") } fun setCarColor(color: String) { this.savedStateHandle.set(Constants.KEY_CAR_COLOR, color) } fun setCarPlaquePartTwo(partTwO: String) { this.savedStateHandle.set(Constants.KEY_PART_TWO, partTwO) } fun getCarPlaqueKeyWord(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_KEY_WORD, "") } fun setCarPlaqueKeyWord(keyWord: String) { this.savedStateHandle.set(Constants.KEY_KEY_WORD, keyWord) } fun getCarPlaquePartThreeCode(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_PART_THREE_CODE, "") } fun setCarPlaquePartThreeCode(partThree: String) { this.savedStateHandle.set(Constants.KEY_PART_THREE_CODE, partThree) } fun getCarPlaqueIrCode(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_IR_CODE, "") } fun setCarPlaqueIrCode(irCode: String) { this.savedStateHandle.set(Constants.KEY_IR_CODE, irCode) } fun getCarName(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_CAR_NAME, "") } fun setCarName(carName: String) { this.savedStateHandle.set(Constants.KEY_CAR_NAME, carName) } fun getCarModel(): LiveData<String> { return this.savedStateHandle.getLiveData(Constants.KEY_CAR_MODEL, "") } fun setCarModel(carModel: String) { this.savedStateHandle.set(Constants.KEY_CAR_MODEL, carModel) } fun insertCar() { val car = Car() car.carName = getCarName().value car.carModel = getCarModel().value car.carColor = getCarColor().value car.carPlaqueIrCode = getCarPlaqueIrCode().value car.carPlaquePartThree = getCarPlaquePartThreeCode().value car.carPlaqueKeyWord = getCarPlaqueKeyWord().value car.carPlaquePartTwo = getCarPlaquePartTwo().value val observer = object : DisposableSingleObserver<Boolean>() { override fun onSuccess(t: Boolean) { setNewCarLiveData(Response.Success(t)) } override fun onError(e: Throwable) { setNewCarLiveData(Response.Error(e)) } } compositeDisposable .add(repositoryManager.insertCar(car) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .doOnSubscribe { setNewCarLiveData(Response.Loading()) } .subscribeWith(observer)) } fun isNewCarInputsNotEmpty(): Boolean { return getCarName().value!!.isNotEmpty() && getCarModel().value!!.isNotBlank() && getCarColor().value!!.isNotEmpty() && getCarPlaqueIrCode().value!!.isNotEmpty() && getCarPlaquePartThreeCode().value!!.isNotEmpty() && getCarPlaqueKeyWord().value!! .isNotEmpty() && getCarPlaquePartTwo().value!!.isNotEmpty() } fun getNewCarLiveData(): MutableLiveData<Response<Boolean>> { return this.newCarLiveData } private fun setNewCarLiveData(response: Response<Boolean>) { this.newCarLiveData.value = response } }
1
null
3
8
8287613ca3afb090f52e9bed02671a0375d1c3d9
4,577
StopCar-Redesigned
Apache License 2.0
app/src/main/java/com/ggslk/ggslk/adapter/CategoryRecyclerAdapter.kt
ivantha
130,317,391
false
null
package com.ggslk.ggslk.adapter import android.content.Context import android.support.constraint.ConstraintLayout import android.support.v4.app.FragmentManager import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.android.volley.DefaultRetryPolicy import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.ggslk.ggslk.R import com.ggslk.ggslk.common.Session import com.ggslk.ggslk.fragment.CategoryArticlesFragment import com.ggslk.ggslk.model.Article import com.ggslk.ggslk.model.Author import com.ggslk.ggslk.model.Category import com.squareup.picasso.Picasso import org.json.JSONException class CategoryRecyclerAdapter(private val context: Context, private val categories: List<Category>, private val fragmentManager: FragmentManager) : RecyclerView.Adapter<CategoryRecyclerAdapter.CategoryViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_category, parent, false) return CategoryViewHolder(v) } override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) { holder.cardViewBackground.setBackgroundColor(Session.categoryColors[position % Session.categoryColors.size]) holder.category = categories[position] holder.categoryTitle.text = categories[position].title var featuredArticle = categories[position].featuredArticle if (featuredArticle != null) { Picasso.get().load(featuredArticle.imageUrl).fit().centerCrop().into(holder.categoryArticleImageView) holder.categoryArticleName.text = featuredArticle.title holder.categoryArticleAuthor.text = featuredArticle.author!!.name } else { val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, "https://ggslk.com/api/get_category_posts?slug=" + categories[position].slug + "&count=1", null, Response.Listener { response -> try { val firstPost = response.getJSONArray("posts").getJSONObject(0) var author = Author() author.name = firstPost.getJSONObject("author").get("name").toString() var article = Article() article.title = firstPost.get("title").toString() article.imageUrl = firstPost.getJSONObject("thumbnail_images").getJSONObject("full").get("url").toString() article.author = author categories[position].featuredArticle = article Picasso.get().load(article.imageUrl).fit().centerCrop().into(holder.categoryArticleImageView) holder.categoryArticleName.text = article.title holder.categoryArticleAuthor.text = author.name } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { error -> error.printStackTrace() }) jsonObjectRequest.retryPolicy = DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT) jsonObjectRequest.tag = "cat" Session.mRequestQueue!!.add(jsonObjectRequest) } } override fun getItemCount(): Int { return categories.size } inner class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var category: Category? = null val cardView: CardView = itemView.findViewById(R.id.categoryCardView) val cardViewBackground: ConstraintLayout = itemView.findViewById(R.id.categoryCardViewBackgroundLayout) val categoryArticleImageView: ImageView = itemView.findViewById(R.id.categoryArticleImageView) val categoryArticleName: TextView = itemView.findViewById(R.id.categoryArticleNameTextView) val categoryArticleAuthor: TextView = itemView.findViewById(R.id.categoryArticleAuthorTextView) val categoryTitle: TextView = itemView.findViewById(R.id.categoryTitleTextView) init { cardView.setOnClickListener { val transaction = fragmentManager.beginTransaction() val fragment = CategoryArticlesFragment.newInstance(category!!.slug!!) transaction.replace(R.id.container, fragment) transaction.commit() } } } }
15
Kotlin
9
1
7747a78a451443f02354f2f57ba170ebdc6f5aee
4,693
ggslk-app
MIT License
code-gen-with-kotlin/gradle-build-logic/src/main/kotlin/de/jjohannes/codegen/gradle/BuildGradleGen.kt
jjohannes
225,674,785
false
{"Text": 5, "Ignore List": 9, "Markdown": 26, "Gradle Kotlin DSL": 140, "Shell": 27, "Batchfile": 27, "INI": 30, "Java": 75, "Kotlin": 32, "Checksums": 24, "XML": 18, "C": 6, "Gradle": 12, "Groovy": 3, "YAML": 1}
package de.jjohannes.codegen.gradle import de.jjohannes.codegen.CodeGenerator import de.jjohannes.codegen.CodeGeneratorConfig object BuildGradleGen : CodeGenerator { override fun fileName(conf: CodeGeneratorConfig) = with(conf) { "build.gradle.kts" } override fun generateContent(conf: CodeGeneratorConfig) = with(conf) { """ plugins { application } dependencies { implementation("org.jdom:jdom2:2.0.6") } application { mainClass.set("${projectPackage.get()}.${projectName.get()}App") } """ } }
0
Java
3
48
d730224ae5e45ce5b4156d2b022d081bbf2b97cd
672
gradle-demos
Apache License 2.0
app/src/main/java/com/rmnivnv/cryptomoon/ui/coinAllocation/ICoinAllocation.kt
ivnvrmn
98,931,608
false
null
package com.rmnivnv.cryptomoon.ui.coinAllocation import com.github.mikephil.charting.data.PieData interface ICoinAllocation { interface View { fun drawPieChart(pieData: PieData) fun enableGraphLoading() fun disableGraphLoading() } interface Presenter { fun onCreate() fun onStop() } }
2
null
14
113
4d1651ce680fbf49e71cafb7d49e2d49d059b5fd
345
CryptoMoon
Apache License 2.0
yas/src/main/java/io/github/amalhanaja/yas/Duration.kt
amalhanaja
110,639,261
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 6, "XML": 19, "Java": 2}
package io.github.amalhanaja.yas import android.support.design.widget.Snackbar /** * Created by doy on 11/12/17. * Email : amalhanaja@gmail.com * Created On : 11/12/17. */ object Duration { val INDEFINED = Snackbar.LENGTH_INDEFINITE val SHORT = Snackbar.LENGTH_SHORT val LONG = Snackbar.LENGTH_LONG val CUSTOM: (Int) -> Int = { it } }
1
null
1
1
7ce9c8fe9c087fdd106b8be696d82e6a5005ba04
356
YetAnotherSnackbar
Apache License 2.0
app/src/main/java/ajar/huzefa/olaplay/data/Entity.kt
huzefaraja
115,239,147
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 38, "XML": 29, "Java": 1}
package ajar.huzefa.olaplay.data import android.content.Context interface Entity { fun insert(context: Context): Long fun update(context: Context) fun delete(context: Context) interface OnEntitiesInsertedListener { fun onEntitiesInserted(taskId: Int, entities: Array<out Entity?>?) } interface OnEntitiesUpdatedListener { fun onEntitiesUpdated(taskId: Int, entities: Array<out Entity?>?) } interface OnEntitiesDeletedListener { fun onEntitiesDeleted(taskId: Int, entities: Array<out Entity?>?) } interface OnEntitiesQueriedListener { fun onEntitiesQueried(taskId: Int, type: Class<*>, result: List<*>?) } }
1
null
1
1
779098baaf99b5a31389ec08ef33dff4a959f19e
691
ola_play
MIT License
app/src/main/java/com/alanyuan/clipboard/ClipboardAdapter.kt
AlanGinger
141,264,979
false
null
package com.alanyuan.clipboard import android.content.Context import android.databinding.DataBindingUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.alanyuan.clipboard.databinding.ItemClipboardBinding class ClipboardAdapter : RecyclerView.Adapter<ClipboardAdapter.ClipboardViewHolder>() { private lateinit var mContext: Context var mClipboardDataList: List<ClipboardData>? = null fun setData(dataList: List<ClipboardData>?) { this.mClipboardDataList = dataList notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClipboardViewHolder { mContext = parent.context val binding: ItemClipboardBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.item_clipboard, parent, false) return ClipboardViewHolder(binding) } override fun getItemCount(): Int { return mClipboardDataList?.size ?: 0 } override fun onBindViewHolder(holder: ClipboardViewHolder, position: Int) { holder.binding.clipData = mClipboardDataList?.get(position) holder.binding.executePendingBindings() } class ClipboardViewHolder(val binding: ItemClipboardBinding) : RecyclerView.ViewHolder(binding.root) }
0
Kotlin
0
0
0f37d385f4f26c575f0f3a6fba434a3b5668a6cb
1,317
GingersnapButler
Apache License 2.0
zircon.jvm/src/test/kotlin/org/hexworks/zircon/api/data/SizeTest.kt
entelente
148,384,225
false
null
package org.hexworks.zircon.api.data import org.assertj.core.api.Assertions.assertThat import org.junit.Test class SizeTest { @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTerminalXLengthIsNegative() { Size.create( xLength = -1, yLength = 1) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTerminalYLengthIsNegative() { Size.create( xLength = 1, yLength = -1) } @Test fun shouldCreateNewSizeWithProperXLengthWhenWithXLengthIsCalled() { assertThat(Size.create( xLength = Int.MAX_VALUE, yLength = EXPECTED_ROW).withXLength(EXPECTED_COL)) .isEqualTo(EXPECTED_TERMINAL_SIZE) } @Test fun shouldProperlyAddTwoSizes() { assertThat(Size.create(1, 2) + Size.create(2, 1)).isEqualTo(Size.create(3, 3)) } @Test fun shouldCreateNewSizeWithProperRelativeXLengthWhenWithRelativeXLengthIsCalled() { assertThat(Size.create( xLength = EXPECTED_COL - 1, yLength = EXPECTED_ROW).withRelativeXLength(1)) .isEqualTo(EXPECTED_TERMINAL_SIZE) } @Test fun shouldCreateNewSizeWithProperYLengthWhenWithYLengthIsCalled() { assertThat(Size.create( xLength = EXPECTED_COL, yLength = Int.MAX_VALUE).withYLength(EXPECTED_ROW)) .isEqualTo(EXPECTED_TERMINAL_SIZE) } @Test fun shouldCreateNewSizeWithProperRelativeYLengthWhenWithRelativeYLengthIsCalled() { assertThat(Size.create( xLength = EXPECTED_COL, yLength = EXPECTED_ROW - 1).withRelativeYLength(1)) .isEqualTo(EXPECTED_TERMINAL_SIZE) } @Test fun shouldCreateNewSizeWithProperRelativesWhenWithRelativeIsCalled() { assertThat(Size.create( xLength = EXPECTED_COL - 1, yLength = EXPECTED_ROW - 1).withRelative(Size.create(1, 1))) .isEqualTo(EXPECTED_TERMINAL_SIZE) } @Test fun shouldFetchPositionsInCorrectIterationOrder() { assertThat(Size.create(2, 2).fetchPositions().toList()) .isEqualTo(listOf( Position.create(x = 0, y = 0), Position.create(x = 1, y = 0), Position.create(x = 0, y = 1), Position.create(x = 1, y = 1))) } @Test fun shouldReturnItselfWhenWithXLengthIsCalledAndXLengthIsTheSame() { val target = Size.defaultTerminalSize() val result = target.withXLength(target.xLength) assertThat(target).isSameAs(result) } @Test fun shouldReturnItselfWhenWithYLengthIsCalledAndYLengthIsTheSame() { val target = Size.defaultTerminalSize() val result = target.withYLength(target.yLength) assertThat(target).isSameAs(result) } @Test fun shouldReturnItselfWhenWithRelativeXLengthIsCalledAndXLengthIsTheSame() { val target = Size.defaultTerminalSize() val result = target.withRelativeXLength(0) assertThat(target).isSameAs(result) } @Test fun shouldReturnItselfWhenWithRelativeYLengthIsCalledAndYLengthIsTheSame() { val target = Size.defaultTerminalSize() val result = target.withRelativeYLength(0) assertThat(target).isSameAs(result) } @Test fun shouldReturnItselfWhenWithIsCalledAndYLengthAndXLengthIsTheSame() { val target = Size.defaultTerminalSize() val result = target.with(target) assertThat(target).isSameAs(result) } @Test fun shouldReturnProperMin() { val wide = Size.create(5, 2) val tall = Size.create(2, 5) assertThat(wide.min(tall)).isEqualTo(Size.create(2, 2)) } @Test fun shouldReturnProperMax() { val wide = Size.create(5, 2) val tall = Size.create(2, 5) assertThat(wide.max(tall)).isEqualTo(Size.create(5, 5)) } // TODO: UNCOMMENT THIS WHEN FIXED // @Test // fun shouldProperlyFetchBoundingBoxPositions() { // val target = Size.create(3, 3) // assertThat(target.fetchBoundingBoxPositions()) // .containsExactlyInAnyOrder(Position.create(0, 0), Position.create(1, 0), Position.create(2, 0), // Position.create(0, 1), Position.create(2, 1), Position.create(0, 2), Position.create(1, 2), Position.create(2, 2)) // } @Test fun shouldProperlyFetchTopLeftPosition() { assertThat(Size.create(3, 3).fetchTopLeftPosition()).isEqualTo(Position.create(0, 0)) } @Test fun shouldProperlyFetchTopRightPosition() { assertThat(Size.create(3, 3).fetchTopRightPosition()).isEqualTo(Position.create(2, 0)) } @Test fun shouldProperlyFetchBottomLeftPosition() { assertThat(Size.create(3, 3).fetchBottomLeftPosition()).isEqualTo(Position.create(0, 2)) } @Test fun shouldProperlyFetchBottomRightPosition() { assertThat(Size.create(3, 3).fetchBottomRightPosition()).isEqualTo(Position.create(2, 2)) } @Test fun withShouldReturnProperResult() { assertThat(Size.create(1, 2).with(Size.create(2, 3))) .isEqualTo(Size.create(2, 3)) } companion object { val EXPECTED_COL = 5 val EXPECTED_ROW = 5 val EXPECTED_TERMINAL_SIZE = Size.create( xLength = EXPECTED_COL, yLength = EXPECTED_ROW) } }
1
null
1
1
a8320415e949d47f55b316092a29f20469450720
5,580
zircon
MIT License
api/src/main/kotlin/com/duj/example/cleankt/api/entrypoint/queue/ExampleQueueConsumer.kt
CorreiaEduardo
415,375,934
false
{"Kotlin": 24682}
package com.duj.example.cleankt.api.entrypoint.queue import com.duj.example.api.util.ApplicationLogger import com.duj.example.cleankt.api.entrypoint.queue.message.ExampleMessage import org.springframework.amqp.rabbit.annotation.RabbitListener import org.springframework.stereotype.Component @Component class ExampleQueueConsumer { companion object : ApplicationLogger() @RabbitListener(queues = ["\${ecosystem.queue.example_queue}"]) fun receive(message: ExampleMessage) { logger.info(message.toString()) } }
0
Kotlin
0
0
d3b8b989919517501fd1fa19c8a9807d95bbd8b1
536
ex-clean-spring-kt
MIT License
app/src/main/java/project/dheeraj/githubvisualizer/Activity/IssuesActivity.kt
dheerajkotwani
265,686,465
false
null
/* * MIT License * * Copyright (c) 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package project.dheeraj.githubvisualizer.Activity import IssuesModel import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.viewpager.widget.ViewPager import com.bumptech.glide.Glide import com.ogaclejapan.smarttablayout.SmartTabLayout import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems import kotlinx.android.synthetic.main.activity_issues.* import project.dheeraj.githubvisualizer.Adapter.IssuesAdapter import project.dheeraj.githubvisualizer.AppConfig import project.dheeraj.githubvisualizer.Fragment.Issues.AllIssuesFragment import project.dheeraj.githubvisualizer.Fragment.Issues.AssignedIssuesFragment import project.dheeraj.githubvisualizer.Fragment.Issues.CreatedIssuesFragment import project.dheeraj.githubvisualizer.Fragment.Issues.MentionedIssuesFragment import project.dheeraj.githubvisualizer.Fragment.Main.FeedsFragment import project.dheeraj.githubvisualizer.Fragment.Main.HomeFragment import project.dheeraj.githubvisualizer.Fragment.Main.NotificationsFragment import project.dheeraj.githubvisualizer.Fragment.Main.ProfileFragment import project.dheeraj.githubvisualizer.Model.IssuesPagerModel import project.dheeraj.githubvisualizer.Network.GithubApiClient import project.dheeraj.githubvisualizer.Network.GithubApiInterface import project.dheeraj.githubvisualizer.R import retrofit2.Call import retrofit2.Callback import retrofit2.Response import timber.log.Timber class IssuesActivity : AppCompatActivity() { private lateinit var sharedPref: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_issues) sharedPref = getSharedPreferences(AppConfig.SHARED_PREF, Context.MODE_PRIVATE) var fragments: ArrayList<IssuesPagerModel> = ArrayList() fragments.add(IssuesPagerModel("All", HomeFragment())) fragments.add(IssuesPagerModel("All", HomeFragment())) fragments.add(IssuesPagerModel("All", HomeFragment())) fragments.add(IssuesPagerModel("All", HomeFragment())) val adapter = FragmentPagerItemAdapter(supportFragmentManager, FragmentPagerItems.with(this) .add("All", AllIssuesFragment::class.java) .add("Created", CreatedIssuesFragment::class.java) .add("Assigned", AssignedIssuesFragment::class.java) .add("Mentioned", MentionedIssuesFragment::class.java) .create()); val viewPager = findViewById<View>(R.id.viewpager) as ViewPager viewPager.adapter = adapter val viewPagerTab = findViewById<View>(R.id.scaleTabLayoutIssues) as SmartTabLayout viewPagerTab.setViewPager(viewPager) buttonBack.setOnClickListener { onBackPressed() } } override fun onBackPressed() { super.onBackPressed() finish() } }
1
Kotlin
19
96
31c1cac980876c01d0f06f5609b50b8da3de7e91
4,234
GithubVisualizer
MIT License
src/cds/src/main/kotlin/org/icpclive/api/Advanced.kt
icpc
447,849,919
false
null
package org.icpclive.api import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.icpclive.util.ColorSerializer import org.icpclive.util.DurationInSecondsSerializer import org.icpclive.util.humanReadable import java.awt.Color import kotlin.time.Duration @Serializable data class TeamInfoOverride( val name: String? = null, val shortname: String? = null, val groups: List<String>? = null, val hashTag: String? = null, val medias: Map<TeamMediaType, MediaType?>? = null, val additionalInfo: String? = null, val isHidden: Boolean? = null, val isOutOfContest: Boolean? = null ) @Serializable data class ProblemInfoOverride( val name: String? = null, @Serializable(ColorSerializer::class) val color: Color? = null, val minScore: Double? = null, val maxScore: Double? = null, val scoreMergeMode: ScoreMergeMode? = null ) @Serializable data class GroupInfoOverride( val isHidden: Boolean? = null, val isOutOfContest: Boolean? = null ) @Serializable class RankingSettings( val medals: List<MedalType>? = null, val penaltyPerWrongAttempt: Int? = null, val showTeamsWithoutSubmissions: Boolean? = null, val penaltyRoundingMode: PenaltyRoundingMode? = null ) @Serializable data class AdvancedProperties( val startTime: String? = null, @Serializable(with = DurationInSecondsSerializer::class) @SerialName("freezeTimeSeconds") val freezeTime: Duration? = null, @Serializable(with = DurationInSecondsSerializer::class) @SerialName("holdTimeSeconds") val holdTime: Duration? = null, val teamMediaTemplate: Map<TeamMediaType, MediaType?>? = null, val teamOverrides: Map<String, TeamInfoOverride>? = null, val groupOverrides: Map<String, GroupInfoOverride>? = null, val problemOverrides: Map<String, ProblemInfoOverride>? = null, val scoreboardOverrides: RankingSettings? = null ) fun ContestInfo.toAdvancedProperties(fields: Set<String>) : AdvancedProperties { fun <T> T.takeIfAsked(name: String) = takeIf { name in fields || "all" in fields } return AdvancedProperties( startTime = startTime.humanReadable.takeIfAsked("startTime"), freezeTime = freezeTime.takeIfAsked("freezeTime"), holdTime = holdBeforeStartTime?.takeIfAsked("holdBeforeStartTime"), teamOverrides = teams.associate { it.contestSystemId to TeamInfoOverride( name = it.name.takeIfAsked("name"), shortname = it.shortName.takeIfAsked("shortname"), groups = it.groups.takeIfAsked("groups"), hashTag = it.hashTag.takeIfAsked("hashTag"), medias = it.medias.takeIfAsked("medias"), isHidden = it.isHidden.takeIfAsked("isHidden"), isOutOfContest = it.isOutOfContest.takeIfAsked("isOutOfContest") ) }, problemOverrides = problems.associate { it.letter to ProblemInfoOverride( name = it.name.takeIfAsked("problemName"), color = it.color.takeIfAsked("color"), minScore = it.minScore.takeIfAsked("minScore"), maxScore = it.maxScore.takeIfAsked("maxScore"), scoreMergeMode = it.scoreMergeMode.takeIfAsked("scoreMergeMode") ) }, groupOverrides = groups.associate { it.name to GroupInfoOverride( isHidden = it.isHidden.takeIfAsked("isHidden"), isOutOfContest = it.isOutOfContest.takeIfAsked("isOutOfContest") ) }, scoreboardOverrides = RankingSettings( medals = medals.takeIfAsked("medals"), penaltyPerWrongAttempt = penaltyPerWrongAttempt.takeIfAsked("penaltyPerWrongAttempt"), penaltyRoundingMode = penaltyRoundingMode.takeIfAsked("penaltyRoundingMode") ) ) }
15
null
7
28
a8f6d0f18f2b5b39781a0196fd1b531b0878013f
3,900
live-v3
MIT License
src/main/kotlin/felis/launcher/GameLauncher.kt
Felis-Project
774,006,760
false
{"Kotlin": 60108}
package felis.launcher fun interface GameLauncher { fun instantiate(args: Array<String>): GameInstance }
3
Kotlin
1
2
da20f2400be2442e640731c74365de2f14e64da8
110
felis
MIT License
cli/src/main/kotlin/tools/samt/cli/TypePrinter.kt
samtkit
602,288,830
false
{"Kotlin": 612490, "Batchfile": 1420, "Shell": 1226}
package tools.samt.cli import com.github.ajalt.mordant.rendering.TextColors.* import com.github.ajalt.mordant.rendering.TextStyles.bold import tools.samt.semantic.Package internal object TypePrinter { fun dump(samtPackage: Package): String = buildString { if (samtPackage.isRootPackage) { appendLine(red("<root>")) } else { appendLine(blue(samtPackage.name)) } for (enum in samtPackage.enums) { appendLine(" ${bold("enum")} ${yellow(enum.name)}") } for (record in samtPackage.records) { appendLine(" ${bold("record")} ${yellow(record.name)}") } for (alias in samtPackage.aliases) { appendLine(" ${bold("typealias")} ${yellow(alias.name)} = ${gray(alias.fullyResolvedType?.humanReadableName ?: "Unknown")}") } for (service in samtPackage.services) { appendLine(" ${bold("service")} ${yellow(service.name)}") } for (provider in samtPackage.providers) { appendLine(" ${bold("provider")} ${yellow(provider.name)}") } for (consumer in samtPackage.consumers) { appendLine(" ${bold("consumer")} for ${yellow(consumer.provider.humanReadableName)}") } val childDumps: List<String> = samtPackage.subPackages.map { dump(it) } childDumps.forEachIndexed { childIndex, child -> var firstLine = true child.lineSequence().forEach { line -> if (line.isNotEmpty()) { if (childIndex != childDumps.lastIndex) { if (firstLine) { append("${white("├─")}$line") } else { append("${white("│ ")}$line") } } else { if (firstLine) { append("${white("└─")}$line") } else { append(" $line") } } appendLine() } firstLine = false } } } }
0
Kotlin
0
8
58f179de53ebb92da8e02cac021bb691b6447448
2,182
core
MIT License
cli/src/main/kotlin/tools/samt/cli/TypePrinter.kt
samtkit
602,288,830
false
{"Kotlin": 612490, "Batchfile": 1420, "Shell": 1226}
package tools.samt.cli import com.github.ajalt.mordant.rendering.TextColors.* import com.github.ajalt.mordant.rendering.TextStyles.bold import tools.samt.semantic.Package internal object TypePrinter { fun dump(samtPackage: Package): String = buildString { if (samtPackage.isRootPackage) { appendLine(red("<root>")) } else { appendLine(blue(samtPackage.name)) } for (enum in samtPackage.enums) { appendLine(" ${bold("enum")} ${yellow(enum.name)}") } for (record in samtPackage.records) { appendLine(" ${bold("record")} ${yellow(record.name)}") } for (alias in samtPackage.aliases) { appendLine(" ${bold("typealias")} ${yellow(alias.name)} = ${gray(alias.fullyResolvedType?.humanReadableName ?: "Unknown")}") } for (service in samtPackage.services) { appendLine(" ${bold("service")} ${yellow(service.name)}") } for (provider in samtPackage.providers) { appendLine(" ${bold("provider")} ${yellow(provider.name)}") } for (consumer in samtPackage.consumers) { appendLine(" ${bold("consumer")} for ${yellow(consumer.provider.humanReadableName)}") } val childDumps: List<String> = samtPackage.subPackages.map { dump(it) } childDumps.forEachIndexed { childIndex, child -> var firstLine = true child.lineSequence().forEach { line -> if (line.isNotEmpty()) { if (childIndex != childDumps.lastIndex) { if (firstLine) { append("${white("├─")}$line") } else { append("${white("│ ")}$line") } } else { if (firstLine) { append("${white("└─")}$line") } else { append(" $line") } } appendLine() } firstLine = false } } } }
0
Kotlin
0
8
58f179de53ebb92da8e02cac021bb691b6447448
2,182
core
MIT License
app/src/main/java/com/bdlepla/android/mymusicplayer/business/CurrentPlayingStats.kt
bdlepla
451,687,232
false
null
package com.bdlepla.android.mymusicplayer.business data class CurrentPlayingStats( val currentPlaying: SongInfo?, val currentPosition:Int, val maxPosition:Int, )
0
Kotlin
0
0
152be26baa42a3bbf6aa2da276f4ee8291eaa692
175
MyMusicPlayer
MIT License
app/src/main/java/com/devcommop/joaquin/codeforgood/ui/sponsors_screen/sponsor_detail_screen/SponsorDetailFragment.kt
RahulSoni0
522,188,041
false
null
package com.devcommop.joaquin.codeforgood.ui.sponsors_screen.sponsor_detail_screen import androidx.fragment.app.Fragment import com.devcommop.joaquin.codeforgood.R class SponsorDetailFragment : Fragment(R.layout.fragment_sponsor_detail) { }
0
Kotlin
1
1
02f20d700cea6bf0cd9a59ae51ffec9b928f41d8
243
DucoSign
Creative Commons Zero v1.0 Universal
app/src/main/java/org/avmedia/gShockPhoneSync/services/KeepAliveManager.kt
izivkov
480,047,057
false
{"Kotlin": 232698, "Shell": 69, "Ruby": 46}
package org.avmedia.gShockPhoneSync.services import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.PRIORITY_DEFAULT import androidx.core.app.NotificationManagerCompat import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters object KeepAliveManager { fun start(context: Context) { val immediateWorkRequest = OneTimeWorkRequestBuilder<LongRunningWorker>().build() WorkManager.getInstance(context).enqueue(immediateWorkRequest) } fun stop(context: Context) { WorkManager.getInstance(context).cancelUniqueWork("LongRunningWorker") fun cancelAllNotifications(context: Context) { val notificationManager = NotificationManagerCompat.from(context) notificationManager.cancelAll() } cancelAllNotifications(context) } class LongRunningWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { override fun doWork(): Result { showNotification("G-Shock Smart Sync", "Running...") return Result.success() } @SuppressLint("MissingPermission") private fun showNotification(title: String, message: String) { val channelId = "gshock_smart_sync_keep_alive_channel" val channel = NotificationChannel( channelId, "G-Shock Keep Alive Notification", NotificationManager.IMPORTANCE_LOW ) val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId) .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle(title) .setContentText(message) .setPriority(PRIORITY_DEFAULT) .setOngoing(true) with(NotificationManagerCompat.from(applicationContext)) { notify(System.currentTimeMillis().toInt(), notificationBuilder.build()) } } } }
6
Kotlin
9
96
4a67d586e8eb94a4d5dba2120101e92a8fe513e7
2,449
CasioGShockSmartSync
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/skills/crafting/pottery/PotteryData.kt
2011Scape
578,880,245
false
{"Kotlin": 8359518, "Dockerfile": 1354}
package gg.rsmod.plugins.content.skills.crafting.pottery import gg.rsmod.plugins.api.cfg.Items enum class PotteryData(vararg val products: PotteryItem, val urn: Boolean = true, val runeRequired: Int? = null) { NOT_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_FISHING_URN_UNF, fired = -1), PotteryItem(unfired = Items.POT_UNFIRED, fired = Items.EMPTY_POT, levelRequired = 1, formingExperience = 6.3, firingExperience = 6.3), PotteryItem(unfired = Items.PIE_DISH_UNFIRED, fired = Items.PIE_DISH, levelRequired = 7, formingExperience = 15.0, firingExperience = 10.0), PotteryItem(unfired = Items.BOWL_UNFIRED, fired = Items.BOWL, levelRequired = 8, formingExperience = 18.0, firingExperience = 15.0), PotteryItem(unfired = Items.UNFIRED_PLANT_POT, fired = Items.PLANT_POT, levelRequired = 19, formingExperience = 20.0, firingExperience = 17.5), PotteryItem(unfired = Items.UNFIRED_POT_LID, fired = Items.POT_LID, levelRequired = 25, formingExperience = 20.0, firingExperience = 20.0) ), urn = false), MINING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_MINING_URN_UNF, fired = Items.CRACKED_MINING_URN_NR, levelRequired = 1, formingExperience = 11.8, firingExperience = 16.8, addRuneAnimation = 11420), PotteryItem(unfired = Items.FRAGILE_MINING_URN_UNF, fired = Items.FRAGILE_MINING_URN_NR, levelRequired = 17, formingExperience = 21.2, firingExperience = 31.8, addRuneAnimation = 11421), PotteryItem(unfired = Items.MINING_URN_UNF, fired = Items.MINING_URN_NR, levelRequired = 32, formingExperience = 27.2, firingExperience = 40.8, addRuneAnimation = 11425), PotteryItem(unfired = Items.STRONG_MINING_URN_UNF, fired = Items.STRONG_MINING_URN_NR, levelRequired = 48, formingExperience = 30.8, firingExperience = 49.2, addRuneAnimation = 11447), PotteryItem(unfired = Items.DECORATED_MINING_URN_UNF, fired = Items.DECORATED_MINING_URN_NR, levelRequired = 59, formingExperience = 38.0, firingExperience = 57.0, addRuneAnimation = 11448) ), runeRequired = Items.EARTH_RUNE), COOKING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_COOKING_URN_UNF, fired = Items.CRACKED_COOKING_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 8649), PotteryItem(unfired = Items.FRAGILE_COOKING_URN_UNF, fired = Items.FRAGILE_COOKING_URN_NR, levelRequired = 12, formingExperience = 16.0, firingExperience = 24.0, addRuneAnimation = 8651), PotteryItem(unfired = Items.COOKING_URN_UNF, fired = Items.COOKING_URN_NR, levelRequired = 36, formingExperience = 28.6, firingExperience = 42.8, addRuneAnimation = 8652), PotteryItem(unfired = Items.STRONG_COOKING_URN_UNF, fired = Items.STRONG_COOKING_URN_NR, levelRequired = 51, formingExperience = 35.0, firingExperience = 52.5, addRuneAnimation = 8654), PotteryItem(unfired = Items.DECORATED_COOKING_URN_UNF, fired = Items.DECORATED_COOKING_URN_NR, levelRequired = 81, formingExperience = 52.0, firingExperience = 78.0, addRuneAnimation = 8961) ), runeRequired = Items.FIRE_RUNE), FISHING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_FISHING_URN_UNF, fired = Items.CRACKED_FISHING_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 6474), PotteryItem(unfired = Items.FRAGILE_FISHING_URN_UNF, fired = Items.FRAGILE_FISHING_URN_NR, levelRequired = 15, formingExperience = 20.0, firingExperience = 30.0, addRuneAnimation = 6475), PotteryItem(unfired = Items.FISHING_URN_UNF, fired = Items.FISHING_URN_NR, levelRequired = 41, formingExperience = 31.2, firingExperience = 46.8, addRuneAnimation = 6769), PotteryItem(unfired = Items.STRONG_FISHING_URN_UNF, fired = Items.STRONG_FISHING_URN_NR, levelRequired = 53, formingExperience = 36.0, firingExperience = 54.0, addRuneAnimation = 6770), PotteryItem(unfired = Items.DECORATED_FISHING_URN_UNF, fired = Items.DECORATED_FISHING_URN_NR, levelRequired = 76, formingExperience = 48.0, firingExperience = 72.0, addRuneAnimation = 6789) ), runeRequired = Items.WATER_RUNE), WOODCUTTING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_WOODCUTTING_URN_UNF, fired = Items.CRACKED_WOODCUTTING_URN_NR, levelRequired = 4, formingExperience = 15.4, firingExperience = 23.1, addRuneAnimation = 10279), PotteryItem(unfired = Items.FRAGILE_WOODCUTTING_URN_UNF, fired = Items.FRAGILE_WOODCUTTING_URN_NR, levelRequired = 15, formingExperience = 20.0, firingExperience = 30.0, addRuneAnimation = 10280), PotteryItem(unfired = Items.WOODCUTTING_URN_UNF, fired = Items.WOODCUTTING_URN_NR, levelRequired = 44, formingExperience = 32.0, firingExperience = 48.0, addRuneAnimation = 10281), PotteryItem(unfired = Items.STRONG_WOODCUTTING_URN_UNF, fired = Items.STRONG_WOODCUTTING_URN_NR, levelRequired = 61, formingExperience = 38.8, firingExperience = 58.2, addRuneAnimation = 10828) ), runeRequired = Items.EARTH_RUNE), SMELTING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_SMELTING_URN_UNF, fired = Items.CRACKED_SMELTING_URN_NR, levelRequired = 4, formingExperience = 15.4, firingExperience = 23.8, addRuneAnimation = 6384), PotteryItem(unfired = Items.FRAGILE_SMELTING_URN_UNF, fired = Items.FRAGILE_SMELTING_URN_NR, levelRequired = 17, formingExperience = 21.2, firingExperience = 31.8, addRuneAnimation = 6385), PotteryItem(unfired = Items.SMELTING_URN_UNF, fired = Items.SMELTING_URN_NR, levelRequired = 35, formingExperience = 28.0, firingExperience = 42.0, addRuneAnimation = 6386), PotteryItem(unfired = Items.STRONG_SMELTING_URN_UNF, fired = Items.STRONG_SMELTING_URN_NR, levelRequired = 49, formingExperience = 33.8, firingExperience = 50.8, addRuneAnimation = 6387) ), runeRequired = Items.FIRE_RUNE), PRAYER_URNS(products = arrayOf( PotteryItem(unfired = Items.IMPIOUS_URN_UNF, fired = Items.IMPIOUS_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 4567), PotteryItem(unfired = Items.ACCURSED_URN_UNF, fired = Items.ACCURSED_URN_NR, levelRequired = 26, formingExperience = 25.0, firingExperience = 37.5, addRuneAnimation = 4569), PotteryItem(unfired = Items.INFERNAL_URN_UNF, fired = Items.INFERNAL_URN_NR, levelRequired = 62, formingExperience = 40.0, firingExperience = 60.0, addRuneAnimation = 4578) ), runeRequired = Items.AIR_RUNE); companion object { val values = enumValues<PotteryData>() fun getAllFiredUrns() : MutableList<Int> { val temp = mutableListOf<Int>() for (data in PotteryData.values()) { if (data.urn) { for (product in data.products) { if (!temp.contains(product.fired)) temp.add(product.fired) } } } return temp } fun findPotteryDataByItem(item: Int) : PotteryData? { for (data in PotteryData.values()) { for (product in data.products) { if (product.unfired == item || product.fired == item) return data } } return null } fun findPotteryItemByItem(item: Int) : PotteryItem? { for (data in PotteryData.values()) { for (product in data.products) { if (product.unfired == item || product.fired == item) return product } } return null } } }
36
Kotlin
138
32
da66bb6d68ebae531ee325b909a6536e798b1144
7,724
game
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/skills/crafting/pottery/PotteryData.kt
2011Scape
578,880,245
false
{"Kotlin": 8359518, "Dockerfile": 1354}
package gg.rsmod.plugins.content.skills.crafting.pottery import gg.rsmod.plugins.api.cfg.Items enum class PotteryData(vararg val products: PotteryItem, val urn: Boolean = true, val runeRequired: Int? = null) { NOT_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_FISHING_URN_UNF, fired = -1), PotteryItem(unfired = Items.POT_UNFIRED, fired = Items.EMPTY_POT, levelRequired = 1, formingExperience = 6.3, firingExperience = 6.3), PotteryItem(unfired = Items.PIE_DISH_UNFIRED, fired = Items.PIE_DISH, levelRequired = 7, formingExperience = 15.0, firingExperience = 10.0), PotteryItem(unfired = Items.BOWL_UNFIRED, fired = Items.BOWL, levelRequired = 8, formingExperience = 18.0, firingExperience = 15.0), PotteryItem(unfired = Items.UNFIRED_PLANT_POT, fired = Items.PLANT_POT, levelRequired = 19, formingExperience = 20.0, firingExperience = 17.5), PotteryItem(unfired = Items.UNFIRED_POT_LID, fired = Items.POT_LID, levelRequired = 25, formingExperience = 20.0, firingExperience = 20.0) ), urn = false), MINING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_MINING_URN_UNF, fired = Items.CRACKED_MINING_URN_NR, levelRequired = 1, formingExperience = 11.8, firingExperience = 16.8, addRuneAnimation = 11420), PotteryItem(unfired = Items.FRAGILE_MINING_URN_UNF, fired = Items.FRAGILE_MINING_URN_NR, levelRequired = 17, formingExperience = 21.2, firingExperience = 31.8, addRuneAnimation = 11421), PotteryItem(unfired = Items.MINING_URN_UNF, fired = Items.MINING_URN_NR, levelRequired = 32, formingExperience = 27.2, firingExperience = 40.8, addRuneAnimation = 11425), PotteryItem(unfired = Items.STRONG_MINING_URN_UNF, fired = Items.STRONG_MINING_URN_NR, levelRequired = 48, formingExperience = 30.8, firingExperience = 49.2, addRuneAnimation = 11447), PotteryItem(unfired = Items.DECORATED_MINING_URN_UNF, fired = Items.DECORATED_MINING_URN_NR, levelRequired = 59, formingExperience = 38.0, firingExperience = 57.0, addRuneAnimation = 11448) ), runeRequired = Items.EARTH_RUNE), COOKING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_COOKING_URN_UNF, fired = Items.CRACKED_COOKING_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 8649), PotteryItem(unfired = Items.FRAGILE_COOKING_URN_UNF, fired = Items.FRAGILE_COOKING_URN_NR, levelRequired = 12, formingExperience = 16.0, firingExperience = 24.0, addRuneAnimation = 8651), PotteryItem(unfired = Items.COOKING_URN_UNF, fired = Items.COOKING_URN_NR, levelRequired = 36, formingExperience = 28.6, firingExperience = 42.8, addRuneAnimation = 8652), PotteryItem(unfired = Items.STRONG_COOKING_URN_UNF, fired = Items.STRONG_COOKING_URN_NR, levelRequired = 51, formingExperience = 35.0, firingExperience = 52.5, addRuneAnimation = 8654), PotteryItem(unfired = Items.DECORATED_COOKING_URN_UNF, fired = Items.DECORATED_COOKING_URN_NR, levelRequired = 81, formingExperience = 52.0, firingExperience = 78.0, addRuneAnimation = 8961) ), runeRequired = Items.FIRE_RUNE), FISHING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_FISHING_URN_UNF, fired = Items.CRACKED_FISHING_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 6474), PotteryItem(unfired = Items.FRAGILE_FISHING_URN_UNF, fired = Items.FRAGILE_FISHING_URN_NR, levelRequired = 15, formingExperience = 20.0, firingExperience = 30.0, addRuneAnimation = 6475), PotteryItem(unfired = Items.FISHING_URN_UNF, fired = Items.FISHING_URN_NR, levelRequired = 41, formingExperience = 31.2, firingExperience = 46.8, addRuneAnimation = 6769), PotteryItem(unfired = Items.STRONG_FISHING_URN_UNF, fired = Items.STRONG_FISHING_URN_NR, levelRequired = 53, formingExperience = 36.0, firingExperience = 54.0, addRuneAnimation = 6770), PotteryItem(unfired = Items.DECORATED_FISHING_URN_UNF, fired = Items.DECORATED_FISHING_URN_NR, levelRequired = 76, formingExperience = 48.0, firingExperience = 72.0, addRuneAnimation = 6789) ), runeRequired = Items.WATER_RUNE), WOODCUTTING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_WOODCUTTING_URN_UNF, fired = Items.CRACKED_WOODCUTTING_URN_NR, levelRequired = 4, formingExperience = 15.4, firingExperience = 23.1, addRuneAnimation = 10279), PotteryItem(unfired = Items.FRAGILE_WOODCUTTING_URN_UNF, fired = Items.FRAGILE_WOODCUTTING_URN_NR, levelRequired = 15, formingExperience = 20.0, firingExperience = 30.0, addRuneAnimation = 10280), PotteryItem(unfired = Items.WOODCUTTING_URN_UNF, fired = Items.WOODCUTTING_URN_NR, levelRequired = 44, formingExperience = 32.0, firingExperience = 48.0, addRuneAnimation = 10281), PotteryItem(unfired = Items.STRONG_WOODCUTTING_URN_UNF, fired = Items.STRONG_WOODCUTTING_URN_NR, levelRequired = 61, formingExperience = 38.8, firingExperience = 58.2, addRuneAnimation = 10828) ), runeRequired = Items.EARTH_RUNE), SMELTING_URNS(products = arrayOf( PotteryItem(unfired = Items.CRACKED_SMELTING_URN_UNF, fired = Items.CRACKED_SMELTING_URN_NR, levelRequired = 4, formingExperience = 15.4, firingExperience = 23.8, addRuneAnimation = 6384), PotteryItem(unfired = Items.FRAGILE_SMELTING_URN_UNF, fired = Items.FRAGILE_SMELTING_URN_NR, levelRequired = 17, formingExperience = 21.2, firingExperience = 31.8, addRuneAnimation = 6385), PotteryItem(unfired = Items.SMELTING_URN_UNF, fired = Items.SMELTING_URN_NR, levelRequired = 35, formingExperience = 28.0, firingExperience = 42.0, addRuneAnimation = 6386), PotteryItem(unfired = Items.STRONG_SMELTING_URN_UNF, fired = Items.STRONG_SMELTING_URN_NR, levelRequired = 49, formingExperience = 33.8, firingExperience = 50.8, addRuneAnimation = 6387) ), runeRequired = Items.FIRE_RUNE), PRAYER_URNS(products = arrayOf( PotteryItem(unfired = Items.IMPIOUS_URN_UNF, fired = Items.IMPIOUS_URN_NR, levelRequired = 2, formingExperience = 12.0, firingExperience = 18.0, addRuneAnimation = 4567), PotteryItem(unfired = Items.ACCURSED_URN_UNF, fired = Items.ACCURSED_URN_NR, levelRequired = 26, formingExperience = 25.0, firingExperience = 37.5, addRuneAnimation = 4569), PotteryItem(unfired = Items.INFERNAL_URN_UNF, fired = Items.INFERNAL_URN_NR, levelRequired = 62, formingExperience = 40.0, firingExperience = 60.0, addRuneAnimation = 4578) ), runeRequired = Items.AIR_RUNE); companion object { val values = enumValues<PotteryData>() fun getAllFiredUrns() : MutableList<Int> { val temp = mutableListOf<Int>() for (data in PotteryData.values()) { if (data.urn) { for (product in data.products) { if (!temp.contains(product.fired)) temp.add(product.fired) } } } return temp } fun findPotteryDataByItem(item: Int) : PotteryData? { for (data in PotteryData.values()) { for (product in data.products) { if (product.unfired == item || product.fired == item) return data } } return null } fun findPotteryItemByItem(item: Int) : PotteryItem? { for (data in PotteryData.values()) { for (product in data.products) { if (product.unfired == item || product.fired == item) return product } } return null } } }
36
Kotlin
138
32
da66bb6d68ebae531ee325b909a6536e798b1144
7,724
game
Apache License 2.0
sample/src/main/java/com/seiko/immersionbar/sample/fragment/five/MineFiveFragment.kt
qdsfdhvh
273,822,575
true
{"Kotlin": 79797}
package com.seiko.immersionbar.sample.fragment.five import android.os.Bundle import com.seiko.immersionbar.immersionBar import com.seiko.immersionbar.sample.R import com.seiko.immersionbar.sample.utils.getResColor /** * @author geyifeng * @date 2017/7/20 */ class MineFiveFragment : BaseFiveFragment() { override fun getLayoutId(): Int { return R.layout.fragment_two_mine } override fun initImmersionBar() { super.initImmersionBar() immersionBar { keyboardEnable(true) navigationBarColor(getResColor(R.color.btn7)) } } companion object { @JvmStatic fun newInstance(): MineFiveFragment { val args = Bundle() val fragment = MineFiveFragment() fragment.arguments = args return fragment } } }
0
Kotlin
0
1
70e0969f96eae5cbf665e8edd38a32c63d3172c5
848
immersionbar
Apache License 2.0
zircon.core/common/src/main/kotlin/org/hexworks/zircon/api/component/Visibility.kt
jmedinaJBM
178,613,075
true
{"Kotlin": 1311631, "Java": 128163}
package org.hexworks.zircon.api.component /** * Determines the Visibility of a component */ enum class Visibility { /** * Component is Visible */ Visible, /** * Component is invisible but occupies the space */ Hidden //Invisible...maybe an option for later (but makes only sense if a Layout Manager is present and //adapts the positions accordingly) }
0
Kotlin
0
0
700f7542c1d59f5561f2aec084f9b6a1f50649b0
400
zircon
MIT License
core/src/commonMain/kotlin/response/ResponseDeserializers.kt
aSoft-Ltd
546,494,559
false
null
package response import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json import response.failure.decodeFailureFromString import response.success.decodeSuccessFromString fun <D> Json.decodeResponseFromString( dataSerializer: KSerializer<D>, json: String, ): Response<D, Any?> = try { decodeSuccessFromString(dataSerializer, json) } catch (cause: Throwable) { try { decodeFailureFromString(json) } catch (err: Throwable) { cause.printStackTrace() err.printStackTrace() responseOf(Throwable("Failed to decode the response", cause)) } } fun <D, I : Any> Json.decodeResponseWithInfoFromString( dataSerializer: KSerializer<D>, infoSerializer: KSerializer<I>, json: String, ): Response<D, I> = try { decodeSuccessFromString(dataSerializer, infoSerializer, json) } catch (cause: Throwable) { try { decodeFailureFromString(json) } catch (err: Throwable) { responseOf(Throwable("Failed to decode the response", cause)) } }
0
Kotlin
0
0
96728a0fea91820506113dba466663a8cfdb25aa
1,039
response
MIT License
new-tab-page/new-tab-page-impl/src/test/java/com/duckduckgo/newtabpage/impl/shortcuts/NewTabShortcutsProviderTest.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2024 DuckDuckGo * * 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.duckduckgo.newtabpage.impl.shortcuts import app.cash.turbine.test import com.duckduckgo.newtabpage.impl.FakeSettingStore import com.duckduckgo.newtabpage.impl.disabledShortcutPlugins import com.duckduckgo.newtabpage.impl.enabledShortcutPlugins import com.duckduckgo.newtabpage.impl.settings.NewTabSettingsStore import kotlinx.coroutines.test.runTest import org.junit.Assert.assertTrue import org.junit.Test import org.mockito.kotlin.mock class NewTabShortcutsProviderTest { private val newTabSettingsStore: NewTabSettingsStore = mock() private lateinit var testee: NewTabShortcutsProvider @Test fun whenShortcutPluginsEnabledThenProvided() = runTest { val store = FakeSettingStore() testee = RealNewTabPageShortcutProvider(enabledShortcutPlugins, store) testee.provideActiveShortcuts().test { expectMostRecentItem().also { assertTrue(it[0].getShortcut().name() == "bookmarks") assertTrue(it[1].getShortcut().name() == "chat") } } } @Test fun whenShortcutsDisabledThenProvided() = runTest { testee = RealNewTabPageShortcutProvider(disabledShortcutPlugins, newTabSettingsStore) testee.provideActiveShortcuts().test { expectMostRecentItem().also { assertTrue(it.isEmpty()) } } } }
67
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
1,980
Android
Apache License 2.0
app/src/main/java/eu/kanade/domain/chapter/interactor/UpdateChapter.kt
AntsyLich
378,910,163
true
{"Kotlin": 2124469}
package eu.kanade.domain.chapter.interactor import eu.kanade.domain.chapter.model.ChapterUpdate import eu.kanade.domain.chapter.repository.ChapterRepository class UpdateChapter( private val chapterRepository: ChapterRepository, ) { suspend fun await(chapterUpdate: ChapterUpdate) { chapterRepository.update(chapterUpdate) } }
0
Kotlin
1
4
3c40010afffa807017f0b56634d8c5323154b4e4
349
tachiyomi
Apache License 2.0
app/src/main/java/com/envelope/pickyapp/ui/chooseinterests/ChooseInterestsActivity.kt
othreecodes
195,314,696
false
null
package com.envelope.pickyapp.ui.chooseinterests import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.envelope.pickyapp.R class ChooseInterestsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.choose_interests_activity) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, ChooseInterestsFragment.newInstance()) .commitNow() } } }
0
Kotlin
1
1
934123d616dd16e19ad80205c5771a3c1f8860d3
594
NewZZ
Apache License 2.0
app/src/main/java/com/marcodiegopia/myapplication/PremiumActivity.kt
SPVbug
713,625,941
false
{"Kotlin": 11329}
package com.marcodiegopia.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class PremiumActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_premium) //volver a la pantalla de inicio val btnPVolver: Button = findViewById(R.id.btn_PVolver) btnPVolver.setOnClickListener { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() } } }
0
Kotlin
0
0
ed3285fd65e543b477d0414892f92288e572ae02
654
miciclofem
Apache License 2.0
src/main/kotlin/utility/StringValidator.kt
EliFuzz
669,912,353
false
null
package utility import java.lang.Enum.valueOf import kotlin.reflect.KClass fun validate(fieldName: String, fieldValue: String?): Validator<String> = object: Validator<String> { override fun exists(): Validator<String> = require(!fieldValue.isNullOrBlank()) { "${prepend()} $fieldName must not be empty" } .let { this } override fun exact(value: String): Validator<String> = exists().also { require(fieldValue == value) { "${prepend()} $fieldName must be equal to $value" } }.let { this } override fun lessThan(limit: Int): Validator<String> = exists().also { require(fieldValue!!.length <= limit) { "${prepend()} $fieldName must be longer than $limit" } }.let { this } override fun greaterThan(limit: Int): Validator<String> = exists().also { require(fieldValue!!.length >= limit) { "${prepend()} $fieldName must be shorter than $limit" } }.let { this } override fun <K: Enum<K>> tryParse(clazz: KClass<K>): Validator<String> = exists().also { try { valueOf(clazz.java, fieldValue!!).let { this } } catch (e: Exception) { throw IllegalArgumentException("${prepend()} $fieldName failed to parse: ${e.message}") } } override fun regex(regex: String): Validator<String> = exists().also { require(fieldValue!!.matches(regex.toRegex())) { "${prepend()} $fieldName must match $regex" } }.let { this } override fun <K> contains(value: K): Validator<String> = exists().also { require(value is Char && fieldValue!!.contains(value)) { "${prepend()} $fieldName must contain $value" } }.let { this } }
0
Kotlin
0
0
b33744b4945c2726a4db8edae2f0a0a33f0d56bf
1,674
validator
MIT License
app/src/main/java/dev/tomscott/hangman/model/GameState.kt
tscott0
147,972,570
false
null
package dev.tomscott.hangman.model enum class GameState { PLAYING, WON, LOST }
0
Kotlin
0
0
9f98bbb7765599466535c5588c8efd696ee09a9c
83
hangman-android
MIT License
app/src/main/java/me/gibsoncodes/spellingbee/utils/PreConditions.kt
GibsonRuitiari
616,095,603
false
null
package me.gibsoncodes.spellingbee.utils inline fun <reified T:Any> checkNotNull(vararg values:T?) = checkValues(values = values, predicate = {it!=null}) inline fun<T:Any?> checkValues(vararg values:T, predicate: (T) -> Boolean, lazyMessage:String?=null) = checkValues(values=values, predicate=predicate, lazyMessage = {lazyMessage ?: it}) inline fun<T:Any?> checkValues(vararg values:T, predicate:(T)->Boolean, lazyMessage:(defaultErrorMessage:String)->Any):Array<out T>{ val unwantedItemsIndices = mutableListOf<Int>() values.forEachIndexed { index, t -> if (predicate(t).not()){ unwantedItemsIndices += index } } return if (unwantedItemsIndices.isNotEmpty()){ val exceptionMessage = "The following indices did not satisfy the precondition ${unwantedItemsIndices.joinToString(",")}" throw IllegalStateException(lazyMessage(exceptionMessage).toString()) }else values }
1
Kotlin
1
4
7549e6a3f49e7f897f54b6864d93f12b8d8c3f4b
938
SpellingBee
MIT License
app/src/main/java/com/braisgabin/showmedamoney/data/MarvelResponseMapper.kt
BraisGabin
161,705,625
false
null
package com.braisgabin.showmedamoney.data import com.braisgabin.showmedamoney.entities.Contact import okhttp3.HttpUrl.Companion.toHttpUrlOrNull class MarvelResponseMapper( val data: MarvelListMapper ) { fun toDomain(): List<Contact> { return data.results.map { val thumbnail = (it.thumbnail.path + "/standard_xlarge.jpg").toHttpUrlOrNull()!! .newBuilder() .scheme("https") .build() .toString() Contact(it.id.toString(), it.name, thumbnail, null) } } } class MarvelListMapper( val results: List<MarvelContactMapper> ) class MarvelContactMapper( val id: Long, val name: String, val thumbnail: MarvelThumbnailMapper ) class MarvelThumbnailMapper( val path: String )
0
Kotlin
0
0
9610f84170e89c69fe729acfbba300f971d9020a
756
showmedamoney
Apache License 2.0
app/src/main/java/com/punchthrough/blestarterappandroid/MainActivity.kt
Ricardo2308
473,727,427
false
null
/* * Copyright 2019 Punch Through Design 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 * * 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.punchthrough.blestarterappandroid import android.Manifest import android.app.Activity import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.bluetooth.le.ScanFilter import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import com.punchthrough.blestarterappandroid.ble.ConnectionEventListener import com.punchthrough.blestarterappandroid.ble.ConnectionManager import com.punchthrough.blestarterappandroid.ble.isReadable import com.punchthrough.blestarterappandroid.ble.toHexString import kotlinx.android.synthetic.main.activity_main.scan_button import kotlinx.android.synthetic.main.activity_main.scan_results_recycler_view import org.jetbrains.anko.alert import timber.log.Timber import java.lang.StringBuilder import java.util.Locale private const val ENABLE_BLUETOOTH_REQUEST_CODE = 1 private const val LOCATION_PERMISSION_REQUEST_CODE = 2 class MainActivity : AppCompatActivity() { private var scanForeground: ScanForeground? = null var names = arrayOf("202112055") private val idDevice : String = "202112055" /******************************************* * Properties *******************************************/ private val bluetoothAdapter: BluetoothAdapter by lazy { val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothManager.adapter } private val bleScanner by lazy { bluetoothAdapter.bluetoothLeScanner } private val scanSettings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build() private var isScanning = false set(value) { field = value runOnUiThread { scan_button.text = if (value) "Stop Scan" else "Start Scan" } } private val scanResults = mutableListOf<ScanResult>() private val scanResultAdapter: ScanResultAdapter by lazy { ScanResultAdapter(scanResults) { result -> if (isScanning) { stopBleScan() } with(result.device) { Timber.w("Connecting to $address") ConnectionManager.connect(this, this@MainActivity) } } } private val isLocationPermissionGranted get() = hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) /******************************************* * Activity function overrides *******************************************/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scanForeground = ScanForeground() setContentView(R.layout.activity_main) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } scan_button.setOnClickListener { if (isScanning) stopBleScan() else startBleScan() } setupRecyclerView() title = "Endless Service" findViewById<Button>(R.id.btnStartService).let { it.setOnClickListener { log("START THE FOREGROUND SERVICE ON DEMAND") StartForeground() } } findViewById<Button>(R.id.btnStopService).let { it.setOnClickListener { log("STOP THE FOREGROUND SERVICE ON DEMAND") StopForeground() } } } override fun onResume() { super.onResume() ConnectionManager.registerListener(connectionEventListener) if (!bluetoothAdapter.isEnabled) { promptEnableBluetooth() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { ENABLE_BLUETOOTH_REQUEST_CODE -> { if (resultCode != Activity.RESULT_OK) { promptEnableBluetooth() } } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { LOCATION_PERMISSION_REQUEST_CODE -> { if (grantResults.firstOrNull() == PackageManager.PERMISSION_DENIED) { requestLocationPermission() } else { startBleScan() } } } } /******************************************* * Private functions *******************************************/ private fun promptEnableBluetooth() { if (!bluetoothAdapter.isEnabled) { val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH_REQUEST_CODE) } } fun startBleScan() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isLocationPermissionGranted) { requestLocationPermission() } else { scanResults.clear() scanResultAdapter.notifyDataSetChanged() var filters: MutableList<ScanFilter?>? = null if (names != null) { filters = ArrayList() for (name in names) { val filter = ScanFilter.Builder() .setDeviceName(name) .build() filters.add(filter) } } bleScanner.startScan(filters, scanSettings, scanCallback) isScanning = true } } private fun stopBleScan() { bleScanner.stopScan(scanCallback) isScanning = false } private fun requestLocationPermission() { if (isLocationPermissionGranted) { return } runOnUiThread { alert { title = "Location permission required" message = "Starting from Android M (6.0), the system requires apps to be granted " + "location access in order to scan for BLE devices." isCancelable = false positiveButton(android.R.string.ok) { requestPermission( Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_PERMISSION_REQUEST_CODE ) } }.show() } } private fun setupRecyclerView() { scan_results_recycler_view.apply { adapter = scanResultAdapter layoutManager = LinearLayoutManager( this@MainActivity, RecyclerView.VERTICAL, false ) isNestedScrollingEnabled = false } val animator = scan_results_recycler_view.itemAnimator if (animator is SimpleItemAnimator) { animator.supportsChangeAnimations = false } } /******************************************* * Callback bodies *******************************************/ private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { val indexQuery = scanResults.indexOfFirst { it.device.address == result.device.address } if (indexQuery != -1) { // A scan result already exists with the same address scanResults[indexQuery] = result scanResultAdapter.notifyItemChanged(indexQuery) } else { with(result.device) { Timber.i("Found BLE device! Name: ${name ?: "Unnamed"}, address: $address") ConnectionManager.connect(this, this@MainActivity) } //scanResults.add(result) //scanResultAdapter.notifyItemInserted(scanResults.size - 1) } } override fun onScanFailed(errorCode: Int) { Timber.e("onScanFailed: code $errorCode") } } fun obtenerLectura(device: BluetoothDevice){ val characteristics by lazy { ConnectionManager.servicesOnDevice(device)?.flatMap { service -> service.characteristics ?: listOf() } ?: listOf() } characteristics.map { characteristic -> if (characteristic.isReadable()) { ConnectionManager.readCharacteristic(device, characteristic) } } } private val connectionEventListener by lazy { ConnectionEventListener().apply { onDisconnect = { runOnUiThread { startBleScan() } } onConnectionSetupComplete = { gatt -> obtenerLectura(gatt.device) /* Intent(this@MainActivity, BleOperationsActivity::class.java).also { it.putExtra(BluetoothDevice.EXTRA_DEVICE, gatt.device) startActivity(it) } ConnectionManager.unregisterListener(this) } */ onCharacteristicRead = { _, characteristic -> log( "Read from ${characteristic.uuid}: " + "${hexToASCII(characteristic.value.toHexString().replace(" ", ""))}" ) if (idDevice == hexToASCII(characteristic.value.toHexString().replace(" ", ""))) { with("233341317150396E663544") { if (isNotBlank() && isNotEmpty()) { val bytes = hexToBytes() log("Writing to ${characteristic.uuid}: ${bytes.toHexString()}") ConnectionManager.writeCharacteristic( gatt.device, characteristic, bytes ) } else { log("Please enter a hex payload to write to ${characteristic.uuid}") } } } } } } } private fun hexToASCII(hexValue: String): String? { val output = StringBuilder("") var i = 0 while (i < hexValue.length) { val str = hexValue.substring(i, i + 2) output.append(str.toInt(16).toChar()) i += 2 } return output.toString() } private fun String.hexToBytes() = this.chunked(2).map { it.toUpperCase(Locale.US).toInt(16).toByte() }.toByteArray() /******************************************* * Extension functions *******************************************/ private fun Context.hasPermission(permissionType: String): Boolean { return ContextCompat.checkSelfPermission(this, permissionType) == PackageManager.PERMISSION_GRANTED } private fun Activity.requestPermission(permission: String, requestCode: Int) { ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode) } fun StartForeground(){ actionOnService(Actions.START) } fun StopForeground(){ actionOnService(Actions.STOP) } private fun actionOnService(action: Actions) { if (getServiceState(this) == ServiceState.STOPPED && action == Actions.STOP) return Intent(this, EndlessService::class.java).also { it.action = action.name if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { log("Starting the service in >=26 Mode") startForegroundService(it) return } log("Starting the service in < 26 Mode") startService(it) } } }
0
Kotlin
0
0
ce59a8a933b51f89ff0a52cc9ac3ba285bb50eb6
13,089
PendrogonBLEForeground
Apache License 2.0
app/src/main/java/com/punchthrough/blestarterappandroid/MainActivity.kt
Ricardo2308
473,727,427
false
null
/* * Copyright 2019 Punch Through Design 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 * * 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.punchthrough.blestarterappandroid import android.Manifest import android.app.Activity import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.bluetooth.le.ScanFilter import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import com.punchthrough.blestarterappandroid.ble.ConnectionEventListener import com.punchthrough.blestarterappandroid.ble.ConnectionManager import com.punchthrough.blestarterappandroid.ble.isReadable import com.punchthrough.blestarterappandroid.ble.toHexString import kotlinx.android.synthetic.main.activity_main.scan_button import kotlinx.android.synthetic.main.activity_main.scan_results_recycler_view import org.jetbrains.anko.alert import timber.log.Timber import java.lang.StringBuilder import java.util.Locale private const val ENABLE_BLUETOOTH_REQUEST_CODE = 1 private const val LOCATION_PERMISSION_REQUEST_CODE = 2 class MainActivity : AppCompatActivity() { private var scanForeground: ScanForeground? = null var names = arrayOf("202112055") private val idDevice : String = "202112055" /******************************************* * Properties *******************************************/ private val bluetoothAdapter: BluetoothAdapter by lazy { val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothManager.adapter } private val bleScanner by lazy { bluetoothAdapter.bluetoothLeScanner } private val scanSettings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build() private var isScanning = false set(value) { field = value runOnUiThread { scan_button.text = if (value) "Stop Scan" else "Start Scan" } } private val scanResults = mutableListOf<ScanResult>() private val scanResultAdapter: ScanResultAdapter by lazy { ScanResultAdapter(scanResults) { result -> if (isScanning) { stopBleScan() } with(result.device) { Timber.w("Connecting to $address") ConnectionManager.connect(this, this@MainActivity) } } } private val isLocationPermissionGranted get() = hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) /******************************************* * Activity function overrides *******************************************/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scanForeground = ScanForeground() setContentView(R.layout.activity_main) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } scan_button.setOnClickListener { if (isScanning) stopBleScan() else startBleScan() } setupRecyclerView() title = "Endless Service" findViewById<Button>(R.id.btnStartService).let { it.setOnClickListener { log("START THE FOREGROUND SERVICE ON DEMAND") StartForeground() } } findViewById<Button>(R.id.btnStopService).let { it.setOnClickListener { log("STOP THE FOREGROUND SERVICE ON DEMAND") StopForeground() } } } override fun onResume() { super.onResume() ConnectionManager.registerListener(connectionEventListener) if (!bluetoothAdapter.isEnabled) { promptEnableBluetooth() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { ENABLE_BLUETOOTH_REQUEST_CODE -> { if (resultCode != Activity.RESULT_OK) { promptEnableBluetooth() } } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { LOCATION_PERMISSION_REQUEST_CODE -> { if (grantResults.firstOrNull() == PackageManager.PERMISSION_DENIED) { requestLocationPermission() } else { startBleScan() } } } } /******************************************* * Private functions *******************************************/ private fun promptEnableBluetooth() { if (!bluetoothAdapter.isEnabled) { val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH_REQUEST_CODE) } } fun startBleScan() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isLocationPermissionGranted) { requestLocationPermission() } else { scanResults.clear() scanResultAdapter.notifyDataSetChanged() var filters: MutableList<ScanFilter?>? = null if (names != null) { filters = ArrayList() for (name in names) { val filter = ScanFilter.Builder() .setDeviceName(name) .build() filters.add(filter) } } bleScanner.startScan(filters, scanSettings, scanCallback) isScanning = true } } private fun stopBleScan() { bleScanner.stopScan(scanCallback) isScanning = false } private fun requestLocationPermission() { if (isLocationPermissionGranted) { return } runOnUiThread { alert { title = "Location permission required" message = "Starting from Android M (6.0), the system requires apps to be granted " + "location access in order to scan for BLE devices." isCancelable = false positiveButton(android.R.string.ok) { requestPermission( Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_PERMISSION_REQUEST_CODE ) } }.show() } } private fun setupRecyclerView() { scan_results_recycler_view.apply { adapter = scanResultAdapter layoutManager = LinearLayoutManager( this@MainActivity, RecyclerView.VERTICAL, false ) isNestedScrollingEnabled = false } val animator = scan_results_recycler_view.itemAnimator if (animator is SimpleItemAnimator) { animator.supportsChangeAnimations = false } } /******************************************* * Callback bodies *******************************************/ private val scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { val indexQuery = scanResults.indexOfFirst { it.device.address == result.device.address } if (indexQuery != -1) { // A scan result already exists with the same address scanResults[indexQuery] = result scanResultAdapter.notifyItemChanged(indexQuery) } else { with(result.device) { Timber.i("Found BLE device! Name: ${name ?: "Unnamed"}, address: $address") ConnectionManager.connect(this, this@MainActivity) } //scanResults.add(result) //scanResultAdapter.notifyItemInserted(scanResults.size - 1) } } override fun onScanFailed(errorCode: Int) { Timber.e("onScanFailed: code $errorCode") } } fun obtenerLectura(device: BluetoothDevice){ val characteristics by lazy { ConnectionManager.servicesOnDevice(device)?.flatMap { service -> service.characteristics ?: listOf() } ?: listOf() } characteristics.map { characteristic -> if (characteristic.isReadable()) { ConnectionManager.readCharacteristic(device, characteristic) } } } private val connectionEventListener by lazy { ConnectionEventListener().apply { onDisconnect = { runOnUiThread { startBleScan() } } onConnectionSetupComplete = { gatt -> obtenerLectura(gatt.device) /* Intent(this@MainActivity, BleOperationsActivity::class.java).also { it.putExtra(BluetoothDevice.EXTRA_DEVICE, gatt.device) startActivity(it) } ConnectionManager.unregisterListener(this) } */ onCharacteristicRead = { _, characteristic -> log( "Read from ${characteristic.uuid}: " + "${hexToASCII(characteristic.value.toHexString().replace(" ", ""))}" ) if (idDevice == hexToASCII(characteristic.value.toHexString().replace(" ", ""))) { with("233341317150396E663544") { if (isNotBlank() && isNotEmpty()) { val bytes = hexToBytes() log("Writing to ${characteristic.uuid}: ${bytes.toHexString()}") ConnectionManager.writeCharacteristic( gatt.device, characteristic, bytes ) } else { log("Please enter a hex payload to write to ${characteristic.uuid}") } } } } } } } private fun hexToASCII(hexValue: String): String? { val output = StringBuilder("") var i = 0 while (i < hexValue.length) { val str = hexValue.substring(i, i + 2) output.append(str.toInt(16).toChar()) i += 2 } return output.toString() } private fun String.hexToBytes() = this.chunked(2).map { it.toUpperCase(Locale.US).toInt(16).toByte() }.toByteArray() /******************************************* * Extension functions *******************************************/ private fun Context.hasPermission(permissionType: String): Boolean { return ContextCompat.checkSelfPermission(this, permissionType) == PackageManager.PERMISSION_GRANTED } private fun Activity.requestPermission(permission: String, requestCode: Int) { ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode) } fun StartForeground(){ actionOnService(Actions.START) } fun StopForeground(){ actionOnService(Actions.STOP) } private fun actionOnService(action: Actions) { if (getServiceState(this) == ServiceState.STOPPED && action == Actions.STOP) return Intent(this, EndlessService::class.java).also { it.action = action.name if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { log("Starting the service in >=26 Mode") startForegroundService(it) return } log("Starting the service in < 26 Mode") startService(it) } } }
0
Kotlin
0
0
ce59a8a933b51f89ff0a52cc9ac3ba285bb50eb6
13,089
PendrogonBLEForeground
Apache License 2.0
src/commonMain/kotlin/io/github/optimumcode/json/schema/internal/factories/array/ArrayLengthAssertion.kt
OptimumCode
665,024,908
false
{"Kotlin": 340505}
package io.github.optimumcode.json.schema.internal.factories.array import io.github.optimumcode.json.pointer.JsonPointer import io.github.optimumcode.json.schema.ErrorCollector import io.github.optimumcode.json.schema.ValidationError import io.github.optimumcode.json.schema.internal.AssertionContext import io.github.optimumcode.json.schema.internal.JsonSchemaAssertion import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement internal class ArrayLengthAssertion( private val path: JsonPointer, private val length: Int, private val errorMessage: String, private val check: (Int, Int) -> Boolean, ) : JsonSchemaAssertion { override fun validate(element: JsonElement, context: AssertionContext, errorCollector: ErrorCollector): Boolean { if (element !is JsonArray) { return true } if (check(element.size, length)) { return true } errorCollector.onError( ValidationError( schemaPath = path, objectPath = context.objectPath, message = "array length $errorMessage $length", ), ) return false } }
7
Kotlin
0
5
e3bd94b6002733caf12193ae090882aee0aaf9dc
1,114
json-schema-validator
MIT License
androidApp/home/src/main/java/tech/takahana/iconwallpaper/android/home/ui/screen/viewmodel/HomeSelectImageAssetViewModel.kt
Takahana
435,170,985
false
null
package tech.takahana.iconwallpaper.android.home.ui.screen.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import tech.takahana.iconwallpaper.uilogic.home.HomeSelectImageAssetUiLogic import javax.inject.Inject @HiltViewModel class HomeSelectImageAssetViewModel @Inject constructor( private val uiLogicFactory: HomeSelectImageAssetUiLogic.Factory ) : ViewModel() { val uiLogic: HomeSelectImageAssetUiLogic by lazy { uiLogicFactory.create(viewModelScope) } }
3
Kotlin
0
0
c8f07de65b02a460e494e03fa6df7cc49d1f14de
570
IconWallpaper
MIT License
sample-app/src/androidTest/java/com/atiurin/sampleapp/steps/UiElementsPageSteps.kt
sandrika1910
729,296,024
false
{"Kotlin": 729807, "Java": 13828, "HTML": 2886, "Batchfile": 236, "Shell": 236}
package com.atiurin.sampleapp.steps import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.espresso.matcher.ViewMatchers.isNotChecked import com.atiurin.sampleapp.helper.assertIfViewIsNotDisplayed import com.atiurin.sampleapp.helper.isChecked import com.atiurin.sampleapp.helper.isViewDisplayed import com.atiurin.sampleapp.helper.tap import com.atiurin.sampleapp.helper.waitForViewVisible import com.atiurin.sampleapp.pages.UiElementsPage import com.atiurin.ultron.extensions.isDisplayed import org.junit.Assert object UiElementsPageSteps { fun checkIfPageLoaded(): UiElementsPageSteps { onView(UiElementsPage.webView).check(matches(isDisplayed())) return this } fun unMarkEnableCheckBox(): UiElementsPageSteps { UiElementsPage.checkBoxEnabled.tap(3) return this } fun unMarkClickableCheckBox(): UiElementsPageSteps { UiElementsPage.checkBoxClickable.tap(3) return this } fun checkClickableCheckBoxIsUnmarked(): UiElementsPageSteps { onView(UiElementsPage.checkBoxClickable).check(matches(isNotChecked())) return this } fun checkEnableCheckBoxIsUnmarked(): UiElementsPageSteps { onView(UiElementsPage.checkBoxEnabled).check(matches(isNotChecked())) return this } fun selectInvisibleOption(): UiElementsPageSteps { UiElementsPage.radioInvisibleButton.tap(3) return this } fun validateButtonIsNotVisible(): UiElementsPageSteps { UiElementsPage.button.assertIfViewIsNotDisplayed() return this } }
0
Kotlin
0
0
a2a0606eceea530ab6811b814b946a8a94ebf817
1,753
Testproject
Apache License 2.0
src/test/kotlin/com/spothero/employmentTest/controller/PriceControllerTest.kt
JenkinsMike
447,331,203
false
{"Kotlin": 40919, "Java": 138}
package com.spothero.employmentTest.controller import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest @Disabled() //@RunWith(MockitoJUnitRunner::class) //@SpringBootTest(classes = [PriceController::class]) //@AutoConfigureMockMvc class PriceControllerTest { /** * If I were to have gotten this to work, I would have tested the following: * 1) valid 200 response and * 2) created cases where exceptions were thrown such that I would catch and handle them. */ }
1
Kotlin
0
0
58424ed2f1d415c7145c7011b20b8dc2242994ae
726
Spothero
MIT License
app/src/main/java/com/example/swapi/api/services/PeopleApi.kt
Bavon101
490,179,075
false
null
package com.example.swapi.api.services import com.example.swapi.api.models.People import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query import java.util.concurrent.TimeUnit const val BASE_URL = "https://us-central1-allmen-a006d.cloudfunctions.net/app/" interface PeopleApi { @GET("people") suspend fun getPeople(@Query("query" ) query:String?, @Query("page") page: String?): People companion object { private var peopleApi: PeopleApi? = null private val okHttpClient: OkHttpClient get() = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() fun getInstance(): PeopleApi { if (peopleApi == null) { peopleApi = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build().create(PeopleApi::class.java) } return peopleApi!! } } } interface SearchApi { @GET("search") suspend fun getPeople(@Query("query" ) query:String?): People companion object { var searchApi: SearchApi? = null private val okHttpClient: OkHttpClient get() = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() fun getInstance(): SearchApi { if (searchApi == null) { searchApi = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build().create(SearchApi::class.java) } return searchApi!! } } }
0
Kotlin
0
1
d7f8ba8bff9dc8de8fbbeda4ca0480a5ba51d1c7
2,089
swapi_android-
MIT License
app/src/main/java/com/example/client_server_app/adapters/RecentConversationsAdapter.kt
alprshn
686,412,897
false
{"Kotlin": 82203}
package com.example.client_server_app.adapters import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Base64 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.client_server_app.adapters.UsersAdapter.UserViewHolder import com.example.client_server_app.databinding.ItemContainerRecentConversionBinding import com.example.client_server_app.listeners.ConversionListener import com.example.client_server_app.models.ChatMessage import com.example.client_server_app.models.User /** * @author Alper Sahin * An adapter class for populating a RecyclerView with a list of recent chat conversations. * * @param chatMessages The list of chat messages representing recent conversations. * @param conversionListener The listener to handle conversation item click events. * @property RecentConversationsAdapter the name of this class. * @constructor creates an parameter */ class RecentConversationsAdapter : RecyclerView.Adapter<RecentConversationsAdapter.ConversionViewHolder> { private val chatMessages: List<ChatMessage> private val conversionListener: ConversionListener constructor(chatMessages: List<ChatMessage>, conversionListener: ConversionListener) { this.chatMessages = chatMessages this.conversionListener = conversionListener } /** * Inner class representing a ViewHolder for a recent conversation item in the RecyclerView. * * @param itemView The view representing a recent conversation item. */ inner class ConversionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private lateinit var binding: ItemContainerRecentConversionBinding /** * @constructor that takes a binding object for the recent conversation item view. * * @param itemContainerRecentConversionBinding The binding object for the recent conversation item view. */ constructor(itemContainerRecentConversionBinding: ItemContainerRecentConversionBinding) : this( itemContainerRecentConversionBinding.root ) { binding = itemContainerRecentConversionBinding } /** * Sets the data for a recent conversation item in the ViewHolder. * * @param chatMessage The chat message representing the recent conversation. */ fun SetData(chatMessage: ChatMessage) { binding.imageProfile.setImageBitmap(GetConversionImage(chatMessage.conversionImage)) binding.textName.text = chatMessage.conversionName binding.textRecentMessage.text = chatMessage.message binding.root.setOnClickListener { v -> var user: User = User() user.id = chatMessage.conversionId user.name = chatMessage.conversionName user.image = chatMessage.conversionImage conversionListener.OnConversionClicked(user) } } } /** * Decodes a Base64-encoded image string into a Bitmap. * * @param encodedImage The Base64-encoded image string. * @return A Bitmap representation of the decoded image. */ private fun GetConversionImage(encodedImage: String): Bitmap { val bytes: ByteArray = Base64.decode(encodedImage, Base64.DEFAULT) return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } /** * Creates and returns a new [UserViewHolder] instance for the RecyclerView. * * @param parent The parent ViewGroup in which the ViewHolder will be displayed. * @param viewType The type of view to be created (not used in this implementation). * @return A new [ConversionViewHolder] instance. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConversionViewHolder { return ConversionViewHolder( ItemContainerRecentConversionBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } /** * Returns the number of items in the adapter's data set. * * @return The total number of items in the data set. */ override fun getItemCount(): Int { return chatMessages.size } /** * Binds data to a [ConversionViewHolder] at the specified position. * * @param holder The ViewHolder to bind data to. * @param position The position of the item in the data set. */ override fun onBindViewHolder(holder: ConversionViewHolder, position: Int) { holder.SetData(chatMessages.get(position)) } }
0
Kotlin
0
1
08a5763e23beb9911919c93565dfe5c9f76b39f1
4,680
Kotlin_Client_Server_App
MIT License
src/commonMain/kotlin/com/harry1453/klaunchpad/impl/launchpads/minimk3/LaunchpadMiniMk3.kt
harry1453
246,051,071
false
null
package com.harry1453.klaunchpad.impl.launchpads.minimk3 /** * TODO Launchpad Mini MK3 Support */ public class LaunchpadMiniMk3
0
Kotlin
0
0
2caa063dcb784778720f463a6b58d40966cea89e
131
KLaunchpad
MIT License
ComposeMVISample/app/src/main/java/com/hana/composemvisample/data/di/RepositoryModule.kt
DongChyeon
585,783,153
false
null
package com.hana.composemvisample.data.di import com.hana.composemvisample.data.datasource.GithubDataSource import com.hana.composemvisample.data.repository.GithubRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object RepositoryModule { @Provides @ViewModelScoped fun providesGithubRepository(githubDataSource: GithubDataSource): GithubRepository = GithubRepository(githubDataSource) }
0
Kotlin
1
1
74f849d86af673001960767dfb5bb7261dd46efc
597
Android-Samples
MIT License
app/src/main/java/com/watch/noteapplication/feature_note/domain/use_case/AddNote.kt
ChandanJana
784,058,990
false
{"Kotlin": 43153}
package com.watch.noteapplication.feature_note.domain.use_case import com.watch.noteapplication.feature_note.domain.model.InvalidNoteException import com.watch.noteapplication.feature_note.domain.model.Note import com.watch.noteapplication.feature_note.domain.repository.NoteRepository class AddNote( private val repository: NoteRepository ) { @Throws(InvalidNoteException::class) suspend operator fun invoke(note: Note) { if(note.title.isBlank()) { throw InvalidNoteException("The title of the note can't be empty.") } if(note.content.isBlank()) { throw InvalidNoteException("The content of the note can't be empty.") } repository.insertNote(note) } }
0
Kotlin
0
0
ab6dba2c227079da66b1f3d99c7952cba530f1ca
735
Compose-NoteBook
MIT License
UserCenter/src/main/java/com/kotlin/user/data/protocol/LoginReq.kt
xiao125
140,819,180
false
{"Kotlin": 100467, "Java": 6793}
package com.kotlin.user.data.protocol /** * 登录请求体 */ data class LoginReq(val mobile:String,val pwd:String,val pushId:String)
0
Kotlin
0
0
8b8f75c853651f2952b3b9792e609d050ce5ab54
127
KotlinDemo
Apache License 2.0
bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/controller/AddressController.kt
eclipse-tractusx
526,621,398
false
null
/******************************************************************************* * Copyright (c) 2021,2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.eclipse.tractusx.bpdm.gate.controller import org.eclipse.tractusx.bpdm.common.dto.request.PaginationRequest import org.eclipse.tractusx.bpdm.common.dto.response.PageResponse import org.eclipse.tractusx.bpdm.gate.api.GateAddressApi import org.eclipse.tractusx.bpdm.gate.api.model.AddressGateInputRequest import org.eclipse.tractusx.bpdm.gate.api.model.AddressGateInputResponse import org.eclipse.tractusx.bpdm.gate.api.model.AddressGateOutputRequest import org.eclipse.tractusx.bpdm.gate.api.model.AddressGateOutputResponse import org.eclipse.tractusx.bpdm.gate.config.ApiConfigProperties import org.eclipse.tractusx.bpdm.gate.containsDuplicates import org.eclipse.tractusx.bpdm.gate.service.AddressService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RestController @RestController class AddressController( private val addressService: AddressService, private val apiConfigProperties: ApiConfigProperties ) : GateAddressApi { override fun upsertAddresses(addresses: Collection<AddressGateInputRequest>): ResponseEntity<Unit> { if (addresses.size > apiConfigProperties.upsertLimit || addresses.map { it.externalId }.containsDuplicates()) { return ResponseEntity(HttpStatus.BAD_REQUEST) } if (addresses.any { (it.siteExternalId == null && it.legalEntityExternalId == null) || (it.siteExternalId != null && it.legalEntityExternalId != null) }) { return ResponseEntity(HttpStatus.BAD_REQUEST) } addressService.upsertAddresses(addresses) return ResponseEntity(HttpStatus.OK) } override fun getAddressByExternalId(externalId: String): AddressGateInputResponse { return addressService.getAddressByExternalId(externalId) } override fun getAddressesByExternalIds( paginationRequest: PaginationRequest, externalIds: Collection<String> ): PageResponse<AddressGateInputResponse> { return addressService.getAddresses(page = paginationRequest.page, size = paginationRequest.size, externalIds = externalIds) } override fun getAddresses(paginationRequest: PaginationRequest): PageResponse<AddressGateInputResponse> { return addressService.getAddresses(page = paginationRequest.page, size = paginationRequest.size) } override fun getAddressesOutput( paginationRequest: PaginationRequest, externalIds: Collection<String>? ): PageResponse<AddressGateOutputResponse> { return addressService.getAddressesOutput(externalIds = externalIds, page = paginationRequest.page, size = paginationRequest.size) } override fun putAddressesOutput(addresses: Collection<AddressGateOutputRequest>): ResponseEntity<Unit> { if (addresses.size > apiConfigProperties.upsertLimit || addresses.map { it.externalId }.containsDuplicates()) { return ResponseEntity(HttpStatus.BAD_REQUEST) } addressService.upsertOutputAddresses(addresses) return ResponseEntity(HttpStatus.OK) } }
36
Kotlin
6
2
c279eab5b76bd4db7778ae00af1787f222844129
4,023
bpdm
Apache License 2.0
src/commonMain/kotlin/org/tix/config/data/raw/RawJiraFieldConfiguration.kt
ncipollo
336,920,234
false
{"Kotlin": 601503}
package org.tix.config.data.raw import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import org.tix.serialize.dynamic.DynamicElement @Serializable data class RawJiraFieldConfiguration( val default: Map<String, @Contextual DynamicElement> = mapOf(), val epic: Map<String, @Contextual DynamicElement> = mapOf(), val issue: Map<String, @Contextual DynamicElement> = mapOf(), val task: Map<String, @Contextual DynamicElement> = mapOf(), )
8
Kotlin
0
3
02f87c827c1159af055f5afc5481afd45c013703
481
tix-core
MIT License
buildSrc/src/main/kotlin/App.kt
sanogueralorenzo
115,441,256
false
null
object App { const val petproject = "com.sanogueralorenzo.namingishard" const val sample = "com.sanogueralorenzo.sample" }
3
Kotlin
309
1,599
9c27cce37376148d61394e0a4622521dc8805483
131
Android-Kotlin-Clean-Architecture
Apache License 2.0
app/src/main/java/com/projectAnya/stunthink/presentation/component/selector/PortionSelector.kt
StuntedProject
514,847,131
false
{"Kotlin": 522096}
package com.projectAnya.stunthink.presentation.component.selector import androidx.compose.animation.Crossfade import androidx.compose.foundation.border import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Remove import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun PortionSelector( count: Float, decreaseItemCount: () -> Unit, increaseItemCount: () -> Unit, modifier: Modifier = Modifier ) { Row(modifier = modifier) { Text( text = "Porsi", modifier = Modifier .padding(end = 18.dp) .align(Alignment.CenterVertically) ) IconButton( onClick = decreaseItemCount, modifier = Modifier .align(Alignment.CenterVertically) ) { Icon( modifier = Modifier.border( 1.dp, Color.Black, shape = CircleShape ), imageVector = Icons.Default.Remove, contentDescription = "remove" ) } Crossfade( targetState = count, modifier = Modifier .align(Alignment.CenterVertically) ) { Text( text = "$it", textAlign = TextAlign.Center, modifier = Modifier.widthIn(min = 24.dp) ) } IconButton( onClick = increaseItemCount, modifier = Modifier .align(Alignment.CenterVertically) ) { Icon( modifier = Modifier.border( 1.dp, Color.Black, shape = CircleShape ), imageVector = Icons.Default.Add, contentDescription = "add" ) } } }
0
Kotlin
0
1
fb2cd6cb887908070962c8a4e05c87197c333d53
2,468
Mobile
Freetype Project License
domain/monster/core/src/commonMain/kotlin/br/alexandregpereira/hunter/domain/usecase/GetMonstersUseCase.kt
alexandregpereira
347,857,709
false
{"Kotlin": 1412071, "Swift": 754, "Shell": 139}
/* * Copyright 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 * * 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 br.alexandregpereira.hunter.domain.usecase import br.alexandregpereira.hunter.domain.model.Monster import br.alexandregpereira.hunter.domain.repository.MonsterRepository import kotlinx.coroutines.flow.Flow class GetMonstersUseCase internal constructor( private val repository: MonsterRepository ) { operator fun invoke(): Flow<List<Monster>> { return repository.getLocalMonsters() } }
4
Kotlin
5
85
5256ca9553e070f11a8cde5515afb74503b1a23c
1,004
Monster-Compendium
Apache License 2.0
amazon-chime-sdk/src/test/java/com/amazonaws/services/chime/sdk/meetings/internal/ingestion/EventTypeConvertersTests.kt
aws
249,543,698
false
null
package com.amazonaws.services.chime.sdk.meetings.internal.ingestion import com.amazonaws.services.chime.sdk.meetings.analytics.EventAttributeName import com.amazonaws.services.chime.sdk.meetings.utils.logger.Logger import io.mockk.MockKAnnotations import io.mockk.impl.annotations.MockK import io.mockk.verify import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class EventTypeConvertersTests { private lateinit var eventTypeConverters: EventTypeConverters @MockK private lateinit var logger: Logger @Before fun setup() { MockKAnnotations.init(this, relaxUnitFun = true) eventTypeConverters = EventTypeConverters(logger) } @Test fun `toMeetingEvent should convert json string to object`() { val nameValue = "test name" val deviceNameKey = EventAttributeName.deviceName.toString() val deviceNameValue = "test device" val tsKey = EventAttributeName.timestampMs.toString() val tsValue = 1659759236803 val data = "{\"name\":\"$nameValue\", \"eventAttributes\":{\"$deviceNameKey\":\"$deviceNameValue\", \"$tsKey\":$tsValue}}" val event = eventTypeConverters.toMeetingEvent(data) assertEquals(event.name, nameValue) assertEquals(event.eventAttributes[EventAttributeName.deviceName] as? String, deviceNameValue) assertEquals((event.eventAttributes[EventAttributeName.timestampMs] as? Double ?: 0.0).toLong(), tsValue) } @Test fun `toMeetingEvent should handle null name`() { val data = "{\"name\":null, \"eventAttributes\":{}}" val event = eventTypeConverters.toMeetingEvent(data) assertEquals(event.name, "") } @Test fun `toMeetingEvent should handle malformed name`() { val data = "{\"name\":{}, \"eventAttributes\":{}}" val event = eventTypeConverters.toMeetingEvent(data) verify(exactly = 1) { logger.error(any(), any()) } assertEquals(event.name, "") } @Test fun `toMeetingEvent should handle null event attributes data`() { val nameValue = "test name" val data = "{\"name\":\"$nameValue\", \"eventAttributes\":null}" val event = eventTypeConverters.toMeetingEvent(data) assertEquals(event.eventAttributes.count(), 0) } @Test fun `toMeetingEvent should handle malformed event attributes data`() { val nameValue = "test name" val data = "{\"name\":\"$nameValue\", \"eventAttributes\":\"invalid data\"}" val event = eventTypeConverters.toMeetingEvent(data) verify(exactly = 1) { logger.error(any(), any()) } assertEquals(event.eventAttributes.count(), 0) } @Test fun `fromMeetingEvent should convert object to json string`() { val nameValue = "test name" val deviceNameKey = EventAttributeName.deviceName.toString() val deviceNameValue = "test device" val tsKey = EventAttributeName.timestampMs.toString() val tsValue = 1659759236803 val mockEvent = SDKEvent(nameValue, mutableMapOf( EventAttributeName.deviceName to deviceNameValue, EventAttributeName.timestampMs to tsValue )) val result = eventTypeConverters.fromMeetingEvent(mockEvent) val jsonString = "{\"name\":\"test name\",\"eventAttributes\":{\"$deviceNameKey\":\"$deviceNameValue\",\"$tsKey\":$tsValue}}" assertEquals(result, jsonString) } }
24
Kotlin
44
91
320a98419aa774a4b72d7951ffc47d303879db20
3,481
amazon-chime-sdk-android
Apache License 2.0
support/src/main/java/com/landside/support/extensions/ImageLoadExtension.kt
landscapeside
350,730,923
false
null
package com.landside.support.extensions import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.widget.ImageView import androidx.annotation.DrawableRes import com.bumptech.glide.Glide import com.bumptech.glide.Priority.HIGH import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.bumptech.glide.request.transition.DrawableCrossFadeFactory import com.landside.support.glide.CropCircleTarget import com.landside.support.glide.RotateTransformation import com.landside.support.glide.ScaleTarget import java.io.File fun String.loadImage( context: Context, imgView: ImageView, @DrawableRes errImg: Int = -1, @DrawableRes emptyImg: Int = -1 ) { if (this.isEmpty()) { if (emptyImg != -1) { Glide.with(context) .load(emptyImg) .into(imgView) } return } val glideLoader = Glide.with(context) .load(this) if (errImg != -1) { glideLoader.error(errImg) .placeholder(errImg) .into(imgView) } else { glideLoader.into(imgView) } } fun String.loadImage( context: Context, imgView: ImageView, width: Int, height: Int, @DrawableRes errImg: Int = -1, @DrawableRes emptyImg: Int = -1 ) { if (this.isEmpty()) { if (emptyImg != -1) { Glide.with(context) .load(emptyImg) .into(imgView) } return } val glideLoader = Glide.with(context) .load(this) .override(width, height) .dontAnimate() .dontTransform() .skipMemoryCache(false) .diskCacheStrategy(DiskCacheStrategy.ALL) if (errImg != -1) { glideLoader.error(errImg) .placeholder(errImg) .into(imgView) } else { glideLoader.into(imgView) } } fun Bitmap.loadImage( context: Context, imgView: ImageView, @DrawableRes defaultImg: Int = -1 ) { val glideLoader = Glide.with(context) .load(this) if (defaultImg != -1) { glideLoader.error(defaultImg) .placeholder(defaultImg) .into(imgView) } else { glideLoader.into(imgView) } } fun File.loadImage( context: Context, imgView: ImageView, @DrawableRes defaultImg: Int = -1 ) { val glideLoader = Glide.with(context) .load(this) if (defaultImg != -1) { glideLoader.error(defaultImg) .placeholder(defaultImg) .into(imgView) } else { glideLoader.into(imgView) } } fun Int.loadImage( context: Context, imgView: ImageView ) { val glideLoader = Glide.with(context) .load(this) glideLoader.placeholder(imgView.drawable) .dontAnimate() .into(imgView) } fun Int.loadGif( context: Context, imgView: ImageView ) { val options = RequestOptions() .centerCrop() .priority(HIGH) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) Glide.with(context) .load(this) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { return false } }) .apply(options) .into(imgView) } fun String.loadImageRotated( context: Context, imgView: ImageView ) { val drawableCrossFadeFactory = DrawableCrossFadeFactory.Builder() .setCrossFadeEnabled(true) .build() Glide .with(context) .load(this) .transform(RotateTransformation(180f)) .transition(DrawableTransitionOptions.with(drawableCrossFadeFactory)) .into(imgView) } fun String.loadScaleImage( context: Context, imgView: ImageView, @DrawableRes defaultImg: Int = -1 ) { val glideLoader = Glide.with(context) .asBitmap() .load(this) if (defaultImg != -1) { glideLoader.error(defaultImg) .placeholder(defaultImg) .into(ScaleTarget(imgView)) } else { glideLoader.into(ScaleTarget(imgView)) } } fun String.loadCenterCropImage( context: Context, imgView: ImageView, @DrawableRes defaultImg: Int = -1 ) { val glideLoader = Glide.with(context) .asBitmap() .load(this) .centerCrop() if (defaultImg != -1) { glideLoader.error(defaultImg) .placeholder(defaultImg) .into(imgView) } else { glideLoader.into(imgView) } } fun String.loadCircle( context: Context, imgView: ImageView, @DrawableRes defaultImg: Int = -1 ) { var glideLoader = Glide.with(context) .asBitmap() .load(this) if (defaultImg != -1) { glideLoader = glideLoader.error(defaultImg) .placeholder(defaultImg) } glideLoader .circleCrop() .into(CropCircleTarget(imgView)) }
0
Kotlin
0
0
cf4ea14a78e9dc3e17fa2b42f8e951404822f8b9
5,246
support
MIT License
composeApp/src/commonMain/kotlin/search/presentation/SearchViewModel.kt
Ikutsu
808,480,037
false
{"Kotlin": 238395, "Swift": 608}
package io.ikutsu.osumusic.search.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.ikutsu.osumusic.core.data.getBeatmapBackgroundUrl import io.ikutsu.osumusic.core.domain.DiffBeatmapState import io.ikutsu.osumusic.core.domain.Music import io.ikutsu.osumusic.player.player.OMPlayerController import io.ikutsu.osumusic.player.player.OMPlayerEvent import io.ikutsu.osumusic.search.data.datasource.ApiType import io.ikutsu.osumusic.search.data.repository.SearchRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class SearchViewModel( private val searchRepository: SearchRepository, private val playerController: OMPlayerController ) : ViewModel() { private val _uiState = MutableStateFlow(SearchUiState()) val uiState = _uiState.asStateFlow() fun onTextFieldChange(text: String) { viewModelScope.launch { if (text.isBlank()) { onClearSearch() } _uiState.update { it.copy(searchText = text) } } } fun onSearch() { viewModelScope.launch(Dispatchers.IO) { if (_uiState.value.searchText.isNotBlank()) { _uiState.update { it.copy( isLoading = true, searchContent = SearchUiContent.RESULT ) } searchRepository.search( apiType = ApiType.SAYOBOT, query = _uiState.value.searchText ).onSuccess { data -> _uiState.update { it.copy( isLoading = false, searchResult = data, displaySearchText = if (data.isEmpty()) "No result found" else "Search result for \"${it.searchText}\"" ) } } } } } fun onClearSearch() { viewModelScope.launch { _uiState.update { it.copy( searchText = "", searchContent = SearchUiContent.HISTORY ) } } } fun onSearchItemClick( beatmapState: DiffBeatmapState ) { viewModelScope.launch { playerController.addPlayerItem( listOf( Music( title = beatmapState.title, artist = beatmapState.artist, creator = beatmapState.creator, diff = beatmapState.diff.first(), coverUrl = beatmapState.coverUrl, backgroundUrl = getBeatmapBackgroundUrl(beatmapState.beatmapId), source = beatmapState.audioUrl ) ) ) playerController.onPlayerEvent( OMPlayerEvent.PlayPause ) } } }
0
Kotlin
0
6
88825449bb089bcd31ea0df438ab5750422e05d8
3,221
OsuMusic
MIT License
examples/server-ktor/src/main/kotlin/HelloConfig.kt
rocketraman
363,045,930
false
{"Kotlin": 35639}
data class HelloConfig( val response: String, )
1
Kotlin
0
2
eda5f277df4cb5c5f27489efcdcc96ad5e5131e3
50
bootable
Apache License 2.0
app/src/main/kotlin/com/muedsa/agetv/model/age/AnimeDetailModel.kt
muedsa
713,334,832
false
{"Kotlin": 321497}
package com.muedsa.agetv.model.age import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AnimeDetailModel( @SerialName("id") val id: Int, @SerialName("name_other") val nameOther: String, @SerialName("company") val company: String, @SerialName("name") val name: String, @SerialName("type") val type: String, @SerialName("writer") val writer: String, @SerialName("name_original") val nameOriginal: String, @SerialName("plot") val plot: String, @SerialName("plot_arr") val plotArr: List<String>, @SerialName("playlists") val playLists: Map<String, List<List<String>>>, @SerialName("area") val area: String, @SerialName("letter") val letter: String, @SerialName("website") val website: String, @SerialName("star") val star: Int, @SerialName("status") val status: String, @SerialName("uptodate") val upToDate: String, @SerialName("time_format_1") val timeFormat1: String, @SerialName("time_format_2") val timeFormat2: String, @SerialName("time_format_3") val timeFormat3: String, @SerialName("time") val time: Long, @SerialName("tags") val tags: String, @SerialName("tags_arr") val tagsArr: List<String>, @SerialName("intro") val intro: String, @SerialName("intro_html") val introHtml: String, @SerialName("intro_clean") val introClean: String, @SerialName("series") val series: String, // @SerialName("net_disk") // val netDisk: String, @SerialName("resource") val resource: String, @SerialName("year") val year: Int, @SerialName("season") val season: Int, @SerialName("premiere") val premiere: String, @SerialName("rank_cnt") val rankCnt: String, @SerialName("cover") val cover: String, // ratio 256X356 @SerialName("comment_cnt") val commentCnt: String, @SerialName("collect_cnt") val collectCnt: String )
5
Kotlin
2
3
4ffd6435d30578575ce9479b55e97df6ca0ab590
2,071
AGETV
MIT License
09. Lazy (Bonus)/09.01 Missing setValue/solution.kts
evgeny-trushin
136,894,138
false
{"Kotlin": 15292, "Shell": 3369}
//error: missing 'setValue(Fixme.Home.Companion, KProperty<*>, Fixme.TimeOfOperation)'interface TimeOfOperation { import kotlin.reflect.KProperty interface TimeOfOperation { fun getTime(): Int } enum class Home(var min: Int) : TimeOfOperation { RELAX(59), CLEAN(58); override fun getTime() = min companion object : TimeOfOperation { var defaultValue: TimeOfOperation by lazy { RELAX } override fun getTime() = defaultValue.getTime() } } fun showTimeByDefault(c: TimeOfOperation) { println("Time to clean at ${c.javaClass.getSimpleName()}: ${c.getTime()} min ") } showTimeByDefault(Home)
0
Kotlin
0
0
052845a963dccb788405386e0cef9db0f36bd110
635
Kotlin-Script_CLI_Presentation_Trial-And-Error
MIT License
instantsearch-compose/src/main/java/com/algolia/instantsearch/compose/filter/toggle/internal/FilterToggleStateImpl.kt
algolia
55,971,521
false
{"Kotlin": 689459}
package com.algolia.instantsearch.compose.filter.toggle.internal import com.algolia.instantsearch.compose.filter.toggle.FilterToggleState import com.algolia.instantsearch.compose.internal.trace import com.algolia.instantsearch.compose.selectable.SelectableItemState internal class FilterToggleStateImpl( text: String, isSelected: Boolean ) : FilterToggleState, SelectableItemState<String> by SelectableItemState(text, isSelected) { init { trace() } override fun changeSelection(isSelected: Boolean) { onSelectionChanged?.invoke(isSelected) } }
15
Kotlin
32
156
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
588
instantsearch-android
Apache License 2.0
app/src/main/java/com/theone/demo/data/model/bean/CollectBus.kt
Theoneee
473,409,123
false
{"Kotlin": 616409, "Java": 410498}
package com.theone.demo.data.model.bean /** * 作者 : hegaojian * 时间 : 2020/3/4 * 描述 : */ class CollectBus(var id: Int, var collect: Boolean)
0
Kotlin
4
6
66e7dd671635352c8039bc3bf47a715620347448
143
QMUI-MVVM
Apache License 2.0
src/test/kotlin/clients/ActorClient.kt
frynet
413,667,973
false
{"Kotlin": 119539}
package clients import com.frynet.theatre.data.actors.ActorCreate import com.frynet.theatre.data.actors.ActorInfo import org.springframework.cloud.openfeign.FeignClient import org.springframework.web.bind.annotation.* @FeignClient( name = "actors", url = "\${endpoint.url}" ) @RequestMapping("/actors") interface ActorClient { @GetMapping fun getAllActors(): List<ActorInfo> @GetMapping("/{id}") fun getActorById(@PathVariable id: Long): ActorInfo @PostMapping fun addActor(@RequestBody actor: ActorCreate): ActorInfo @PutMapping("/{id}") fun updateActor(@PathVariable id: Long, actor: ActorCreate): ActorInfo @DeleteMapping fun deleteAllActors() @DeleteMapping("/{id}") fun deleteActor(@PathVariable id: Long) }
0
Kotlin
0
0
bb0bdfa37ed2b76e0c6a9badca128e4fcabd6bde
777
TheatreManager
MIT License
server/src/main/kotlin/org/jetbrains/teamcity/sccache/SCCacheProjectFeatureProvider.kt
JetBrains
305,432,581
false
{"Kotlin": 28412, "Java": 8234}
package org.jetbrains.teamcity.sccache import jetbrains.buildServer.serverSide.InvalidProperty import jetbrains.buildServer.serverSide.PropertiesProcessor import jetbrains.buildServer.serverSide.oauth.OAuthConnectionDescriptor import jetbrains.buildServer.serverSide.oauth.OAuthProvider import jetbrains.buildServer.web.openapi.PluginDescriptor import org.jetbrains.teamcity.sccache.SCCacheConstants.ProjectFeatureSettings class SCCacheProjectFeatureProvider(descriptor: PluginDescriptor) : OAuthProvider() { private val editUrl = descriptor.getPluginResourcesPath("sccache-project.jsp") override fun getType(): String = ProjectFeatureSettings.FEATURE_TYPE override fun getDisplayName(): String = "sccache remote backend connection" override fun getEditParametersUrl(): String = editUrl override fun describeConnection(connection: OAuthConnectionDescriptor): String { return SCCachePresentationProvider.getDescription(connection.parameters) } override fun getPropertiesProcessor(): PropertiesProcessor { return object : PropertiesProcessor { override fun process(properties: MutableMap<String, String>): Collection<InvalidProperty> { val config = getBackendConfigFromFeatureParameters(properties) ?: return listOf(InvalidProperty(ProjectFeatureSettings.BACKEND_TYPE, "Should be specified")) val errors = HashMap<String, String>() config.validate(errors) return errors.map { (name, msg) -> InvalidProperty(name, msg) } } } } override fun getDefaultProperties(): MutableMap<String, String>? { return null } }
0
Kotlin
4
1
7c2f246990efc2a02111edb3147d5dffa06068ad
1,700
teamcity-sccache-plugin
Apache License 2.0
kotlin/src/main/kotlin/com/example/coroutineServer/web/controller/SomeProcessController.kt
retheviper
499,837,316
false
null
package com.example.coroutineServer.web.controller import com.example.coroutineServer.domain.service.SomeProcessService import com.example.coroutineServer.web.model.request.SomeProcessRequest import com.example.coroutineServer.web.model.response.SomeProcessResponse import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController @RestController class SomeProcessController( private val someProcessService: SomeProcessService ) { @PostMapping("/some-process") fun someProcess(@RequestBody request: SomeProcessRequest): SomeProcessResponse { val dto = someProcessService.process(request.id) return SomeProcessResponse( id = dto.id, result = dto.result ) } }
0
Kotlin
0
2
10beb85fa8ae84a599c85e56a22888d5277342bc
839
AsyncServerExample
MIT License
app/src/main/java/com/app/desafiodourado/feature/initial/data/InitialRepository.kt
maeceloacm1998
722,401,741
false
{"Kotlin": 241880}
package com.app.desafiodourado.feature.initial.data import com.app.desafiodourado.core.firebase.models.UserModel interface InitialRepository { suspend fun createUserInFirebase(user: UserModel): Result<Boolean> suspend fun createChallengers(id: String): Result<Boolean> suspend fun createMissions(id: String): Result<Boolean> }
0
Kotlin
0
0
436c024443452ebe87d073778ff6e0002666b40b
340
Desafio-Dourado
MIT License
app/src/test/java/com/example/android/architecture/blueprints/todoapp/LiveDataTestUtil.kt
YChaeeun
380,507,092
false
null
package com.example.android.architecture.blueprints.todoapp import androidx.annotation.VisibleForTesting import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException // https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04 @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun <T> LiveData<T>.getOrAwaitValue( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS, afterObserve: () -> Unit = {} ): T { var data: T? = null val latch = CountDownLatch(1) // observe LiveData until it receives new Value val observer = object : Observer<T> { override fun onChanged(t: T) { data = t latch.countDown() // once value updated, remove observer this@getOrAwaitValue.removeObserver(this) } } this.observeForever(observer) try { afterObserve.invoke() // if the value is never set within 2 seconds, throws exception if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData Never Set") } } finally { this.removeObserver(observer) } @Suppress("UNCHECKED_CAST") return data as T }
0
Kotlin
0
0
7e35d3bf57d5f1fb5ed7520fce8a7dcaeaba399d
1,226
android-testing-codelab
Apache License 2.0
app/src/main/java/dev/rdnt/m8face/utils/VerticalComplication.kt
rdnt
585,996,555
false
null
package dev.rdnt.m8face.utils import android.content.Context import android.graphics.* import android.util.Log import androidx.core.content.ContextCompat import androidx.core.graphics.ColorUtils import androidx.core.graphics.drawable.toBitmap import androidx.wear.watchface.CanvasComplication import androidx.wear.watchface.CanvasComplicationFactory import androidx.wear.watchface.RenderParameters import androidx.wear.watchface.complications.data.* import dev.rdnt.m8face.R import java.time.Instant import java.time.ZonedDateTime class VerticalComplication(private val context: Context) : CanvasComplication { var tertiaryColor: Int = Color.parseColor("#8888bb") set(tertiaryColor) { field = tertiaryColor textPaint.color = tertiaryColor titlePaint.color = tertiaryColor iconPaint.colorFilter = PorterDuffColorFilter(tertiaryColor, PorterDuff.Mode.SRC_IN) prefixPaint.color = tertiaryColor prefixPaint.alpha = 100 } var opacity: Float = 1f set(opacity) { field = opacity val color = ColorUtils.blendARGB(Color.TRANSPARENT, tertiaryColor, opacity) textPaint.color = color titlePaint.color = color iconPaint.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) imagePaint.alpha = (opacity * 255).toInt() prefixPaint.color = color prefixPaint.alpha = 100 } private val textPaint = Paint().apply { isAntiAlias = true typeface = context.resources.getFont(R.font.m8stealth57) textAlign = Paint.Align.LEFT color = tertiaryColor } private val titlePaint = Paint().apply { isAntiAlias = true typeface = context.resources.getFont(R.font.m8stealth57) textAlign = Paint.Align.LEFT color = tertiaryColor } private val iconPaint = Paint().apply { colorFilter = PorterDuffColorFilter(tertiaryColor, PorterDuff.Mode.SRC_IN) } private val imagePaint = Paint() private val prefixPaint = Paint().apply { isAntiAlias = true typeface = context.resources.getFont(R.font.m8stealth57) textAlign = Paint.Align.LEFT color = Color.parseColor("#343434") alpha = 127 } override fun render( canvas: Canvas, bounds: Rect, zonedDateTime: ZonedDateTime, renderParameters: RenderParameters, slotId: Int ) { if (bounds.isEmpty) return when (data.type) { ComplicationType.SHORT_TEXT -> { renderShortTextComplication(canvas, bounds, data as ShortTextComplicationData) } ComplicationType.MONOCHROMATIC_IMAGE -> { renderMonochromaticImageComplication( canvas, bounds, data as MonochromaticImageComplicationData ) } ComplicationType.SMALL_IMAGE -> { renderSmallImageComplication(canvas, bounds, data as SmallImageComplicationData) } else -> return } } private fun renderShortTextComplication( canvas: Canvas, bounds: Rect, data: ShortTextComplicationData, ) { val now = Instant.now() var text = data.text.getTextAt(context.resources, now).toString().uppercase() if (text == "--") { return } val isBattery = data.dataSource?.className == "com.google.android.clockwork.sysui.experiences.complications.providers.BatteryProviderService" val threeDigit = isBattery var title: String? = null var icon: Bitmap? = null var iconBounds = Rect() if (isBattery) { val drawable = ContextCompat.getDrawable(context, R.drawable.battery_icon_32)!! icon = drawable.toBitmap( (32f / 78f * bounds.width()).toInt(), (32f / 78f * bounds.width()).toInt() ) iconBounds = Rect(0, 0, (32f / 78f * bounds.width()).toInt(), (32f / 78f * bounds.width()).toInt()) } else if (data.monochromaticImage != null) { val drawable = data.monochromaticImage!!.image.loadDrawable(context) if (drawable != null) { val size = (bounds.width().coerceAtMost(bounds.height()).toFloat() / 2f).toInt() icon = drawable.toBitmap(size, size) iconBounds = Rect(0, 0, size, size) } } var prefixLen = 0 if (threeDigit) { prefixLen = 3 - text.length text = text.padStart(3, ' ') } if (data.title != null && !data.title!!.isPlaceholder()) { title = data.title!!.getTextAt(context.resources, now).toString().uppercase() } if (text.length <= 3) { textPaint.textSize = 24F / 78F * bounds.width() } else if (text.length <= 6) { textPaint.textSize = 16F / 78F * bounds.width() } else { textPaint.textSize = 12F / 78F * bounds.width() } val textBounds = Rect() if (threeDigit) { textPaint.getTextBounds("000", 0, 3, textBounds) } else { textPaint.getTextBounds(text, 0, text.length, textBounds) } val titleBounds = Rect() if (title != null) { if (title.length <= 3) { titlePaint.textSize = 24F / 78F * bounds.width() } else if (title.length <= 6) { titlePaint.textSize = 16F / 78F * bounds.width() } else { titlePaint.textSize = 12F / 78F * bounds.width() } titlePaint.getTextBounds(title, 0, title.length, titleBounds) } var iconOffsetY = 0f var titleOffsetY = 0f var textOffsetY = 0f if (icon != null) { val height = iconBounds.height() + textBounds.height() iconOffsetY = (height - iconBounds.height()).toFloat() / 2f textOffsetY = (height - textBounds.height()).toFloat() / 2f iconOffsetY += 9f / 132f * bounds.height() if (isBattery) { iconOffsetY = iconOffsetY.toInt().toFloat() } textOffsetY += 9f / 132f * bounds.height() } else if (title != null) { val height = titleBounds.height() + textBounds.height() titleOffsetY = (height - titleBounds.height()).toFloat() / 2f textOffsetY = (height - textBounds.height()).toFloat() / 2f titleOffsetY += 9f / 132f * bounds.height() textOffsetY += 9f / 132f * bounds.height() } if (icon != null) { val dstRect = RectF( bounds.exactCenterX() - iconBounds.width() / 2, bounds.exactCenterY() - iconBounds.height() / 2 - iconOffsetY, bounds.exactCenterX() + iconBounds.width() / 2, bounds.exactCenterY() + iconBounds.height() / 2 - iconOffsetY, ) canvas.drawBitmap(icon, iconBounds, dstRect, iconPaint) } else if (title != null) { canvas.drawText( title, bounds.exactCenterX() - titleBounds.width() / 2, bounds.exactCenterY() + titleBounds.height() / 2 - titleOffsetY, titlePaint ) } if (prefixLen > 0) { val prefix = "".padStart(prefixLen, '0') prefixPaint.textSize = textPaint.textSize canvas.drawText( prefix, bounds.exactCenterX() - textBounds.width() / 2, bounds.exactCenterY() + textBounds.height() / 2 + textOffsetY, prefixPaint ) } canvas.drawText( text, bounds.exactCenterX() - textBounds.width() / 2, bounds.exactCenterY() + textBounds.height() / 2 + textOffsetY, textPaint ) } private fun renderMonochromaticImageComplication( canvas: Canvas, bounds: Rect, data: MonochromaticImageComplicationData, ) { val icon: Bitmap val iconBounds: Rect val drawable = data.monochromaticImage.image.loadDrawable(context) ?: return val size = (bounds.width().coerceAtMost(bounds.height()).toFloat() * 0.8f).toInt() icon = drawable.toBitmap(size, size) iconBounds = Rect(0, 0, size, size) val dstRect = RectF( bounds.exactCenterX() - iconBounds.width() / 2, bounds.exactCenterY() - iconBounds.height() / 2, bounds.exactCenterX() + iconBounds.width() / 2, bounds.exactCenterY() + iconBounds.height() / 2, ) canvas.drawBitmap(icon, iconBounds, dstRect, iconPaint) } private fun renderSmallImageComplication( canvas: Canvas, bounds: Rect, data: SmallImageComplicationData, ) { val icon: Bitmap val iconBounds: Rect val drawable = data.smallImage.image.loadDrawable(context) ?: return val size = (bounds.width().coerceAtMost(bounds.height()).toFloat() * 0.75f).toInt() icon = drawable.toBitmap(size, size) iconBounds = Rect(0, 0, size, size) val dstRect = RectF( bounds.exactCenterX() - iconBounds.width() / 2, bounds.exactCenterY() - iconBounds.height() / 2, bounds.exactCenterX() + iconBounds.width() / 2, bounds.exactCenterY() + iconBounds.height() / 2, ) canvas.drawBitmap(icon, iconBounds, dstRect, imagePaint) } override fun drawHighlight( canvas: Canvas, bounds: Rect, boundsType: Int, zonedDateTime: ZonedDateTime, color: Int ) { } private var data: ComplicationData = NoDataComplicationData() override fun getData(): ComplicationData = data override fun loadData( complicationData: ComplicationData, loadDrawablesAsynchronous: Boolean ) { data = complicationData } } fun createVerticalComplicationFactory(context: Context) = CanvasComplicationFactory { _, _ -> VerticalComplication(context) }
8
null
1
9
fc5629da88acb66a90af7224f2c5dfc93f22d665
9,178
m8
MIT License
ExoPlayer_end/app/src/main/java/com/linkedin/exoplayer/MainActivity.kt
rootofmylife
415,455,956
false
null
package com.linkedin.exoplayer import android.net.Uri import android.os.Bundle import android.support.annotation.RawRes import android.support.v7.app.AppCompatActivity import com.google.android.exoplayer2.* import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.source.MediaSource import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.upstream.DataSource import com.google.android.exoplayer2.upstream.DataSpec import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.upstream.RawResourceDataSource import com.google.android.exoplayer2.util.Util import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { lateinit var videoExoPlayer: SimpleExoPlayer lateinit var audioExoPlayer: SimpleExoPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createVideoPlayer() createAudioPlayer() setupVideoPlayer() setupAudioPlayer(URL) play.setOnClickListener { audioExoPlayer.playWhenReady = true } pause.setOnClickListener { audioExoPlayer.playWhenReady = false } playerView.player = videoExoPlayer } fun setupAudioPlayer(url: String) { audioExoPlayer.prepare(createUrlMediaSource(url)) } fun setupVideoPlayer() { videoExoPlayer.prepare(createRawMediaSource(R.raw.sports)) } fun createVideoPlayer() { val trackSelector = DefaultTrackSelector() val loadControl = DefaultLoadControl() val renderersFactory = DefaultRenderersFactory(this) videoExoPlayer = ExoPlayerFactory.newSimpleInstance( this, renderersFactory, trackSelector, loadControl ) videoExoPlayer.videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING } fun createAudioPlayer() { val trackSelector = DefaultTrackSelector() val loadControl = DefaultLoadControl() val renderersFactory = DefaultRenderersFactory(this) audioExoPlayer = ExoPlayerFactory.newSimpleInstance( this, renderersFactory, trackSelector, loadControl ) } fun createUrlMediaSource(url: String): MediaSource { val userAgent = Util.getUserAgent(this, getString(R.string.app_name)) return ExtractorMediaSource .Factory(DefaultDataSourceFactory(this, userAgent)) .setExtractorsFactory(DefaultExtractorsFactory()) .createMediaSource(Uri.parse(url)) } fun createRawMediaSource(@RawRes rawId: Int): MediaSource { val rawResourceDataSource = RawResourceDataSource(this) val dataSpec = DataSpec(RawResourceDataSource.buildRawResourceUri(rawId)) rawResourceDataSource.open(dataSpec) return ExtractorMediaSource.Factory(DataSource.Factory { rawResourceDataSource }).createMediaSource(rawResourceDataSource.uri) } companion object { const val URL = "https://791353.youcanlearnit.net/EC_podcast.mp3" } }
0
Kotlin
0
0
7470d9baf6b9874d877a06a6d1e7dfd6ba454528
3,327
android-audio-video
MIT License
app/src/main/java/com/ezzy/adanianpixabay/data/repository/OfflineImageRepositoryImpl.kt
EzekielWachira
437,988,176
false
{"Kotlin": 54259}
package com.ezzy.adanianpixabay.data.repository import com.ezzy.adanianpixabay.common.Resource import com.ezzy.adanianpixabay.data.local.dao.ImageDao import com.ezzy.adanianpixabay.domain.model.Image import com.ezzy.adanianpixabay.domain.repository.OfflineImageRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class OfflineImageRepositoryImpl @Inject constructor( private val imageDao: ImageDao ): OfflineImageRepository { override suspend fun insertImage(images: List<Image>) { return imageDao.insertImageToCache(images) } override fun getImages(): Flow<List<Image>> { return imageDao.getImagesFromCache() } override fun searchImage(keyword: String): Flow<List<Image>> { return imageDao.searchImages(keyword) } override suspend fun deleteImage(image: Image) { return imageDao.deleteImageFromCache(image) } override suspend fun deleteAllImages() { return imageDao.deleteAllImages() } }
0
Kotlin
0
1
d9fe762a6a2cc293fbf234befd22d2df8f12335a
1,001
Adalabs-Pixabay
MIT License
app/src/main/java/com/devspush/atom/components/card/fragment/StyledCardFragment.kt
devspush
253,251,162
false
null
package com.devspush.atom.components.card.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.devspush.atom.R import com.devspush.atom.components.card.adapter.StyledCardAdapter import com.devspush.atom.components.card.interfaces.OnItemClickListener import com.devspush.atom.components.card.model.StyledCardItem import kotlinx.android.synthetic.main.fragment_content_list.view.* class StyledCardFragment : Fragment(), OnItemClickListener { private lateinit var viewLayout: View private lateinit var items: ArrayList<StyledCardItem> private lateinit var adapter: StyledCardAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) items = arguments?.getParcelableArrayList(CARD_STYLED_DATA) ?: arrayListOf() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { loadView(inflater.inflate(R.layout.fragment_content_list, container, false)) return this.viewLayout } private fun loadView(view: View) { viewLayout = view adapter = StyledCardAdapter(items) adapter.setOnItemClickListener(this) viewLayout.rvList.layoutManager = LinearLayoutManager(view.context) viewLayout.rvList.adapter = adapter } override fun onItemClick(item: StyledCardItem) { Toast.makeText(viewLayout.context, item.title, Toast.LENGTH_SHORT).show() } override fun onCommentsClick() { Toast.makeText(viewLayout.context, R.string.on_comment_click, Toast.LENGTH_SHORT).show() } companion object { const val CARD_STYLED_DATA = "CARD_STYLED_DATA" fun newInstance(viewItems: ArrayList<StyledCardItem>): StyledCardFragment { val fragment = StyledCardFragment() val args = Bundle() args.putParcelableArrayList(CARD_STYLED_DATA, viewItems) fragment.arguments = args return fragment } } }
0
Kotlin
0
0
5d3baf4bb9aa31b9db4b31e334d3074af408d6a3
2,225
atom-android-single-page
MIT License
services/csm.cloud.project.project/src/test/kotlin/com/bosch/pt/iot/smartsite/project/importer/boundary/ImportTaskIntegrationTest.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: Robert Bosch Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.importer.boundary import com.bosch.pt.csm.cloud.projectmanagement.craft.messages.ProjectCraftEventEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.craft.messages.ProjectCraftEventG2Avro import com.bosch.pt.csm.cloud.projectmanagement.craft.messages.ProjectCraftListEventAvro import com.bosch.pt.csm.cloud.projectmanagement.craft.messages.ProjectCraftListEventEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.external.messages.ExternalIdEventAvro import com.bosch.pt.csm.cloud.projectmanagement.external.messages.ExternalIdEventEnumAvro import com.bosch.pt.csm.cloud.projectmanagement.importer.messages.ProjectImportFinishedEventAvro import com.bosch.pt.csm.cloud.projectmanagement.importer.messages.ProjectImportStartedEventAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventEnumAvro.ACCEPTED import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventEnumAvro.CREATED import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskEventEnumAvro.STARTED import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskScheduleEventAvro import com.bosch.pt.csm.cloud.projectmanagement.task.messages.TaskScheduleEventEnumAvro import com.bosch.pt.iot.smartsite.application.config.EnableAllKafkaListeners import com.bosch.pt.iot.smartsite.common.event.setupDatasetTestData import com.bosch.pt.iot.smartsite.common.test.FileSource import com.bosch.pt.iot.smartsite.project.importer.submitProjectImportFeatureToggle import com.bosch.pt.iot.smartsite.project.project.ProjectId import com.bosch.pt.iot.smartsite.project.project.facade.rest.ProjectController import com.bosch.pt.iot.smartsite.project.project.shared.repository.ProjectRepository import com.bosch.pt.iot.smartsite.project.task.shared.model.Task.Companion.MAX_DESCRIPTION_LENGTH import com.bosch.pt.iot.smartsite.project.task.shared.model.Task.Companion.MAX_NAME_LENGTH import com.bosch.pt.iot.smartsite.project.task.shared.model.TaskStatusEnum import com.bosch.pt.iot.smartsite.project.task.shared.repository.TaskRepository import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.params.ParameterizedTest import org.springframework.beans.factory.annotation.Autowired import org.springframework.core.io.Resource import org.springframework.data.domain.Pageable.unpaged @EnableAllKafkaListeners class ImportTaskIntegrationTest : AbstractImportIntegrationTest() { @Autowired private lateinit var projectImportService: ProjectImportService @Autowired private lateinit var projectRepository: ProjectRepository @Autowired private lateinit var taskRepository: TaskRepository @Autowired private lateinit var projectController: ProjectController private val projectIdentifier = ProjectId() private val project by lazy { projectRepository.findOneByIdentifier(projectIdentifier)!! } @BeforeEach fun init() { eventStreamGenerator.setupDatasetTestData().submitProjectImportFeatureToggle() setAuthentication("userCsm1") projectController.createProject(projectIdentifier, createDefaultSaveProjectResource()) projectEventStoreUtils.reset() } @FileSource( container = "project-import-testdata", files = [ "task-with-empty-name.pp", "task-with-empty-name.mpp", "task-with-empty-name.xer", "task-with-empty-name-ms.xml", "task-with-empty-name-p6.xml"]) @ParameterizedTest fun `verify a task with empty name is imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), true, null, null, null, null) val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content tasks.apply { assertThat(this).hasSize(1) assertThat(this.first().name).isEqualTo("Unnamed Task") } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, CREATED, 1, false) .map { it.aggregate.name } .all { it == "Unnamed Task" } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftListEventAvro::class.java, ProjectCraftListEventEnumAvro.ITEMADDED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyNumberOfEvents(7) } // In P6 you cannot create tasks without names. @FileSource( container = "project-import-testdata", files = [ "task-2-tasks-without-name.pp", "task-2-tasks-without-name.mpp", "task-2-tasks-without-name-ms.xml"]) @ParameterizedTest fun `verify a task without name is imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), true, null, null, null, null) val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content tasks.apply { assertThat(this).hasSize(2) assertThat(this.first().name).isEqualTo("Unnamed Task") } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, CREATED, 2, false) .map { it.aggregate.name } .all { listOf("Unnamed Task", "<New Task>").contains(it) } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 2, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftListEventAvro::class.java, ProjectCraftListEventEnumAvro.ITEMADDED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, 2, false) projectEventStoreUtils.verifyNumberOfEvents(10) } @FileSource( container = "project-import-testdata", files = [ "task-with-name-too-long.pp", "task-with-name-too-long.mpp", "task-with-name-too-long.xer", "task-with-name-too-long-ms.xml", "task-with-name-too-long-p6.xml"]) @ParameterizedTest fun `verify a task with too long name is imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), true, null, null, null, null) val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content tasks.apply { assertThat(this).hasSize(1) assertThat(this.first().name) .isEqualTo("Task name is too long. ".repeat(5).take(MAX_NAME_LENGTH)) } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, CREATED, 1, false) .map { it.aggregate.name } .all { it.startsWith("Task name is too long.") } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftListEventAvro::class.java, ProjectCraftListEventEnumAvro.ITEMADDED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyNumberOfEvents(7) } // There doesn't seem to be a "notes" column in P6, therefore we don't test it. @FileSource( container = "project-import-testdata", files = ["task-with-note.pp", "task-with-note.mpp", "task-with-note-ms.xml"]) @ParameterizedTest fun `verify a task with note is imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), true, null, null, null, null) val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content tasks.apply { assertThat(this).hasSize(1) assertThat(this.first().name).isEqualTo("task1") assertThat(this.first().description).isEqualTo("This is a note.") } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, CREATED, 1, false) .map { it.aggregate.name } .all { it == "task1" } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftListEventAvro::class.java, ProjectCraftListEventEnumAvro.ITEMADDED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyNumberOfEvents(7) } // There doesn't seem to be a "notes" column in P6, therefore we don't test it. @FileSource( container = "project-import-testdata", files = [ "task-with-note-too-long.pp", "task-with-note-too-long.mpp", "task-with-note-too-long-ms.xml"]) @ParameterizedTest fun `verify a task with too long note is imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), false, null, null, null, null) val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content tasks.apply { assertThat(this).hasSize(1) assertThat(this.first().name).isEqualTo("task1") assertThat(this.first().description) .isEqualTo("This note is too long. ".repeat(44).take(MAX_DESCRIPTION_LENGTH)) } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, CREATED, 1, false) .map { it.aggregate.name } .all { it == "task1" } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains( ProjectCraftListEventAvro::class.java, ProjectCraftListEventEnumAvro.ITEMADDED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyNumberOfEvents(7) } @FileSource( container = "project-import-testdata", files = [ "empty-project.pp", "empty-project.mpp", "empty-project.xer", "empty-project-ms.xml", "empty-project-p6.xml"]) @ParameterizedTest fun `verify an empty project can be processed but nothing is imported`(file: Resource) { projectImportService.import(project, readProject(file), false, null, null, null, null) projectEventStoreUtils.verifyEmpty() } @FileSource( container = "project-import-testdata", files = [ "task-with-status.pp", "task-with-status.mpp", "task-with-status.xer", "task-with-status-ms.xml", "task-with-status-p6.xml"]) @ParameterizedTest fun `verify tasks with status are imported successfully`(file: Resource) { projectImportService.import(project, readProject(file), true, null, null, null, null) val isPP = file.file.name.endsWith(".pp") val expectedCount = if (isPP) 4 else 3 val tasks = taskRepository.findAllByProjectIdentifier(projectIdentifier, unpaged()).content assertThat(tasks).hasSize(expectedCount) val taskNotStarted = tasks.singleOrNull { it.name == "taskNotStarted" } assertThat(taskNotStarted).isNotNull assertThat(taskNotStarted?.status).isEqualTo(TaskStatusEnum.DRAFT) val taskStarted = tasks.singleOrNull { it.name == "taskStarted" } assertThat(taskStarted).isNotNull assertThat(taskStarted?.status).isEqualTo(TaskStatusEnum.STARTED) val taskFinished = tasks.singleOrNull { it.name == "taskFinished" } assertThat(taskFinished).isNotNull assertThat(taskFinished?.status).isEqualTo(TaskStatusEnum.ACCEPTED) projectEventStoreUtils.verifyContains(TaskEventAvro::class.java, CREATED, expectedCount, false) projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, STARTED, 1, false) .map { it.aggregate.name } .all { it == "taskStarted" } projectEventStoreUtils .verifyContainsAndGet(TaskEventAvro::class.java, ACCEPTED, 1, false) .map { it.aggregate.name } .all { it == "taskFinished" } projectEventStoreUtils.verifyContains( TaskScheduleEventAvro::class.java, TaskScheduleEventEnumAvro.CREATED, 3, false) projectEventStoreUtils.verifyContains( ProjectCraftEventG2Avro::class.java, ProjectCraftEventEnumAvro.CREATED, 1, false) projectEventStoreUtils.verifyContains(ProjectImportStartedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ProjectImportFinishedEventAvro::class.java, null, 1, false) projectEventStoreUtils.verifyContains( ExternalIdEventAvro::class.java, ExternalIdEventEnumAvro.CREATED, expectedCount, false) projectEventStoreUtils.verifyNumberOfEvents(if (isPP) 17 else 15) } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
15,090
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/code/flower/GardenFragment.kt
cydear
198,600,612
false
null
package com.code.flower import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment /** * [类功能说明] * * @author lary.huang * @version v 1.4.8 2019-07-30 XLXZ Exp $ * @email <EMAIL> */ class GardenFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_garden, container,false) return view } }
0
Kotlin
0
0
69ceac77dd7175915d892f07dbbfea66e76abf15
542
android-flower
Apache License 2.0
app/src/main/java/com/isanz/inmomarket/ui/chat/ChatFragment.kt
Zenin0
777,260,226
false
{"Kotlin": 143186}
package com.isanz.inmomarket.ui.chat import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.isanz.inmomarket.InmoMarket import com.isanz.inmomarket.databinding.FragmentChatBinding import com.isanz.inmomarket.rv.chatItem.ChatListAdapter import kotlinx.coroutines.launch class ChatFragment : Fragment() { private lateinit var mBinding: FragmentChatBinding private lateinit var idChat: String private lateinit var recipientId: String private val chatViewModel: ChatViewModel by lazy { ViewModelProvider(this)[ChatViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) idChat = requireArguments().getString("idChat")!! recipientId = InmoMarket.getAuth().currentUser?.uid!! } @RequiresApi(Build.VERSION_CODES.O) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { mBinding = FragmentChatBinding.inflate(inflater, container, false) setUpView() return mBinding.root } @RequiresApi(Build.VERSION_CODES.O) private fun setUpView() { setUpOtherUser() setUpButtons() setUpRecyclerView() } private fun setUpOtherUser() = lifecycleScope.launch { val users = chatViewModel.getUsersInConversation(idChat).await() val otherUser = users.find { it.uid != InmoMarket.getAuth().currentUser!!.uid } mBinding.tvNameChat.text = otherUser?.displayName otherUser?.photoUrl?.let { loadImage(it) } } private fun setUpRecyclerView() { val adapter = ChatListAdapter() val layoutManager = LinearLayoutManager(context) mBinding.recyclerView.layoutManager = layoutManager mBinding.recyclerView.adapter = adapter observeMessages(adapter) chatViewModel.retrieveMessages(idChat) } private fun observeMessages(adapter: ChatListAdapter) { chatViewModel.messageList.observe(viewLifecycleOwner) { messages -> adapter.submitList(messages) { val lastPosition = messages.size - 1 if (lastPosition >= 0) { mBinding.recyclerView.scrollToPosition(lastPosition) } } } } private fun loadImage(imageUri: String) { Glide.with(this).load(imageUri).circleCrop().into(mBinding.ivProfileChat) } @RequiresApi(Build.VERSION_CODES.O) private fun setUpButtons() { mBinding.fabSendMessage.setOnClickListener { sendMessage() } mBinding.ibBack.setOnClickListener { navigateBack() } } @RequiresApi(Build.VERSION_CODES.O) private fun sendMessage() { val text = mBinding.tieMessage.text.toString() chatViewModel.sendMessage(text, idChat, recipientId) mBinding.tieMessage.text?.clear() } private fun navigateBack() { this.findNavController().popBackStack() } }
0
Kotlin
0
1
02689b6d62a56d2e509044b6226870bdffe132fc
3,421
InmoMarket
Creative Commons Zero v1.0 Universal
backend/src/main/kotlin/de/predic8/openapicatalogbackend/repository/document/ReportRepository.kt
membrane
845,459,914
false
{"Kotlin": 49328, "Vue": 24276, "TypeScript": 13326, "JavaScript": 2766, "HTML": 982, "SCSS": 777}
package de.predic8.openapicatalogbackend.repository.document import de.predic8.openapicatalogbackend.model.entity.document.Report import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import java.util.* @Repository interface ReportRepository : JpaRepository<Report, UUID>
0
Kotlin
0
1
223dd88fdf178104b32c74c8b322fa05b4706aa4
330
openapi-catalog
Apache License 2.0
app/src/main/java/dev/jahidhasanco/fliq/ui/fragments/ProfileFragment.kt
JahidHasanCO
405,033,258
false
{"Kotlin": 72063}
package dev.jahidhasanco.fliq.ui.fragments import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dev.jahidhasanco.fliq.R import dev.jahidhasanco.fliq.ui.activity.LoginActivity class ProfileFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_profile, container, false) startActivity(Intent(context, LoginActivity::class.java)) return view } }
2
Kotlin
4
19
e08959114ace3d85c8454cfc56e086a23b35857f
718
Fliq.-The-Movie-DB
MIT License
app/src/main/java/dev/abbasian/applyhistory/ui/company/CompanyViewState.kt
MahdiAbbasian
776,492,945
false
{"Kotlin": 74395}
package dev.abbasian.applyhistory.ui.company import dev.abbasian.applyhistory.domain.model.CompanyEntity sealed class CompanyViewState { object Loading : CompanyViewState() data class Success(val companies: List<CompanyEntity>) : CompanyViewState() data class Error(val message: String) : CompanyViewState() }
0
Kotlin
0
2
14015250821265ae0e39460251acf8f257629040
324
ApplyHistory
MIT License
jipp-core/src/main/java/com/hp/jipp/model/PrinterIccProfiles.kt
billmcchesney1
331,642,692
true
{"Kotlin": 717942, "Java": 348565, "Python": 51275, "Shell": 1417}
// Copyright 2018 HP Development Company, L.P. // SPDX-License-Identifier: MIT // // DO NOT MODIFY. Code is auto-generated by genTypes.py. Content taken from registry at // https://www.iana.org/assignments/ipp-registrations/ipp-registrations.xml, updated on 2020-06-10 @file:Suppress("MaxLineLength", "WildcardImport") package com.hp.jipp.model import com.hp.jipp.encoding.* // ktlint-disable no-wildcard-imports /** * Data object corresponding to a "printer-icc-profiles" collection as defined in: * [PWG5100.13](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobprinterext3v10-20120727-5100.13.pdf). */ @Suppress("RedundantCompanionReference", "unused") data class PrinterIccProfiles constructor( var profileName: String? = null, var profileUrl: java.net.URI? = null ) : AttributeCollection { /** Construct an empty [PrinterIccProfiles]. */ constructor() : this(null, null) /** Produce an attribute list from members. */ override val attributes: List<Attribute<*>> get() = listOfNotNull( profileName?.let { PrinterIccProfiles.profileName.of(it) }, profileUrl?.let { PrinterIccProfiles.profileUrl.of(it) } ) /** Defines types for each member of [PrinterIccProfiles]. */ companion object : AttributeCollection.Converter<PrinterIccProfiles> { override fun convert(attributes: List<Attribute<*>>): PrinterIccProfiles = PrinterIccProfiles( extractOne(attributes, profileName)?.value, extractOne(attributes, profileUrl) ) override val cls = PrinterIccProfiles::class.java @Deprecated("Remove this symbol") @JvmField val Types = this @JvmField val profileName = NameType("profile-name") @JvmField val profileUrl = UriType("profile-url") } override fun toString() = "PrinterIccProfiles(${attributes.joinToString()})" }
21
Kotlin
0
0
720731fefaf95a6aceceb20ec8034873fb2736a7
1,904
jipp
MIT License
src/main/kotlin/no/torvundconsulting/sms/model/Sms.kt
frodeto
701,642,562
false
{"Kotlin": 20995}
package no.torvundconsulting.sms.model import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId @Suppress("unused", "PropertyName", "MemberVisibilityCanBePrivate") class Sms( val date: LocalDateTime? = null, val protocol: String? = null, val address: String? = null, val type: String? = null, val subject: String? = null, val body: String? = null, val sc_toa: String? = null, val service_center: String? = null, val readable_date: String? = null, val contact_name: String? = null ): Comparable<Sms> { override fun compareTo(other: Sms): Int = when { this.contact_name != other.contact_name -> compareValues(this.contact_name, other.contact_name) this.date != other.date -> compareValues(this.date, other.date) else -> 0 } companion object { fun of(smses: List<no.torvundconsulting.sms.model.simpleframework.Sms>) = smses.map { of(it) } fun of(sms: no.torvundconsulting.sms.model.simpleframework.Sms): Sms { return Sms( getDate(sms), sms.protocol, sms.address, sms.type, sms.subject, sms.body, sms.sc_toa, sms.service_center, sms.readable_date, sms.contact_name ?: sms.name ) } private fun getDate(sms: no.torvundconsulting.sms.model.simpleframework.Sms): LocalDateTime? { return sms.date?.let { LocalDateTime.ofInstant( Instant.ofEpochMilli(it.toLong()), ZoneId.systemDefault() ) } } } override fun toString(): String { return "Sms(date=$date, address=$address, body=$body, contact_name=$contact_name)" } fun toCSV(): String { return "$contact_name;$body;$date;$address" } }
0
Kotlin
0
0
3d57d0028daf26cfb86db89ddd6ca6407c98dba4
1,898
sms-backup-processor
MIT License
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/filled/SquareOnSquare.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868}
/* * Copyright (c) 2023-2024. Compose Cupertino project and open source 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. * */ package io.github.alexzhirkevich.cupertino.icons.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons public val CupertinoIcons.Filled.SquareOnSquare: ImageVector get() { if (_squareOnSquare != null) { return _squareOnSquare!! } _squareOnSquare = Builder(name = "SquareOnSquare", defaultWidth = 24.7969.dp, defaultHeight = 24.5742.dp, viewportWidth = 24.7969f, viewportHeight = 24.5742f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 15.5156f) curveTo(0.0f, 17.9297f, 1.2188f, 19.1484f, 3.6797f, 19.1484f) lineTo(4.0781f, 19.1484f) lineTo(4.0781f, 9.082f) curveTo(4.0781f, 5.7656f, 6.0234f, 3.8555f, 9.3633f, 3.8555f) lineTo(19.1133f, 3.8555f) lineTo(19.1133f, 3.6563f) curveTo(19.1133f, 1.2422f, 17.8828f, 0.0234f, 15.4453f, 0.0234f) lineTo(3.6797f, 0.0234f) curveTo(1.2188f, 0.0234f, 0.0f, 1.2422f, 0.0f, 3.6563f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.3633f, 24.5742f) lineTo(21.1289f, 24.5742f) curveTo(23.5664f, 24.5742f, 24.7969f, 23.3555f, 24.7969f, 20.9414f) lineTo(24.7969f, 9.082f) curveTo(24.7969f, 6.668f, 23.5664f, 5.4492f, 21.1289f, 5.4492f) lineTo(9.3633f, 5.4492f) curveTo(6.9023f, 5.4492f, 5.6836f, 6.6563f, 5.6836f, 9.082f) lineTo(5.6836f, 20.9414f) curveTo(5.6836f, 23.3555f, 6.9023f, 24.5742f, 9.3633f, 24.5742f) close() } } .build() return _squareOnSquare!! } private var _squareOnSquare: ImageVector? = null
18
Kotlin
31
848
54bfbb58f6b36248c5947de343567903298ee308
3,494
compose-cupertino
Apache License 2.0
src/main/kotlin/me/aberrantfox/judgebot/extensions/UserExtensions.kt
the-programmers-hangout
251,074,065
false
null
package me.aberrantfox.judgebot.extensions import me.jakejmattson.discordkt.api.extensions.jda.fullName import net.dv8tion.jda.api.entities.User fun User.verboseDescriptor() = "**${this.asMention} :: ${this.fullName()} :: ID :: ${this.id}**"
0
Kotlin
0
1
3d70f5d4cb3dbf17bfcfad7bb9db21785a6ab343
243
JudgeBot-old
MIT License
annotation-processor/test-cases/1/output-expected/externalType/KT30280PrimitiveJsonCodec.kt
fluidsonic
105,949,984
false
null
package externalType import codecProvider.CustomCodingContext import codecProvider.KT30280Primitive import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeValueOrNull import kotlin.Unit internal object KT30280PrimitiveJsonCodec : AbstractJsonCodec<KT30280Primitive, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<KT30280Primitive>): KT30280Primitive = KT30280Primitive(value = readDouble()) public override fun JsonEncoder<CustomCodingContext>.encode(value: KT30280Primitive): Unit { writeDouble(value.value) } }
9
Kotlin
4
26
2c43bd1929fc1f1daa73eee67c1cd0b436f95c98
1,197
fluid-json
Apache License 2.0
onboarding/src/main/java/com/proxer/easydo/onboarding/ui/screen/Onboarding.kt
binkos
405,064,940
false
{"Kotlin": 41409}
package com.proxer.easydo.onboarding.ui.screen import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.runtime.remember import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.PagerState import com.google.accompanist.pager.rememberPagerState import com.proxer.easydo.onboarding.R import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalPagerApi::class) @Composable fun Onboarding(onOnboardingFinished: () -> Unit) { val titles = listOf( stringResource(R.string.create_simple_tasks), stringResource(R.string.plan_your_day), stringResource(R.string.plan_your_every_day_activity), stringResource(R.string.add_notifications), stringResource(R.string.see_progress) ) val coroutineScope = rememberCoroutineScope() Column(modifier = Modifier.fillMaxSize()) { val pagerState = rememberPagerState( pageCount = titles.size, initialPage = 0, initialOffscreenLimit = 2 ) Text( text = stringResource(R.string.skip), modifier = Modifier .padding(top = 16.dp, end = 16.dp) .clickable { onOnboardingFinished() } .align(Alignment.End) ) OnboardingPager(Modifier.weight(1f), pagerState, titles) Spacer(modifier = Modifier.height(8.dp)) NextCircleButton( modifier = Modifier .align(Alignment.CenterHorizontally) .padding(vertical = 12.dp), pagerState ) { if (pagerState.pageCount == (pagerState.currentPage + 1)) { onOnboardingFinished() } else { coroutineScope.launch { pagerState.animateScrollToPage(pagerState.currentPage + 1) } } } } } @OptIn(ExperimentalPagerApi::class) @Composable private fun OnboardingPager( modifier: Modifier = Modifier, pagerState: PagerState, titles: List<String> ) { HorizontalPager( modifier = modifier.fillMaxWidth(), state = pagerState, verticalAlignment = Alignment.CenterVertically, horizontalAlignment = Alignment.CenterHorizontally, itemSpacing = 4.dp ) { Text( modifier = Modifier.fillMaxWidth(), text = titles[it], textAlign = TextAlign.Center, color = MaterialTheme.colors.onSurface ) } } @OptIn(ExperimentalPagerApi::class) @Composable private fun NextCircleButton( modifier: Modifier = Modifier, pagerState: PagerState, clickListener: () -> Unit ) { val oneSegmentPart = remember { 360f / pagerState.pageCount } val finalCurrentPage = pagerState.currentPage + 1 val multiply = oneSegmentPart * pagerState.currentPageOffset val angelState = animateFloatAsState(targetValue = oneSegmentPart * finalCurrentPage + multiply) Box(modifier = modifier) { Box( modifier = Modifier .padding(top = 8.dp, start = 8.dp) .size(48.dp) .clip(CircleShape) .clickable { clickListener() } .background(Color.Green), contentAlignment = Alignment.Center ) { Icon( modifier = Modifier .padding(start = 4.dp) .size(24.dp), contentDescription = null, tint = MaterialTheme.colors.onSurface, painter = painterResource(id = R.drawable.ic_right_arrow) ) } Canvas(modifier = Modifier.size(64.dp)) { drawCircle( SolidColor(Color(0xFF2F4951)), style = Stroke(8f) ) drawArc( brush = SolidColor(Color.Green), startAngle = -90f, sweepAngle = angelState.value, useCenter = false, style = Stroke(8f) ) } } }
0
Kotlin
0
0
2508089e15254123f470cd23a98c91b3509a10bc
4,915
easy-do
Apache License 2.0
src/main/kotlin/me/shedaniel/architect/plugin/transformers/GenerateFakeFabricModJson.kt
Paspartout
338,587,068
true
{"Kotlin": 55605, "Java": 3853}
package me.shedaniel.architect.plugin.transformers import me.shedaniel.architect.plugin.Transformer import org.gradle.api.Project import org.zeroturnaround.zip.ByteSource import org.zeroturnaround.zip.ZipUtil import java.nio.file.Files import java.nio.file.Path import java.util.* object GenerateFakeFabricModJson : Transformer { override fun invoke(project: Project, input: Path, output: Path) { Files.copy(input, output) val fakeModId = "generated_" + UUID.randomUUID().toString().filterNot { it == '-' }.take(7) ZipUtil.addOrReplaceEntries( output.toFile(), arrayOf( ByteSource( "fabric.mod.json", """{ "schemaVersion": 1, "id": "$fakeModId", "name": "Generated Mod (Please Ignore)", "version": "1.0.0", "custom": { "fabric-loom:generated": true } }""".toByteArray() ) ) ) } }
0
null
0
0
21d2a47623ea3670eed68c055172125c6d9af8df
913
architectury-plugin
MIT License
feature/profile/src/main/kotlin/team/duckie/app/android/feature/profile/screen/edit/ProfileEditScreen.kt
duckie-team
503,869,663
false
null
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ @file:OptIn(ExperimentalComposeUiApi::class) package team.duckie.app.android.feature.profile.screen.edit import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.launch import team.duckie.app.android.common.compose.ui.PhotoPicker import team.duckie.app.android.feature.profile.R import team.duckie.app.android.feature.profile.component.EditTopAppBar import team.duckie.app.android.feature.profile.component.GrayBorderButton import team.duckie.app.android.feature.profile.viewmodel.ProfileEditViewModel import team.duckie.app.android.feature.profile.viewmodel.state.NicknameState import team.duckie.app.android.common.compose.ui.Spacer import team.duckie.app.android.common.compose.ui.skeleton import team.duckie.quackquack.ui.color.QuackColor import team.duckie.quackquack.ui.component.QuackBody1 import team.duckie.quackquack.ui.component.QuackErrorableTextField import team.duckie.quackquack.ui.component.QuackImage import team.duckie.quackquack.ui.component.QuackReviewTextArea import team.duckie.quackquack.ui.shape.SquircleShape import team.duckie.quackquack.ui.util.DpSize private const val MaxNicknameLength = 12 private const val MaxIntroductionLength = 60 @Composable internal fun ProfileEditScreen( vm: ProfileEditViewModel, ) { val state by vm.container.stateFlow.collectAsStateWithLifecycle() val galleryState = remember(state) { state.galleryState } val keyboardController = LocalSoftwareKeyboardController.current val coroutineScope = rememberCoroutineScope() val focusManager = LocalFocusManager.current val takePhotoFromCameraLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicturePreview(), ) { takenPhoto -> vm.changePhotoPickerVisible(false) if (takenPhoto != null) { vm.changeProfile(takenPhoto) } } BackHandler(galleryState.visible) { vm.changePhotoPickerVisible(false) } if (galleryState.visible) { SideEffect { keyboardController?.hide() focusManager.clearFocus() } PhotoPicker( modifier = Modifier .fillMaxSize() .background(color = QuackColor.White.composeColor) .navigationBarsPadding() .systemBarsPadding(), imageUris = galleryState.images, imageSelections = galleryState.imagesSelections, onCameraClick = { coroutineScope.launch { takePhotoFromCameraLauncher.launch() } }, onImageClick = { index, _ -> vm.clickGalleryImage(index) }, onCloseClick = { vm.changePhotoPickerVisible(false) }, onAddClick = { vm.addProfileFromGallery() }, ) } Column( modifier = Modifier .fillMaxSize() .background(QuackColor.White.composeColor) .navigationBarsPadding() .systemBarsPadding(), ) { EditTopAppBar( title = stringResource(id = R.string.edit_profile), onBackPressed = vm::clickBackPress, onClickEditComplete = vm::clickEditComplete, ) Column( modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp), ) { Spacer(space = 40.dp) ProfileEditSection( profile = state.profile, onClickEditProfile = vm::clickEditProfile, ) Spacer(space = 40.dp) QuackBody1( text = stringResource(R.string.nickname), color = QuackColor.Gray1, ) QuackErrorableTextField( modifier = Modifier.skeleton(state.isLoading), text = state.nickname, onTextChanged = { text -> if (text.length <= MaxNicknameLength) { vm.changeNickName(text) } }, placeholderText = stringResource(R.string.profile_nickname_placeholder), isError = state.nicknameState.isInValid(), maxLength = MaxNicknameLength, errorText = when (state.nicknameState) { NicknameState.NicknameRuleError -> stringResource(R.string.profile_nickname_rule_error) NicknameState.NicknameDuplicateError -> stringResource(R.string.profile_nickname_duplicate_error) else -> "" }, keyboardActions = KeyboardActions { keyboardController?.hide() }, ) Spacer(space = 36.dp) QuackBody1( text = stringResource(R.string.introduce), color = QuackColor.Gray1, ) Spacer(space = 8.dp) QuackReviewTextArea( // TODO(evergreenTree97) 배포 후 글자 수 제한있는 텍스트필드 구현 modifier = Modifier.skeleton(state.isLoading), text = state.introduce, onTextChanged = { if (it.length <= MaxIntroductionLength) { vm.inputIntroduce(it) } }, focused = state.introduceFocused, placeholderText = stringResource(id = R.string.please_input_introduce), ) } } } @Composable internal fun ProfileEditSection( profile: Any?, onClickEditProfile: () -> Unit, ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp), ) { QuackImage( src = profile, shape = SquircleShape, size = DpSize(80.dp), ) GrayBorderButton( text = stringResource(id = R.string.edit_profile_picture), onClick = onClickEditProfile, ) } }
19
Kotlin
2
34
4fa7edae1fd24811ec278b0e24236c247f98dff0
7,510
duckie-android
MIT License
src/main/kotlin/org/jetbrains/research/testspark/bundles/plugin/PluginDefaultsBundle.kt
JetBrains-Research
563,889,235
false
{"Kotlin": 733171, "Java": 5347, "Shell": 1563}
package org.jetbrains.research.testspark.bundles.plugin import com.intellij.DynamicBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.PropertyKey /** * Loads the `resources` directory. */ object PluginDefaultsBundle : DynamicBundle(PluginBundlePaths.defaults) { /** * Gets the requested default value. */ @Nls fun get(@PropertyKey(resourceBundle = PluginBundlePaths.defaults) key: String): String = getMessage(key) }
66
Kotlin
19
51
e1553b15f05f8e125f17aba1e062e4f3ad2c00e3
470
TestSpark
MIT License
generator/graphql-kotlin-federation/src/test/kotlin/com/expediagroup/graphql/generator/federation/directives/contact/ContactDirectiveTest.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2024 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.expediagroup.graphql.generator.federation.directives.contact import com.expediagroup.graphql.generator.TopLevelObject import com.expediagroup.graphql.generator.extensions.print import com.expediagroup.graphql.generator.federation.FederatedSchemaGeneratorConfig import com.expediagroup.graphql.generator.federation.FederatedSchemaGeneratorHooks import com.expediagroup.graphql.generator.federation.directives.ContactDirective import com.expediagroup.graphql.generator.federation.toFederatedSchema import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class ContactDirectiveTest { @Test fun `verify we can import federation spec using custom @link`() { val expectedSchema = """ schema @contact(description : "Send emails to <EMAIL>", name : "<NAME>", url : "https://myteam.slack.com/room") @link(url : "https://specs.apollo.dev/federation/v2.6"){ query: Query } "Provides contact information of the owner responsible for this subgraph schema." directive @contact(description: String, name: String!, url: String) on SCHEMA "Marks the field, argument, input field or enum value as deprecated" directive @deprecated( "The reason for the deprecation" reason: String = "No longer supported" ) on FIELD_DEFINITION | ARGUMENT_DEFINITION | ENUM_VALUE | INPUT_FIELD_DEFINITION "Directs the executor to include this field or fragment only when the `if` argument is true" directive @include( "Included when true." if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT "Links definitions within the document to external schemas." directive @link(as: String, import: [link__Import], url: String!) repeatable on SCHEMA "Indicates an Input Object is a OneOf Input Object." directive @oneOf on INPUT_OBJECT "Directs the executor to skip this field or fragment when the `if` argument is true." directive @skip( "Skipped when true." if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT "Exposes a URL that specifies the behaviour of this scalar." directive @specifiedBy( "The URL that specifies the behaviour of this scalar." url: String! ) on SCALAR type Query { _service: _Service! foo: String! } type _Service { sdl: String! } scalar link__Import """.trimIndent() val config = FederatedSchemaGeneratorConfig( supportedPackages = listOf("com.expediagroup.graphql.generator.federation.directives.contact"), hooks = FederatedSchemaGeneratorHooks(emptyList()) ) val schema = toFederatedSchema( queries = listOf(TopLevelObject(FooQuery())), schemaObject = TopLevelObject(CustomSchema()), config = config ) assertEquals(expectedSchema, schema.print().trim()) } @ContactDirective(name = "<NAME>", url = "https://myteam.slack.com/room", description = "Send emails to <EMAIL>") class CustomSchema class FooQuery { fun foo(): String = TODO() } }
68
null
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
4,051
graphql-kotlin
Apache License 2.0
packages/test-sync/src/commonMain/kotlin/io/realm/kotlin/test/mongodb/util/KtorTestMethods.kt
realm
235,075,339
false
{"Kotlin": 4524507, "C++": 124405, "SWIG": 25944, "Shell": 23822, "C": 5126, "CMake": 2765, "Ruby": 1586, "Java": 1470, "Dockerfile": 1090}
/* * Copyright 2022 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.kotlin.test.mongodb.util import io.ktor.http.HttpMethod import kotlin.native.concurrent.SharedImmutable // Sits here because [SharedImmutable] annotation is only available in common. @SharedImmutable val TEST_METHODS = listOf( HttpMethod.Get, HttpMethod.Post, HttpMethod.Patch, HttpMethod.Put, HttpMethod.Delete, )
232
Kotlin
52
868
97f288c4d00e6c8f0fb28e1a595bdc5c08ecdaec
944
realm-kotlin
Apache License 2.0
app/src/main/java/com/jodi/cophat/ui/base/view/ThermometerListener.kt
cophat
241,760,374
false
null
package com.jodi.cophat.ui.base.view import com.jodi.cophat.data.local.entity.AnswerType interface ThermometerListener { fun onAnswerChanged(answerType: AnswerType) }
4
Kotlin
0
0
2272aca57494ef39a09d948549eb9fead5c3f68c
173
cophat
Apache License 2.0
app/src/main/java/com/github/jing332/tts_server_android/help/plugin/ui/Item.kt
jing332
536,800,727
false
null
package com.github.jing332.tts_server_android.help.plugin.ui data class Item(val name: String, val value: Any)
4
Kotlin
60
581
ab8d7140295ec359a4d0aea94f403a271f47c037
111
tts-server-android
MIT License
LearnKotlin/app/src/main/java/sg/edu/nus/learnkotlin/ActivityBreak.kt
aficat
207,585,289
false
null
package sg.edu.nus.learnkotlin import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.v7.app.AppCompatActivity import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.widget.Button import android.widget.TextView class ActivityBreak : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_break) val breakQuiz = findViewById<Button>(R.id.break_quiz) breakQuiz.setOnClickListener { val myIntent = Intent(this, ActivityBreakQuiz::class.java) startActivity(myIntent) } val description1 = findViewById<TextView>(R.id.description1) val spannable1 = SpannableStringBuilder( "The break statement ends the execution of the loop.\n" ) // bold red break spannable1.setSpan(ForegroundColorSpan(Color.RED), 4, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) spannable1.setSpan(StyleSpan(Typeface.BOLD), 4, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) description1.text = spannable1 val example1 = findViewById<TextView>(R.id.code_example1) val code1 = SpannableStringBuilder( "var x = 5\n" + "do {\n" + " println(x);\n" + " x--;\n" + " if (x==3)\n" + " break;\n" + "} while (x > 0);\n" ) // color red 5 code1.setSpan(ForegroundColorSpan(Color.RED), 8, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.RED), 48, 49, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.RED), 74, 75, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) // color dark blue and bold do, if and while, break code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 10, 12, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 10, 12, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 30, 32, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 30, 32, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 40, 43, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 40, 43, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 63, 68, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 63, 68, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.BLACK), 54, 59, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 54, 59, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) example1.text = code1 val example2 = findViewById<TextView>(R.id.code_example2) val code2 = SpannableStringBuilder( "Output:\n" + "5\n" + "4\n\n" + "And then exits the loop.\n" ) example2.text = code2 val description2 = findViewById<TextView>(R.id.description2) val spannable2 = SpannableStringBuilder("In case you want to remain in the loop, but skip an iteration, use the continue statement:\n") // bold red spannable2.setSpan(ForegroundColorSpan(Color.RED), 71, 79, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) spannable2.setSpan(StyleSpan(Typeface.BOLD), 71, 79, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) description2.text = spannable2 val example3 = findViewById<TextView>(R.id.code_example3) val code3 = SpannableStringBuilder( "var x = 0;\n" + "while (x < 5) {\n" + " x++;\n" + " if (x==3)\n" + " continue;\n" + " println(x);\n" + "}\n" ) // color red code1.setSpan(ForegroundColorSpan(Color.RED), 8, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.RED), 22, 23, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.RED), 37, 38, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) // color dark blue and bold code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 11, 16, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 11, 16, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 30, 32, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 30, 32, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(ForegroundColorSpan(Color.rgb(40, 90, 165)), 39, 47, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) code1.setSpan(StyleSpan(Typeface.BOLD), 39, 47, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) example3.text = code3 val example4 = findViewById<TextView>(R.id.code_example4) val code4 = SpannableStringBuilder( "Output:\n" + "1\n" + "2\n" + "4\n" + "5\n\n" + "The value 3 is skipped.\n" ) example4.text = code4 val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavView_Bar) //BottomNavigationViewHelper.disableShiftMode(bottomNavigationView) val menu = bottomNavigationView.menu val menuItem = menu.getItem(0) menuItem.isChecked = true bottomNavigationView.setOnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.ic_home -> { val intent1 = Intent(this@ActivityBreak, ActivityHome::class.java) startActivity(intent1) } R.id.ic_video -> { val intent2 = Intent(this@ActivityBreak, ActivityVideosPage::class.java) startActivity(intent2) } R.id.ic_onlineCode -> { val intent3 = Intent(this@ActivityBreak, ActivityNotes::class.java) startActivity(intent3) } R.id.ic_game -> { val intent4 = Intent(this@ActivityBreak, ActivityGame::class.java) startActivity(intent4) } R.id.ic_disclaimer-> { val intent5 = Intent(this@ActivityBreak, ActivityDisclaimer::class.java) startActivity(intent5) } } false } } }
0
Kotlin
0
0
ccc06fecb092de4e94fbed09d8438db1524d905f
6,983
LearnKotlin
MIT License
example/src/commonMain/kotlin/main.kt
typfel
772,761,428
false
{"Rust": 12808, "Kotlin": 1317}
import crossterm.ClearType import crossterm.Terminal import crossterm.Event import crossterm.KeyCode fun main(args: Array<String>) { val terminal = Terminal() terminal.execute( listOf( crossterm.Command.EnableMouseCapture, crossterm.Command.EnterAlternateScreen ) ) terminal.enableRawMode() while(true) { val event = terminal.read() terminal.execute( listOf( crossterm.Command.Clear(ClearType.CURRENT_LINE), crossterm.Command.MoveTo(0u, 0u) ) ) print(event) if (event is Event.Key && event.event.code == KeyCode.Char("q")) { terminal.disableRawMode() terminal.execute( listOf( crossterm.Command.DisableMouseCapture, crossterm.Command.LeaveAlternateScreen ) ) return } } }
0
Rust
0
0
9955afc5d5e7f5e3f5a79ba87a924b8a04485218
964
crossterm-kmp
MIT License
app/src/main/java/org/sorz/lab/tinykeepass/autofill/TinyAutofillService.kt
ahxxm
307,118,518
true
{"Java Properties": 2, "Gradle": 3, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 45, "Proguard": 1, "Java": 16, "Kotlin": 11}
package org.sorz.lab.tinykeepass.autofill import android.os.Build import android.os.CancellationSignal import android.service.autofill.AutofillService import android.service.autofill.FillCallback import android.service.autofill.FillRequest import android.service.autofill.FillResponse import android.service.autofill.SaveCallback import android.service.autofill.SaveRequest import androidx.annotation.RequiresApi import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import org.sorz.lab.tinykeepass.R import org.sorz.lab.tinykeepass.keepass.hasDatabaseConfigured import kotlin.streams.toList @RequiresApi(api = Build.VERSION_CODES.O) class TinyAutofillService : AutofillService(), AnkoLogger { override fun onFillRequest(request: FillRequest, cancellationSignal: CancellationSignal, callback: FillCallback) { cancellationSignal.setOnCancelListener { debug("autofill canceled.") } if (!hasDatabaseConfigured) { callback.onSuccess(null) return } val structure = request.fillContexts[request.fillContexts.size - 1].structure val parseResult = StructureParser(structure).parse() if (parseResult.password.isEmpty()) { debug("no password field found") callback.onSuccess(null) return } val responseBuilder = FillResponse.Builder() val presentation = AutofillUtils.getRemoteViews(this, getString(R.string.autofill_unlock_db), android.R.drawable.ic_lock_lock) val sender = AuthActivity.getAuthIntentSenderForResponse(this) val autofillIds = parseResult.allAutofillIds().toList().toTypedArray() responseBuilder.setAuthentication(autofillIds, sender, presentation) callback.onSuccess(responseBuilder.build()) } override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) { callback.onFailure(getString(R.string.autofill_not_support_save)) } override fun onConnected() = debug ("onConnected") override fun onDisconnected() = debug("onDisconnected") }
0
null
0
0
da4ebc4959721984fc4f8514a2e34e8d11da5f9d
2,168
TinyKeePass
Apache License 2.0
src/main/kotlin/ru/qiwi/devops/mission/control/service/ingress/IngressEventsService.kt
qiwi
329,911,226
false
null
package ru.qiwi.devops.mission.control.service.ingress import reactor.core.publisher.Flux import ru.qiwi.devops.mission.control.model.event.Event import ru.qiwi.devops.mission.control.model.ingress.IngressInfo interface IngressEventsService { fun getIngressEvents(): Flux<Event<IngressInfo>> }
1
Kotlin
1
1
a5b4a1dc716841bbf0439fa309e3a2b85bbeb1d3
299
k8s-mission-control
MIT License
app/src/main/java/sk/kasper/space/utils/ContextExtensions.kt
ValterKasper
253,570,488
false
null
package sk.kasper.space.utils import android.content.Context import java.io.InputStream fun Context.readFileFromAssets(fileName: String): String { val inputStream: InputStream = assets.open(fileName) val size: Int = inputStream.available() val buffer = ByteArray(size) inputStream.read(buffer) inputStream.close() return String(buffer, Charsets.UTF_8) }
1
Kotlin
14
131
2fadfa5596b255508d0bf8ece61e00a6c0f0aef2
379
space-app
Apache License 2.0