path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/mati/mimovies/features/movies/presentation/detailScreen/MovieDetailScreenShimmer.kt
mr-mati
697,450,396
false
{"Kotlin": 242691}
package com.mati.mimovies.features.movies.presentation.detailScreen import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Star import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalView import androidx.compose.ui.unit.dp import androidx.core.view.WindowInsetsCompat import com.mati.mimovies.utils.Title import com.valentinilk.shimmer.shimmer @SuppressLint("UnrememberedMutableState") @Composable fun MovieDetailScreenShimmer(isVisible: Boolean) { val view = LocalView.current val insets = WindowInsetsCompat.toWindowInsetsCompat(view.rootWindowInsets) val statusBarHeight = with(LocalDensity.current) { insets.getInsets(WindowInsetsCompat.Type.statusBars()).top.toDp() } Column( modifier = Modifier .background(MaterialTheme.colorScheme.primary) .padding(bottom = 16.dp, top = statusBarHeight) .fillMaxSize(), ) { HeaderShimmer() ToolBox( onClickPlay = { }, onClickDownload = { }, onAddToFavorite = { }, addedToList = mutableStateOf(false) ) Row( modifier = Modifier .padding(horizontal = 8.dp) .padding(top = 16.dp, bottom = 16.dp) ) { Row( modifier = Modifier .padding(bottom = 4.dp, top = 8.dp, end = 8.dp) ) { Card( modifier = Modifier .width(100.dp) .shimmer() .height(30.dp), elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), colors = CardDefaults.cardColors( containerColor = Color.Gray, ), shape = RoundedCornerShape(24.dp) ) {} Spacer(modifier = Modifier.width(16.dp)) Card( modifier = Modifier .width(100.dp) .shimmer() .height(30.dp), elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), colors = CardDefaults.cardColors( containerColor = Color.Gray, ), shape = RoundedCornerShape(24.dp) ) {} } } Spacer(modifier = Modifier.height(16.dp)) Title("Trailer") CircularProgressIndicator( modifier = Modifier .width(64.dp) .align(Alignment.CenterHorizontally), color = MaterialTheme.colorScheme.onPrimary, trackColor = MaterialTheme.colorScheme.surface, ) } } @Composable fun HeaderShimmer(modifier: Modifier = Modifier) { Box( modifier = Modifier .fillMaxWidth() .padding(top = 16.dp) .height(350.dp), ) { Column( modifier = Modifier.align(Alignment.Center), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Card( modifier = Modifier .width(200.dp) .shimmer() .height(230.dp), elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.tertiary, ), shape = RoundedCornerShape(8.dp) ) { } Card( modifier = Modifier .width(150.dp) .shimmer() .padding(top = 16.dp) .height(30.dp), elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), colors = CardDefaults.cardColors( containerColor = Color.Gray, ), shape = RoundedCornerShape(24.dp) ) {} Row( modifier = Modifier.padding(8.dp) ) { Icon( Icons.Default.Star, tint = Color.Yellow, contentDescription = null ) Card( modifier = Modifier .width(70.dp) .shimmer() .height(30.dp), elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), colors = CardDefaults.cardColors( containerColor = Color.Gray, ), shape = RoundedCornerShape(24.dp) ) {} } } IconButton( modifier = Modifier .padding(16.dp) .background(Color.Transparent) .border( width = 1.dp, color = MaterialTheme.colorScheme.secondary, shape = RoundedCornerShape(32.dp) ), onClick = { }, ) { Icon( Icons.Default.ArrowBack, null, tint = MaterialTheme.colorScheme.tertiary, modifier = Modifier .size(32.dp) .background(Color.Transparent) ) } } }
0
Kotlin
0
3
d2ceadfdc125291310f0207679c9588aadb2cfd2
7,017
MiMovie
MIT License
src/main/kotlin/org/teamvoided/dusk_debris/data/gen/providers/EntityLootTableProvider.kt
TeamVoided
814,767,803
false
{"Kotlin": 153037, "Java": 3724}
package org.teamvoided.dusk_debris.data.gen.providers import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.SimpleFabricLootTableProvider import net.minecraft.item.Items import net.minecraft.loot.LootPool import net.minecraft.loot.LootTable import net.minecraft.loot.condition.LocationCheckLootCondition import net.minecraft.loot.context.LootContextTypes import net.minecraft.loot.entry.EmptyEntry import net.minecraft.loot.entry.ItemEntry import net.minecraft.loot.entry.LootTableEntry import net.minecraft.predicate.entity.LocationPredicate import net.minecraft.registry.* import net.minecraft.registry.tag.BiomeTags import net.minecraft.world.biome.Biome import net.minecraft.world.biome.Biomes import org.teamvoided.dusk_autumn.util.Utils import org.teamvoided.dusk_debris.data.DuskLootTables import java.util.* import java.util.concurrent.CompletableFuture import java.util.function.BiConsumer class EntityLootTableProvider(o: FabricDataOutput, val r: CompletableFuture<HolderLookup.Provider>) : SimpleFabricLootTableProvider(o, r, LootContextTypes.CHEST) { // val dropsItSelf = listOf() override fun generate(gen: BiConsumer<RegistryKey<LootTable>, LootTable.Builder>) { val biomes = r.get().getLookupOrThrow(RegistryKeys.BIOME) gen.accept( DuskLootTables.ENDERMAN_HOLDS, LootTable.builder().pool( LootPool.builder().rolls(Utils.constantNum(1)) .with(EmptyEntry.builder().weight(10)) .with(LootTableEntry.method_428(DuskLootTables.ENDERMAN_OVERWORLD_GENERIC).weight(10)) .with( LootTableEntry.method_428(DuskLootTables.ENDERMAN_NETHER_GENERIC) .conditionally( LocationCheckLootCondition.builder( LocationPredicate.Builder.create().method_9024( biomes.getTagOrThrow(BiomeTags.NETHER) ) ) ).weight(10) ) // .with( // LootTableEntry.method_428(DuskLootTables.ENDERMAN_NETHER_GENERIC) // .conditionally( // LocationCheckLootCondition.builder( // LocationPredicate.Builder.create().method_9024( // HolderSet.createDirect( // biomes.getHolderOrThrow(Biomes.JUNGLE), // biomes.getHolderOrThrow(Biomes.SPARSE_JUNGLE), // biomes.getHolderOrThrow(Biomes.BAMBOO_JUNGLE) // ) // ) // ) // ).weight(10) // ) .with(LootTableEntry.method_428(DuskLootTables.ENDERMAN_OVERWORLD_DESERT).weight(10)) ) ) gen.accept( DuskLootTables.ENDERMAN_OVERWORLD_GENERIC, LootTable.builder().pool( LootPool.builder().rolls(Utils.constantNum(1)) .with(ItemEntry.builder(Items.GRASS_BLOCK).weight(10)) .with(ItemEntry.builder(Items.DIRT).weight(3)) .with(ItemEntry.builder(Items.POPPY).weight(5)) .with(ItemEntry.builder(Items.DANDELION).weight(5)) .with(ItemEntry.builder(Items.STONE).weight(3)) .with(ItemEntry.builder(Items.GRAVEL).weight(3)) .with(ItemEntry.builder(Items.DEEPSLATE)) .with(ItemEntry.builder(Items.RED_MUSHROOM).weight(3)) .with(ItemEntry.builder(Items.BROWN_MUSHROOM).weight(3)) ) ) gen.accept( DuskLootTables.ENDERMAN_NETHER_GENERIC, LootTable.builder().pool( LootPool.builder().rolls(Utils.constantNum(1)) .with(ItemEntry.builder(Items.NETHERRACK).weight(10)) .with(ItemEntry.builder(Items.CRIMSON_NYLIUM).weight(3)) .with(ItemEntry.builder(Items.WARPED_NYLIUM).weight(7)) .with(ItemEntry.builder(Items.BLACKSTONE).weight(7)) .with(ItemEntry.builder(Items.SOUL_SAND).weight(3)) .with(ItemEntry.builder(Items.SOUL_SOIL).weight(3)) .with(ItemEntry.builder(Items.BASALT).weight(3)) ) ) gen.accept( DuskLootTables.ENDERMAN_OVERWORLD_DESERT, LootTable.builder().pool( LootPool.builder().rolls(Utils.constantNum(1)) .with(ItemEntry.builder(Items.SAND).weight(25)) .with(ItemEntry.builder(Items.SANDSTONE).weight(25)) .with(ItemEntry.builder(Items.RED_SAND).weight(10)) .with(ItemEntry.builder(Items.RED_SANDSTONE).weight(10)) .with(ItemEntry.builder(Items.DEAD_BUSH).weight(15)) .with(ItemEntry.builder(Items.CACTUS).weight(7)) ) ) } }
0
Kotlin
0
0
7973b474b08276fc01cb6222ceadf235004c29f3
5,331
Dusk-Debris
MIT License
protoc-gen-kroto-plus/src/test/kotlin/FileFilterTest.kt
marcoferrer
124,468,545
false
null
/* * Copyright 2019 Kroto+ 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 com.github.marcoferrer.krotoplus.utils import com.github.marcoferrer.krotoplus.config.FileFilter import kotlin.test.Test import kotlin.test.assertEquals class FileFilterTest { val testPaths = listOf( "google/protobuf", "test/dummy/a/1", "test/dummy/a/2", "test/dummy/b/1", "test/dummy/b/2", "test/dummy/c/1", "test/dummy/c/2" ) @Test fun `include all paths`(){ val fileFilter = FileFilter.getDefaultInstance() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(7, matches.size) } @Test fun `Include single path`(){ val fileFilter = FileFilter.newBuilder().addIncludePath("test/dummy/a/*").build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(2, matches.size) assertEquals("test/dummy/a/1",matches[0]) assertEquals("test/dummy/a/2",matches[1]) } @Test fun `Include multiple paths`(){ val fileFilter = FileFilter.newBuilder() .addIncludePath("test/dummy/a/*") .addIncludePath("google/*") .build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(3, matches.size) assertEquals("google/protobuf",matches[0]) assertEquals("test/dummy/a/1",matches[1]) assertEquals("test/dummy/a/2",matches[2]) } @Test fun `Exclude single path`(){ val fileFilter = FileFilter.newBuilder() .addExcludePath("google/*") .build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(6, matches.size) assertEquals("test/dummy/a/1",matches[0]) assertEquals("test/dummy/a/2",matches[1]) assertEquals("test/dummy/b/1",matches[2]) assertEquals("test/dummy/b/2",matches[3]) assertEquals("test/dummy/c/1",matches[4]) assertEquals("test/dummy/c/2",matches[5]) } @Test fun `Exclude multiple paths`(){ val fileFilter = FileFilter.newBuilder() .addExcludePath("google/*") .addExcludePath("test/dummy/b/*") .build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(4, matches.size) assertEquals("test/dummy/a/1",matches[0]) assertEquals("test/dummy/a/2",matches[1]) assertEquals("test/dummy/c/1",matches[2]) assertEquals("test/dummy/c/2",matches[3]) } @Test fun `Include and exclude paths`(){ val fileFilter = FileFilter.newBuilder() .addIncludePath("test/dummy/*") .addExcludePath("test/dummy/*/1") .build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(3, matches.size) assertEquals("test/dummy/a/2",matches[0]) assertEquals("test/dummy/b/2",matches[1]) assertEquals("test/dummy/c/2",matches[2]) } @Test fun `Include and exclude multiple paths`(){ val fileFilter = FileFilter.newBuilder() .addIncludePath("google/*") .addIncludePath("test/dummy/*/1") .addExcludePath("test/dummy/a/*") .addExcludePath("test/dummy/c/*") .build() val matches = testPaths.filter { fileFilter.matches(it) } assertEquals(2, matches.size) assertEquals("google/protobuf",matches[0]) assertEquals("test/dummy/b/1",matches[1]) } }
32
null
27
486
2b0b447d47f14da93b536ef238b379eb4cc6075c
4,095
kroto-plus
Apache License 2.0
src/main/kotlin/com/grapefruit/aid/domain/purchase/service/impl/ModifyPurchaseQuantityServiceImpl.kt
Team-GrapeFruit
621,363,100
false
null
package com.grapefruit.aid.domain.purchase.service.impl import com.grapefruit.aid.domain.purchase.exception.PurchaseNotFoundException import com.grapefruit.aid.domain.purchase.presentation.dto.request.ModifyPurchaseQuantityReqDto import com.grapefruit.aid.domain.purchase.repository.PurchaseRepository import com.grapefruit.aid.domain.purchase.service.ModifyPurchaseQuantityService import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional(rollbackFor = [Exception::class]) class ModifyPurchaseQuantityServiceImpl( private val purchaseRepository: PurchaseRepository ): ModifyPurchaseQuantityService { override fun execute(purchaseId: Long, modifyPurchaseQuantityReqDto: ModifyPurchaseQuantityReqDto) { val purchase = purchaseRepository.findByIdOrNull(purchaseId) ?: throw PurchaseNotFoundException() purchaseRepository.save(purchase.update(modifyPurchaseQuantityReqDto)) } }
0
Kotlin
0
0
5c4ea42e5656709e9b596089c852de2485dafde0
1,038
Aid-Backend-User
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageprisonvisitsorchestration/integration/IntegrationTestBase.kt
ministryofjustice
575,484,836
false
null
package uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.BeforeEach import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT import org.springframework.http.HttpHeaders import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.reactive.server.WebTestClient import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.ChangeVisitSlotRequestDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.ReserveVisitSlotDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.VisitDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.VisitSessionDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.VisitorDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.helper.JwtAuthHelper import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration.mock.VisitSchedulerMockServer import java.time.LocalDateTime @SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") abstract class IntegrationTestBase { companion object { val visitSchedulerMockServer = VisitSchedulerMockServer(ObjectMapper().registerModule(JavaTimeModule())) @BeforeAll @JvmStatic fun startMocks() { visitSchedulerMockServer.start() } @AfterAll @JvmStatic fun stopMocks() { visitSchedulerMockServer.stop() } } @Autowired lateinit var webTestClient: WebTestClient lateinit var roleVisitSchedulerHttpHeaders: (HttpHeaders) -> Unit @Autowired protected lateinit var jwtAuthHelper: JwtAuthHelper @BeforeEach internal fun setUp() { roleVisitSchedulerHttpHeaders = setAuthorisation(roles = listOf("ROLE_VISIT_SCHEDULER")) } internal fun setAuthorisation( user: String = "AUTH_ADM", roles: List<String> = listOf(), scopes: List<String> = listOf() ): (HttpHeaders) -> Unit = jwtAuthHelper.setAuthorisation(user, roles, scopes) fun createVisitDto( reference: String = "aa-bb-cc-dd", applicationReference: String = "aaa-bbb-ccc-ddd" ): VisitDto { return VisitDto( applicationReference = applicationReference, reference = reference, prisonerId = "AB12345DS", prisonCode = "MDI", visitRoom = "A1 L3", visitType = "SOCIAL", visitStatus = "BOOKED", visitRestriction = "OPEN", startTimestamp = LocalDateTime.now(), endTimestamp = LocalDateTime.now().plusHours(1), outcomeStatus = null, createdTimestamp = LocalDateTime.now(), modifiedTimestamp = LocalDateTime.now() ) } fun createReserveVisitSlotDto(prisonerId: String): ReserveVisitSlotDto { val visitor = VisitorDto(1, false) return ReserveVisitSlotDto( prisonerId = prisonerId, prisonCode = "MDI", visitRoom = "A1 L3", visitType = "SOCIAL", visitRestriction = "OPEN", startTimestamp = LocalDateTime.now(), endTimestamp = LocalDateTime.now().plusHours(1), visitContact = null, visitors = setOf(visitor), ) } fun createChangeVisitSlotRequestDto(): ChangeVisitSlotRequestDto { val visitor = VisitorDto(1, false) return ChangeVisitSlotRequestDto( visitRestriction = "OPEN", startTimestamp = LocalDateTime.now(), endTimestamp = LocalDateTime.now().plusHours(1), visitContact = null, visitors = setOf(visitor), ) } fun createVisitSessionDto(prisonCode: String, sessionTemplateId: Long): VisitSessionDto { return VisitSessionDto( sessionTemplateId = sessionTemplateId, prisonCode = prisonCode, visitRoomName = "Visit Room", visitType = "Social", closedVisitCapacity = 5, openVisitCapacity = 30, startTimestamp = LocalDateTime.now(), endTimestamp = LocalDateTime.now().plusHours(1) ) } }
0
Kotlin
0
0
bc1d336583d2f699968a20fcad824ab89a3a558d
4,262
hmpps-manage-prison-visits-orchestration
MIT License
app/src/main/java/com/appbusters/robinpc/constitutionofindia/ui/reading/adapter/DummyTagListAdapter.kt
kumar4Vipul
213,992,183
false
{"XML": 69, "Gradle": 3, "Java Properties": 2, "Text": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Ignore List": 1, "Java": 2, "Kotlin": 83}
package com.appbusters.robinpc.constitutionofindia.ui.reading.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.appbusters.robinpc.constitutionofindia.R import com.appbusters.robinpc.constitutionofindia.data.model.DummyTag import com.appbusters.robinpc.constitutionofindia.ui.reading.adapter.holder.DummyTagHolder class DummyTagListAdapter(comparator: DiffUtil.ItemCallback<DummyTag>): ListAdapter<DummyTag, DummyTagHolder>(comparator), DummyTagHolder.OnTagClickListener { private lateinit var tagClickListener: OnTagClickListener override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DummyTagHolder { return DummyTagHolder(LayoutInflater.from(parent.context).inflate(R.layout.row_dummy_tag, parent, false)) } override fun onBindViewHolder(holder: DummyTagHolder, position: Int) { getItem(position)?.let { holder.setTag(it) holder.setTagClickListener(this) } } override fun onTagClicked(tag: DummyTag) { tagClickListener.onTagClicked(tag) } fun setTagClickListener(tagClickListener: OnTagClickListener) { this.tagClickListener = tagClickListener } interface OnTagClickListener { fun onTagClicked(tag: DummyTag) } }
1
null
1
1
82a916316ac6822023392991f1efc74ff2ed571f
1,386
Indian-Constitution-App
Apache License 2.0
app/src/main/kotlin/hr/kbratko/instakt/infrastructure/persistence/module.kt
karlobratko
802,886,736
false
{"Kotlin": 343278, "Makefile": 749}
package hr.kbratko.instakt.infrastructure.persistence import aws.sdk.kotlin.runtime.auth.credentials.EnvironmentCredentialsProvider import aws.sdk.kotlin.services.s3.S3Client import aws.smithy.kotlin.runtime.net.Host import aws.smithy.kotlin.runtime.net.Scheme import aws.smithy.kotlin.runtime.net.url.Url import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import hr.kbratko.instakt.domain.model.Content import hr.kbratko.instakt.domain.toDuration import hr.kbratko.instakt.infrastructure.ktor.getBoolean import hr.kbratko.instakt.infrastructure.ktor.getInt import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedContentMetadataPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedPasswordResetTokenPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedRefreshTokenPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedRegistrationTokenPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedSocialMediaLinkPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.ExposedUserPersistence import hr.kbratko.instakt.infrastructure.persistence.exposed.PasswordResetTokenPersistenceConfig import hr.kbratko.instakt.infrastructure.persistence.exposed.RefreshTokenPersistenceConfig import hr.kbratko.instakt.infrastructure.persistence.exposed.RegistrationTokenPersistenceConfig import hr.kbratko.instakt.infrastructure.persistence.s3.ContentPersistenceConfig import hr.kbratko.instakt.infrastructure.persistence.s3.S3ContentPersistence import hr.kbratko.instakt.infrastructure.serialization.Resources import io.ktor.server.application.Application import java.sql.Connection import org.flywaydb.core.Flyway import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.DatabaseConfig import org.jetbrains.exposed.sql.StdOutSqlLogger import org.koin.dsl.module fun Application.PersistenceModule() = module { val db = environment.config.config("db") val s3 = environment.config.config("s3") val auth = environment.config.config("auth") single(createdAtStart = true) { val secrets: DatabaseCredentialsConfig = Resources.hocon("secrets/db.dev.conf") val dataSource = HikariDataSource( HikariConfig().apply { jdbcUrl = db.property("jdbcUrl").getString() driverClassName = db.property("dataSource.driverClass").getString() secrets.also { username = it.username password = <PASSWORD> } maximumPoolSize = db.property("maximumPoolSize").getInt() } ) val flyway = Flyway.configure().dataSource(dataSource).load() flyway.migrate() Database.connect( datasource = dataSource, databaseConfig = DatabaseConfig { sqlLogger = StdOutSqlLogger useNestedTransactions = false defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE defaultRepetitionAttempts = 2 } ) } single(createdAtStart = true) { val client = s3.config("client") val endpoint = client.config("endpoint") val secrets: S3CredentialsConfig = Resources.hocon("secrets/s3.dev.conf") val s3Client = S3Client { endpointUrl = Url.invoke { scheme = Scheme.parse(endpoint.property("scheme").getString()) host = Host.parse(endpoint.property("host").getString()) port = endpoint.property("port").getInt() } region = client.property("region").getString() forcePathStyle = client.property("forcePathStyle").getBoolean() credentialsProvider = EnvironmentCredentialsProvider( mapOf( "AWS_ACCESS_KEY_ID" to secrets.username, "AWS_SECRET_ACCESS_KEY" to secrets.password )::get ) } s3Client } single(createdAtStart = true) { RefreshTokenPersistenceConfig( auth.property("lasting.refresh").getString().toDuration() ) } single(createdAtStart = true) { RegistrationTokenPersistenceConfig( auth.property("lasting.registration").getString().toDuration() ) } single(createdAtStart = true) { PasswordResetTokenPersistenceConfig( auth.property("lasting.passwordReset").getString().toDuration() ) } single(createdAtStart = true) { ContentPersistenceConfig( Content.Bucket(s3.property("bucket").getString()) ) } single { ExposedRegistrationTokenPersistence(get(), get()) } single { ExposedUserPersistence(get()) } single { ExposedRefreshTokenPersistence(get(), get()) } single { ExposedPasswordResetTokenPersistence(get(), get()) } single { ExposedSocialMediaLinkPersistence(get()) } single { S3ContentPersistence(get(), get()) } single { ExposedContentMetadataPersistence(get()) } }
5
Kotlin
0
0
e39e316a813b5657315c74440409a7af3ae6e3dc
5,446
instakt
MIT License
app/src/main/java/com/example/applaudochallenge/data/models/tvshowdetails/season/episode/GuestStar.kt
mauriciolima1988
561,894,249
false
null
package com.example.applaudochallenge.data.models.tvshowdetails.season.episode data class GuestStar( val adult: Boolean, val character: String, val credit_id: String, val gender: Int, val id: Int, val known_for_department: String, val name: String, val order: Int, val original_name: String, val popularity: Double, val profile_path: String )
0
Kotlin
0
0
d4481d5e5fcfcaf0c953fd1fe806c1aedfcdca9c
388
Applaudo_s_Code_Challenge_Android
MIT License
meta-resolver/src/main/java/com/rarible/core/meta/resolver/cache/RawMetaCacheService.kt
rariblecom
357,923,214
false
{"Markdown": 5, "Maven POM": 23, "Ignore List": 1, "Groovy": 1, "EditorConfig": 1, "Kotlin": 293, "Java": 30, "CODEOWNERS": 1, "YAML": 2, "INI": 2, "XML": 2}
package com.rarible.core.meta.resolver.cache import com.rarible.core.meta.resource.model.UrlResource class RawMetaCacheService( private val caches: List<RawMetaCache> ) { fun getCache(urlResource: UrlResource): RawMetaCache? { return caches.find { it.isSupported(urlResource) } } }
0
Kotlin
3
11
7bbb0bba0fe055a733d7ea6f376a7bcc3146401e
305
service-core
MIT License
tradeit-android-sdk/src/main/kotlin/it/trade/android/sdk/exceptions/TradeItKeystoreServiceDeleteKeyException.kt
tradingticket
74,619,601
false
null
package it.trade.android.sdk.exceptions class TradeItKeystoreServiceDeleteKeyException(message: String, t: Throwable) : Exception(message, t)
2
Kotlin
10
13
1d784e9eba023479652ccc5963ea7a77624bde01
144
AndroidSDK
Apache License 2.0
src/org/elixir_lang/mix/Deps.kt
KronicDeth
22,329,177
false
null
package org.elixir_lang.mix import com.intellij.psi.PsiElement import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.ResolveResult import org.elixir_lang.psi.CallDefinitionClause import org.elixir_lang.psi.ElixirAccessExpression import org.elixir_lang.psi.ElixirTuple import org.elixir_lang.psi.call.Call import org.elixir_lang.psi.call.name.Module.KERNEL import org.elixir_lang.psi.impl.call.stabBodyChildExpressions import org.elixir_lang.psi.impl.childExpressions import org.elixir_lang.psi.impl.stripAccessExpression object Deps { fun from(depsListElement: PsiElement): Sequence<Dep> = when (depsListElement) { is ElixirTuple -> fromTuple(depsListElement) is Call -> fromCall(depsListElement) else -> emptySequence() } // `ecto_dep()` in `ecto_sql` `deps` private fun fromCall(depsListElement: Call): Sequence<Dep> = depsListElement .reference?.let { it as PsiPolyVariantReference } ?.multiResolve(false) ?.asSequence() ?.filter(ResolveResult::isValidResult) ?.mapNotNull(ResolveResult::getElement) ?.filterIsInstance<Call>() ?.filter { CallDefinitionClause.`is`(it) } ?.flatMap { fromCallDefinitionClause(it) } .orEmpty() private fun fromCallDefinitionClause(callDefinitionClause: Call): Sequence<Dep> = callDefinitionClause .stabBodyChildExpressions() ?.flatMap { fromChildExpression(it) } ?: emptySequence() private tailrec fun fromChildExpression(childExpression: PsiElement): Sequence<Dep> = when (childExpression) { is Call -> fromChildExpression(childExpression) is ElixirAccessExpression -> fromChildExpression(childExpression.stripAccessExpression()) is ElixirTuple -> fromTuple(childExpression) else -> { emptySequence() } } private fun fromChildExpression(childExpression: Call): Sequence<Dep> = if (childExpression.isCalling(KERNEL, "if")) { fromIf(childExpression) } else { emptySequence() } private fun fromTuple(tuple: ElixirTuple): Sequence<Dep> = Dep.from(tuple)?.let { sequenceOf(it) }.orEmpty() private fun fromIf(`if`: Call): Sequence<Dep> { val branchStabSequences = `if`.doBlock?.let { doBlock -> val trueStab = doBlock.stab val falseStab = doBlock .blockList ?.blockItemList?.singleOrNull { it.blockIdentifier.text == "else" } ?.stab sequenceOf(trueStab, falseStab).filterNotNull() } ?: emptySequence() return branchStabSequences .flatMap { stab -> stab.stabBody?.childExpressions().orEmpty() } .flatMap { fromChildExpression(it) } } }
590
null
153
1,815
b698fdaec0ead565023bf4461d48734de135b604
3,100
intellij-elixir
Apache License 2.0
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/CatalogsListProductsByFilterRequestOneOf.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import org.openapitools.client.models.CatalogsListProductsByFilterRequestOneOf import org.openapitools.client.models.CatalogsProductGroupFilters import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Request object to list products for a given product group filter. * * @param feedId Catalog Feed id pertaining to the catalog product group filter. * @param filters */ data class CatalogsListProductsByFilterRequest ( /* Catalog Feed id pertaining to the catalog product group filter. */ @Json(name = "feed_id") val feedId: kotlin.String, @Json(name = "filters") val filters: CatalogsProductGroupFilters )
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
969
pinterest-sdk
MIT License
LABA5kt/src/parserPack/CountryParser.kt
deadxraver
778,738,033
false
{"Text": 3, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java Properties": 3, "Java": 221, "INI": 3, "XML": 27, "Ignore List": 4, "JAR Manifest": 1, "Kotlin": 48, "CSS": 4, "HTML": 85, "JavaScript": 9, "Markdown": 2}
package parserPack import elementsPack.Country import java.util.* object CountryParser { /** * Parses the input line to determine the corresponding Country enum value. * * @param line the input line to be parsed * @return the corresponding Country enum value, or null if not found */ fun parse(line: String): Country { return when (line.lowercase(Locale.getDefault())) { "china" -> Country.CHINA "germany" -> Country.GERMANY "japan" -> Country.JAPAN "spain" -> Country.SPAIN "vatican" -> Country.VATICAN else -> null!! } } }
0
Java
0
0
3f262f3175c7142487f8d225e4aac85f8f197d77
658
Programming
MIT License
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/runtime/data/MutableVehicleWindowStatesImpl.kt
Double-O-Seven
142,487,686
false
null
package ch.leadrian.samp.kamp.core.runtime.data import ch.leadrian.samp.kamp.core.api.constants.VehicleWindowState import ch.leadrian.samp.kamp.core.api.data.MutableVehicleWindowStates import ch.leadrian.samp.kamp.core.api.data.VehicleWindowStates internal data class MutableVehicleWindowStatesImpl( override var driver: VehicleWindowState, override var passenger: VehicleWindowState, override var backLeft: VehicleWindowState, override var backRight: VehicleWindowState ) : MutableVehicleWindowStates { override fun toVehicleWindowStates(): VehicleWindowStates = VehicleWindowStatesImpl( driver = driver, passenger = passenger, backLeft = backLeft, backRight = backRight ) override fun toMutableVehicleWindowStates(): MutableVehicleWindowStates = this }
1
null
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
851
kamp
Apache License 2.0
EasyAndroidTest/src/main/java/com/ayvytr/easyandroidtest/customview/AuthEditTextActivity2.kt
FashionKing
137,089,880
true
{"Java Properties": 2, "Shell": 1, "Markdown": 4, "Batchfile": 1, "Proguard": 3, "Java": 76, "Kotlin": 3}
package com.ayvytr.easyandroidtest.customview import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.LinearLayout import com.ayvytr.easyandroid.tools.Colors import com.ayvytr.easyandroid.tools.withcontext.ToastTool import com.ayvytr.easyandroid.view.custom.NewAuthEditText import com.ayvytr.easyandroidtest.R import kotlinx.android.synthetic.main.activity_auth_edit_text2.* import java.util.* class AuthEditTextActivity2 : AppCompatActivity() { private val random = Random() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth_edit_text2) initView(savedInstanceState) } fun initView(savedInstanceState: Bundle?) { btnMaxLength?.setOnClickListener { authEditText?.maxLength = randomMaxLength } btnSize?.setOnClickListener { authEditText?.layoutParams = randomLp } btnTextColor.setOnClickListener { authEditText?.textColor = randomColor } btnTextSize.setOnClickListener { authEditText.textSize = random.nextInt(30) } btnFrameColor.setOnClickListener { authEditText.frameColor = randomColor } btnFrameWidth.setOnClickListener { authEditText.frameWidth = random.nextInt(20) } btnInputType.setOnClickListener { authEditText.inputType = randomInputType } btnPasswordString.setOnClickListener { authEditText.passwordString = <PASSWORD> } authEditText.setOnInputChangeListener(object : NewAuthEditText.OnInputChangeListener { override fun onFinished(authEditText: NewAuthEditText, s: String) { } override fun onTextChanged(isFinished: Boolean, s: String) { ToastTool.show(s) } }) } private val randomMaxLength: Int get() { var i = random.nextInt(NewAuthEditText.MAX_LENGTH) while (i < NewAuthEditText.MIN_LENGTH) { i = random.nextInt(NewAuthEditText.MAX_LENGTH) } return i } private val randomLp: LinearLayout.LayoutParams get() { return LinearLayout.LayoutParams(random.nextInt(500), random.nextInt(400)) } private val randomColor: Int get() { return Colors.rgb(random.nextInt(0xff), random.nextInt(0xff), random.nextInt(0xff)) } private val randomInputType: NewAuthEditText.InputType get() = NewAuthEditText.InputType.valueOf(random.nextInt(5)) private val randomPasswordString: String get() { val i = random.nextInt(6) when (i) { 0 -> return "·" 1 -> return "*" 2 -> return "CCcccccccc" 4 -> return "" else -> return "aaa" } } }
0
Java
0
0
f951a90061a08eae4dd75c786627d43d4ed9bd3e
3,285
EasyAndroid
Apache License 2.0
spring-boot-elasticsearch/src/main/kotlin/de/larmic/es/elasticsearch/TweetRepository.kt
larmic
381,064,402
false
null
package de.larmic.es.elasticsearch import co.elastic.clients.elasticsearch.ElasticsearchClient import co.elastic.clients.elasticsearch.core.* import de.larmic.es.elasticsearch.TweetDocument.Companion.documentIndex import de.larmic.es.rest.Tweet import org.springframework.stereotype.Service import java.util.* @Service class TweetRepository(private val esClient: ElasticsearchClient) { fun storeTweet(tweet: String): String { val document = TweetDocument(tweet) val response = esClient.index { i: IndexRequest.Builder<Any> -> i.index(documentIndex).document(document) } return response.id() } fun getTweet(id: String): Tweet? { val response: GetResponse<TweetDocument> = esClient.get( { g: GetRequest.Builder -> g.index(documentIndex).id(id) }, TweetDocument::class.java ) return if (response.found()) Tweet(response.id(), response.source()!!.message) else null } fun getAllTweets(): List<Tweet> { val response: SearchResponse<TweetDocument> = esClient.search( { s: SearchRequest.Builder -> s.index(documentIndex) }, TweetDocument::class.java ) return response.hits().hits().map { Tweet(it.id(), it.source()!!.message) } } fun updateTweet(id: String, tweet: String): RestStatus { if (!tweetExists(id)) { return RestStatus.NOT_FOUND } val jsonMap = HashMap<String, Any>() jsonMap["message"] = tweet esClient.update( { u: UpdateRequest.Builder<TweetDocument, Any> -> u.index(documentIndex).id(id).doc(jsonMap) }, TweetDocument::class.java ) return RestStatus.OK } fun deleteTweet(id: String): RestStatus { if (!tweetExists(id)) { return RestStatus.NOT_FOUND } esClient.delete { d: DeleteRequest.Builder -> d.index(documentIndex).id(id) } return RestStatus.OK } private fun tweetExists(id: String): Boolean { val response = esClient.exists { g: ExistsRequest.Builder -> g.index(documentIndex).id(id) } return response.value() } enum class RestStatus { OK, NOT_FOUND } }
4
null
6
22
53e8659c1c1062cc3552b561e3a3d813c6a96d86
2,221
spring-boot-demos
Apache License 2.0
idea/src/org/jetbrains/jet/plugin/references/JetSimpleNameReference.kt
nickgieschen
21,116,939
true
null
/* * Copyright 2010-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jet.plugin.references import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.jet.lang.psi.* import org.jetbrains.jet.lang.resolve.name.FqName import org.jetbrains.jet.lexer.JetTokens import org.jetbrains.jet.plugin.codeInsight.ShortenReferences import org.jetbrains.jet.plugin.refactoring.changeQualifiedName import org.jetbrains.jet.lang.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.jet.lang.psi.psiUtil.getOutermostNonInterleavingQualifiedElement import org.jetbrains.jet.plugin.codeInsight.addToShorteningWaitSet import org.jetbrains.jet.plugin.refactoring.getKotlinFqName public class JetSimpleNameReference( jetSimpleNameExpression: JetSimpleNameExpression ) : JetSimpleReference<JetSimpleNameExpression>(jetSimpleNameExpression) { override fun getRangeInElement(): TextRange = TextRange(0, getElement().getTextLength()) public override fun handleElementRename(newElementName: String?): PsiElement? { if (newElementName == null) return null; val project = expression.getProject() val element = when (expression.getReferencedNameElementType()) { JetTokens.FIELD_IDENTIFIER -> JetPsiFactory.createFieldIdentifier(project, newElementName) JetTokens.LABEL_IDENTIFIER -> JetPsiFactory.createClassLabel(project, newElementName) else -> JetPsiFactory.createNameIdentifier(project, newElementName) } return expression.getReferencedNameElement().replace(element) } public enum class ShorteningMode { NO_SHORTENING DELAYED_SHORTENING FORCED_SHORTENING } // By default reference binding is delayed override fun bindToElement(element: PsiElement): PsiElement { return element.getKotlinFqName()?.let { fqName -> bindToFqName(fqName) } ?: expression } public fun bindToFqName(fqName: FqName, shorteningMode: ShorteningMode = ShorteningMode.DELAYED_SHORTENING): PsiElement { if (fqName.isRoot()) return expression val newExpression = expression.changeQualifiedName(fqName).getQualifiedElementSelector() as JetSimpleNameExpression val newQualifiedElement = newExpression.getOutermostNonInterleavingQualifiedElement() if (shorteningMode == ShorteningMode.NO_SHORTENING) return newExpression val needToShorten = PsiTreeUtil.getParentOfType(expression, javaClass<JetImportDirective>(), javaClass<JetPackageDirective>()) == null if (needToShorten) { if (shorteningMode == ShorteningMode.FORCED_SHORTENING) { ShortenReferences.process(newQualifiedElement) } else { newQualifiedElement.addToShorteningWaitSet() } } return newExpression } override fun toString(): String { return javaClass<JetSimpleNameReference>().getSimpleName() + ": " + expression.getText() } }
0
Java
0
0
d150bfbce0e2e47d687f39e2fd233ea55b2ccd26
3,619
kotlin
Apache License 2.0
compose-ide-plugin/src/com/android/tools/compose/ComposeGradleInspectionSuppressor.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.compose import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.projectsystem.getModuleSystem import com.intellij.codeInspection.InspectionSuppressor import com.intellij.codeInspection.SuppressQuickFix import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement // TODO: This is a hotfix for b/194313332 and should be removed eventually. class ComposeGradleInspectionSuppressor : InspectionSuppressor { override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean { return StudioFlags.COMPOSE_EDITOR_SUPPORT.get() && toolId == "DifferentKotlinGradleVersion" && usesComposeInProject(element.project) } private fun usesComposeInProject(project: Project): Boolean { val modules = ModuleManager.getInstance(project).modules return modules.any { it.getModuleSystem().usesCompose } } override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> { return SuppressQuickFix.EMPTY_ARRAY } }
0
Kotlin
220
857
8d22f48a9233679e85e42e8a7ed78bbff2c82ddb
1,719
android
Apache License 2.0
app/src/main/java/com/dan/videostab/MaskEditFragment.kt
danopdev
509,471,483
false
{"Java": 2491319, "Kotlin": 86467, "Python": 9906, "AIDL": 1990}
package com.dan.videostab import android.graphics.* import android.os.Bundle import android.util.DisplayMetrics import android.view.* import com.dan.videostab.databinding.MaskEditFragmentBinding import org.opencv.android.Utils import org.opencv.core.Core.* import org.opencv.core.CvType import org.opencv.core.Mat class MaskEditFragment(activity: MainActivity, image: Mat, private val mask: Mat, private val onOKListener: ()->Unit ) : AppFragment(activity) { companion object { private const val RADIUS = 50f //dp fun show(activity: MainActivity, image: Mat, mask: Mat, onOKListener: ()->Unit ) { activity.pushView( "Edit Mask", MaskEditFragment( activity, image, mask, onOKListener ) ) } private fun matToBitmap( image: Mat, bitmap: Bitmap ) { val imageRGB: Mat if (CvType.CV_8UC1 == image.type()) { imageRGB = Mat() merge(listOf(image, image, image), imageRGB) } else { imageRGB = image } Utils.matToBitmap(imageRGB, bitmap) } } private lateinit var binding: MaskEditFragmentBinding private var fromX = -1f private var fromY = -1f private val paint = Paint() private val touchImageViewListenerNone = object : TouchImageViewListener { override fun onViewRectChanged(rect: RectF) { } override fun onTouchEvent(event: MotionEvent): Boolean { return true } } private val touchImageViewListenerDrawMask = object : TouchImageViewListener { override fun onViewRectChanged(rect: RectF) { binding.imageView.viewRect = rect } override fun onTouchEvent(event: MotionEvent): Boolean { if (!binding.buttonDraw.isPressed && !binding.buttonErase.isPressed) return false if (MotionEvent.ACTION_DOWN != event.action && MotionEvent.ACTION_MOVE != event.action) { fromX = -1f fromY = -1f return true } val draw = binding.buttonDraw.isPressed val color = if (draw) 255 else 0 val viewRect = binding.imageView.viewRect val scale = image.cols() / viewRect.width() val toX = (event.x - viewRect.left) * scale val toY = (event.y - viewRect.top) * scale val radius = convertDpToPixel(RADIUS) * scale if (fromX < 0 || fromY < 0) { fromX = toX fromY = toY } drawMask { canvas -> paint.color = Color.rgb(color, color, color) paint.strokeWidth = radius canvas.drawLine(fromX, fromY, toX, toY, paint) } fromX = toX fromY = toY return true } } private val imageBitmap: Bitmap = Bitmap.createBitmap( image.cols(), image.rows(), Bitmap.Config.ARGB_8888 ) private val maskBitmap: Bitmap = Bitmap.createBitmap( image.cols(), image.rows(), Bitmap.Config.ARGB_8888 ) init { matToBitmap(image, imageBitmap) if (!mask.empty()) { matToBitmap(mask, maskBitmap) } else { matToBitmap(Mat.zeros(image.rows(), image.cols(), CvType.CV_8UC1), maskBitmap) } paint.isAntiAlias = false paint.strokeCap = Paint.Cap.ROUND paint.strokeJoin = Paint.Join.ROUND } private fun convertDpToPixel(dp: Float): Float { val context = this.context ?: return dp return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } private fun drawMask(callback:(canvas: Canvas)->Unit) { val canvas = Canvas(maskBitmap) callback(canvas) binding.maskView.invalidate() } private fun setMask(value: Int) { drawMask { canvas -> canvas.drawARGB(255, value, value, value) } } override fun onBack(homeButton: Boolean) { if (!homeButton) return val maskMat = Mat() Utils.bitmapToMat(maskBitmap, maskMat) val channels = mutableListOf<Mat>() split(maskMat, channels) val maskChannel = channels[0] val maskChannelIsEmpty = 0 == countNonZero(maskChannel) if (maskChannelIsEmpty && mask.empty()) return //nothing to do if (maskChannelIsEmpty) { mask.release() } else { if (mask.empty()) mask.create(maskChannel.rows(), maskChannel.cols(), CvType.CV_8UC1) maskChannel.copyTo(mask) } onOKListener.invoke() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = MaskEditFragmentBinding.inflate( inflater ) binding.imageView.setListener(touchImageViewListenerNone) binding.maskView.setListener(touchImageViewListenerDrawMask) binding.buttonClear.setOnClickListener{ setMask(0) } binding.buttonFill.setOnClickListener{ setMask(255) } binding.imageView.setBitmap(imageBitmap) binding.maskView.setBitmap(maskBitmap) return binding.root } }
1
null
1
1
da3e7aa6bc0df4a1f01cda4d8e495a32b0695d0a
5,268
VideoStab
MIT License
kotlin.web.demo.server/examples/Kotlin in Action/Chapter 4/4.1/2_1_OpenFinalAndAbstractModifiersFinalByDefault.kt
arrow-kt
117,599,238
false
null
package ch04.ex1_2_1_OpenFinalAbstractModifiers interface Clickable { fun click() fun showOff() = println("I'm clickable!") } open class RichButton : Clickable { fun disable() {} open fun animate() {} override fun click() {} }
3
null
4
7
7165d9568d725c9784a1e7525f35bab93241f292
252
try.arrow-kt.io
Apache License 2.0
plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinStringStubIndexExtension.kt
jinsihou19
192,350,885
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.stubindex import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StubIndex import com.intellij.util.CommonProcessors import com.intellij.util.Processor import com.intellij.util.Processors import com.intellij.util.indexing.IdFilter abstract class KotlinStringStubIndexExtension<PsiNav : NavigatablePsiElement>(private val valueClass: Class<PsiNav>) : StringStubIndexExtension<PsiNav>() { /** * Note: [processor] should not invoke any indices as it could lead to deadlock. Nested index access is forbidden. */ fun processElements(s: String, project: Project, scope: GlobalSearchScope, processor: Processor<in PsiNav>): Boolean { return processElements(s, project, scope, null, processor) } /** * Note: [processor] should not invoke any indices as it could lead to deadlock. Nested index access is forbidden. */ fun processElements(s: String, project: Project, scope: GlobalSearchScope, idFilter: IdFilter? = null, processor: Processor<in PsiNav>): Boolean { return StubIndex.getInstance().processElements(key, s, project, scope, idFilter, valueClass, processor) } fun processAllElements( project: Project, scope: GlobalSearchScope, filter: (String) -> Boolean = { true }, processor: Processor<in PsiNav> ) { val stubIndex = StubIndex.getInstance() val indexKey = key // collect all keys, collect all values those fulfill filter into a single collection, process values after that val allKeys = HashSet<String>() if (!processAllKeys(project, CancelableCollectFilterProcessor(allKeys, filter))) return if (allKeys.isNotEmpty()) { val values = HashSet<PsiNav>(allKeys.size) val collectProcessor = Processors.cancelableCollectProcessor(values) allKeys.forEach { s -> if (!stubIndex.processElements(indexKey, s, project, scope, valueClass, collectProcessor)) return } // process until the 1st negative result of processor values.all(processor::process) } } fun processAllKeys(scope: GlobalSearchScope, filter: IdFilter? = null, processor: Processor<in String>): Boolean = StubIndex.getInstance().processAllKeys(key, processor, scope, filter) } class CancelableCollectFilterProcessor<T>( collection: Collection<T>, private val filter: (T) -> Boolean ) : CommonProcessors.CollectProcessor<T>(collection) { override fun process(t: T): Boolean { ProgressManager.checkCanceled() return super.process(t) } override fun accept(t: T): Boolean = filter(t) }
1
null
1
1
55cb0396e166a3f4e114a59e9357d2e390a6dd96
3,062
intellij-community
Apache License 2.0
medeia-validator-core/src/main/kotlin/com/worldturner/medeia/format/idn-hostname.kt
crunchyroll
364,234,759
true
{"Kotlin": 359238, "Java": 18810}
package com.worldturner.medeia.format import com.worldturner.medeia.format.IdnProperty.CONTEXTO import com.worldturner.medeia.format.IdnProperty.DISALLOWED import com.worldturner.medeia.format.IdnProperty.PVALID import com.worldturner.medeia.format.i18n.Punycode import com.worldturner.util.toCodePoints import java.lang.Character.UnicodeBlock.ANCIENT_GREEK_MUSICAL_NOTATION import java.lang.Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS import java.lang.Character.UnicodeBlock.MUSICAL_SYMBOLS fun String.isIdnHostname() = try { this.idnToLdhHostname().isHostname() } catch (e: IllegalArgumentException) { false } fun String.idnToLdhHostname(): String = this.split('.').map { it.idnToLdhLabel() }.joinToString(".") fun String.idnToLdhLabel(): String = if (this.toCodePoints().count { Punycode.parameters.isBasicCodePoint(it) } == this.length) { // Label is not internationalized this } else { this.toCodePoints().forEach { if (it.idnProperty() != PVALID) throw IllegalArgumentException("Illegal code point in IDN label $it") } "xn--${Punycode.encode(this)}" } enum class IdnProperty { PVALID, CONTEXTJ, CONTEXTO, DISALLOWED, UNASSIGNED } fun Int.idnProperty(): IdnProperty { // If .cp. .in. Exceptions Then Exceptions(cp); idnCodePointsExceptions[this]?.let { return it } // Else If .cp. .in. BackwardCompatible Then BackwardCompatible(cp); idnCodePointsBackwardsCompatible[this]?.let { return it } // Else If .cp. .in. Unassigned Then UNASSIGNED; // Else If .cp. .in. LDH Then PVALID; if (this == '-'.toInt() || Punycode.parameters.isBasicCodePoint(this)) return PVALID // Else If .cp. .in. JoinControl Then CONTEXTJ; // Else If .cp. .in. Unstable Then DISALLOWED; // Else If .cp. .in. IgnorableProperties Then DISALLOWED; if (idnIsIgnorableProperty()) return DISALLOWED // Else If .cp. .in. IgnorableBlocks Then DISALLOWED; if (idnIsIgnorableBlocks()) return DISALLOWED // Else If .cp. .in. OldHangulJamo Then DISALLOWED; // Else If .cp. .in. LetterDigits Then PVALID; if (Character.isLetterOrDigit(this)) return PVALID // Else DISALLOWED; return DISALLOWED } fun Int.idnIsIgnorableProperty(): Boolean { return Character.isWhitespace(this) // C: Default_Ignorable_Code_Point(cp) = True or // White_Space(cp) = True or // Noncharacter_Code_Point(cp) = True } fun Int.idnIsIgnorableBlocks(): Boolean { // D: Block(cp) is in {Combining Diacritical Marks for Symbols, // Musical Symbols, Ancient Greek Musical Notation} val block = Character.UnicodeBlock.of(this) return block == COMBINING_MARKS_FOR_SYMBOLS || block == MUSICAL_SYMBOLS || block == ANCIENT_GREEK_MUSICAL_NOTATION } val idnCodePointsExceptions = mapOf( 0x00DF to PVALID, // LATIN SMALL LETTER SHARP S 0x03C2 to PVALID, // GREEK SMALL LETTER FINAL SIGMA 0x06FD to PVALID, // ARABIC SIGN SINDHI AMPERSAND 0x06FE to PVALID, // ARABIC SIGN SINDHI POSTPOSITION MEN 0x0F0B to PVALID, // TIBETAN MARK INTERSYLLABIC TSHEG 0x3007 to PVALID, // IDEOGRAPHIC NUMBER ZERO 0x00B7 to CONTEXTO, // MIDDLE DOT 0x0375 to CONTEXTO, // GREEK LOWER NUMERAL SIGN (KERAIA) 0x05F3 to CONTEXTO, // HEBREW PUNCTUATION GERESH 0x05F4 to CONTEXTO, // HEBREW PUNCTUATION GERSHAYIM 0x30FB to CONTEXTO, // KATAKANA MIDDLE DOT 0x0660 to CONTEXTO, // ARABIC-INDIC DIGIT ZERO 0x0661 to CONTEXTO, // ARABIC-INDIC DIGIT ONE 0x0662 to CONTEXTO, // ARABIC-INDIC DIGIT TWO 0x0663 to CONTEXTO, // ARABIC-INDIC DIGIT THREE 0x0664 to CONTEXTO, // ARABIC-INDIC DIGIT FOUR 0x0665 to CONTEXTO, // ARABIC-INDIC DIGIT FIVE 0x0666 to CONTEXTO, // ARABIC-INDIC DIGIT SIX 0x0667 to CONTEXTO, // ARABIC-INDIC DIGIT SEVEN 0x0668 to CONTEXTO, // ARABIC-INDIC DIGIT EIGHT 0x0669 to CONTEXTO, // ARABIC-INDIC DIGIT NINE 0x06F0 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT ZERO 0x06F1 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT ONE 0x06F2 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT TWO 0x06F3 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT THREE 0x06F4 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT FOUR 0x06F5 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT FIVE 0x06F6 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT SIX 0x06F7 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT SEVEN 0x06F8 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT EIGHT 0x06F9 to CONTEXTO, // EXTENDED ARABIC-INDIC DIGIT NINE 0x0640 to DISALLOWED, // ARABIC TATWEEL 0x07FA to DISALLOWED, // NKO LAJANYALAN 0x302E to DISALLOWED, // HANGUL SINGLE DOT TONE MARK 0x302F to DISALLOWED, // HANGUL DOUBLE DOT TONE MARK 0x3031 to DISALLOWED, // VERTICAL KANA REPEAT MARK 0x3032 to DISALLOWED, // VERTICAL KANA REPEAT WITH VOICED SOUND MARK 0x3033 to DISALLOWED, // VERTICAL KANA REPEAT MARK UPPER HALF 0x3034 to DISALLOWED, // VERTICAL KANA REPEAT WITH VOICED SOUND MARK UPPER HA 0x3035 to DISALLOWED, // VERTICAL KANA REPEAT MARK LOWER HALF 0x303B to DISALLOWED // VERTICAL IDEOGRAPHIC ITERATION MARK ) val idnCodePointsBackwardsCompatible = mapOf<Int, IdnProperty>()
1
null
0
0
9f435c57f5a31cc5f7fbde6cdae747c38a2ed9ec
5,289
medeia-validator
Apache License 2.0
intellij-plugin-verifier/verifier-repository/src/main/java/com/jetbrains/pluginverifier/repository/repositories/bundled/BundledPluginsRepository.kt
Ololoshechkin
291,723,586
false
null
/* * Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.pluginverifier.repository.repositories.bundled import com.jetbrains.plugin.structure.ide.Ide import com.jetbrains.plugin.structure.intellij.version.IdeVersion import com.jetbrains.pluginverifier.repository.PluginRepository import com.jetbrains.pluginverifier.repository.repositories.VERSION_COMPARATOR /** * [PluginRepository] consisting of plugins bundled to the [IDE] [ide]. */ class BundledPluginsRepository( val ide: Ide ) : PluginRepository { private fun getAllPlugins() = ide.bundledPlugins.map { BundledPluginInfo(ide.version, it) } override fun getLastCompatiblePlugins(ideVersion: IdeVersion) = getAllPlugins() .filter { it.isCompatibleWith(ideVersion) } .groupBy { it.pluginId } .mapValues { it.value.maxWith(VERSION_COMPARATOR)!! } .values.toList() override fun getLastCompatibleVersionOfPlugin(ideVersion: IdeVersion, pluginId: String) = getAllVersionsOfPlugin(pluginId).filter { it.isCompatibleWith(ideVersion) }.maxWith(VERSION_COMPARATOR) override fun getAllVersionsOfPlugin(pluginId: String) = getAllPlugins().filter { it.pluginId == pluginId } override fun getIdOfPluginDeclaringModule(moduleId: String) = ide.getPluginByModule(moduleId)?.pluginId fun findPluginById(pluginId: String) = getAllVersionsOfPlugin(pluginId).firstOrNull() fun findPluginByModule(moduleId: String) = getAllPlugins().find { moduleId in it.idePlugin.definedModules } override val presentableName get() = "Bundled plugins of ${ide.version}" override fun toString() = presentableName }
0
null
0
1
524190e01f9a2421c9e972356d23649e27eed865
1,754
plugin-verifier
Apache License 2.0
memory-benchmark/src/MemoryUsage.kt
orangy
746,253,476
true
{"XML": 12, "Maven POM": 5, "EditorConfig": 1, "Markdown": 1, "Text": 3, "Ignore List": 2, "Java": 40, "Kotlin": 13, "JSON": 5, "YAML": 1, "TOML": 1, "JavaScript": 2, "HTML": 1, "JSON with Comments": 1, "SVG": 1, "Vue": 3, "CSS": 1}
import it.unimi.dsi.fastutil.objects.Object2LongArrayMap import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap import org.jetbrains.benchmark.collection.* import org.openjdk.jmh.infra.Blackhole import java.nio.file.Path fun main() { @Suppress("SpellCheckingInspection") val blackhole = Blackhole("Today's password is swordfish. I understand instantiating Blackholes directly is dangerous.") val sizes = sequenceOf(100, 1_000, 10_00, 100_000, 1_000_000, 10_000_000).map { Util.formatSize(it) }.toList() val types = listOf("IntToInt", "IntToObject", "ObjectToInt", "ObjectToObject", "ReferenceToObject", "LinkedMap") val typeToData = Object2ObjectArrayMap<String, Object2ObjectArrayMap<String, Object2LongArrayMap<String>>>() val measurers = measurers + KotlinObjectToObjectMemoryBenchmark() + KotlinLinkedMapMemoryBenchmark() for (type in types) { val sizeToOperations = Object2ObjectArrayMap<String, Object2LongArrayMap<String>>() typeToData.put(type, sizeToOperations) for (size in sizes) { println("measure $type for size $size") val operations = Object2LongArrayMap<String>() sizeToOperations.put(size, operations) for (measurer in measurers) { if (measurer.javaClass.name.contains(type)) { measurer.measure(size, operations, blackhole) } } } } writeJson("memoryChartData", Path.of("site", "memory-data.js")) { writer -> writer.writeStartObject() writeSizesAndSeries(writer, sizes.asSequence().map { Util.parseSize(it) }) for (entry in typeToData.object2ObjectEntrySet().fastIterator()) { writer.writeArrayFieldStart(entry.key) for (sizeEntry in entry.value.object2ObjectEntrySet().fastIterator()) { writer.writeStartObject() writer.writeStringField("size", sizeEntry.key) for (operationEntry in sizeEntry.value.object2LongEntrySet().fastIterator()) { writer.writeNumberField(operationEntry.key, operationEntry.longValue) } writer.writeEndObject() } writer.writeEndArray() } writer.writeEndObject() } }
0
null
0
0
1dbf4c79a10c386e69321a9d51d71d79a5f5ad20
2,104
jvm-collection-lib-benchmarks
The Unlicense
buildSrc/src/main/kotlin/ru/surfstudio/android/build/exceptions/FolderNotFoundException.kt
surfstudio
175,407,898
false
null
package ru.surfstudio.android.build.exceptions import org.gradle.api.GradleException /** * Throw when folder doesn't exist somewhere */ class FolderNotFoundException(folderPath: String) : GradleException( "Can't find folder with folderPath : $folderPath in artifactory." )
1
null
2
27
5f68262ac148bc090c600121295f81c7ce3486c0
284
EasyAdapter
Apache License 2.0
android/src/main/kotlin/top/kikt/ijkplayer/IjkplayerPlugin.kt
mpcreza
293,030,579
false
{"Markdown": 17, "YAML": 3, "JSON": 6, "Text": 1, "Ignore List": 4, "XML": 18, "Git Attributes": 1, "Gradle": 6, "Shell": 4, "INI": 6, "Proguard": 1, "Batchfile": 1, "Java": 29, "Kotlin": 7, "Dart": 56, "Java Properties": 2, "Ruby": 4, "OpenStep Property List": 4, "Objective-C": 19, "HTML": 1}
package top.kikt.ijkplayer import android.app.Activity import android.content.Context import android.media.AudioManager import android.view.WindowManager import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.activity.ActivityAware import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result import io.flutter.view.TextureRegistry import tv.danmaku.ijk.media.player.IjkMediaPlayer /** * IjkplayerPlugin */ class IjkplayerPlugin: FlutterPlugin, ActivityAware, MethodCallHandler { private lateinit var channel : MethodChannel private var activity : Activity? = null private lateinit var textureRegistry : TextureRegistry private lateinit var manager: IjkManager private lateinit var binaryMessenger: BinaryMessenger override fun onMethodCall(call: MethodCall, result: Result) { IjkMediaPlayer.loadLibrariesOnce(null) IjkMediaPlayer.native_profileBegin("libijkplayer.so") handleMethodCall(call, result) } private fun handleMethodCall(call: MethodCall, result: Result) { when (call.method) { "init" -> { manager.disposeAll() result.success(true) } "create" -> { try { val options: Map<String, Any> = call.arguments() val ijk = manager.create(options) result.success(ijk.id) } catch (e: Exception) { e.printStackTrace() result.error("1", "创建失败", e) } } "dispose" -> { val id = call.argument<Int>("id")!!.toLong() manager.dispose(id) result.success(true) } "setSystemVolume" -> { val volume = call.argument<Int>("volume") if (volume != null) { setVolume(volume) } result.success(true) } "getSystemVolume" -> { val volume = getSystemVolume() result.success(volume) } "volumeUp" -> { this.volumeUp() val volume = getSystemVolume() result.success(volume) } "volumeDown" -> { this.volumeDown() val volume = getSystemVolume() result.success(volume) } "setSystemBrightness" -> { val target = call.argument<Double>("brightness") if (target != null) setBrightness(target.toFloat()) result.success(true) } "getSystemBrightness" -> { result.success(getBrightness().toDouble()) } "resetBrightness" -> { setBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) result.success(true) } "showStatusBar" -> { val show = call.arguments<Boolean>() setStatusBar(show) } else -> result.notImplemented() } } private fun setStatusBar(show: Boolean) { val window = activity?.window ?: return if (show) { window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN) } } private fun getSystemVolume(): Int { val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat() return (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() / max * 100).toInt() } private fun setVolume(volume: Int) { audioManager.apply { val max = getStreamMaxVolume(AudioManager.STREAM_MUSIC) val step = 100.toFloat() / max.toFloat() val current = getSystemVolume() val progress = current * step if (volume > progress) { volumeDown() } else if (volume < progress) { volumeUp() } } } private fun volumeUp() { audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND) } private fun volumeDown() { audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND) } private val audioManager: AudioManager get() = activity?.getSystemService(Context.AUDIO_SERVICE) as AudioManager private fun setBrightness(brightness: Float) { val window = activity?.window val lp = window?.attributes lp?.screenBrightness = brightness window?.attributes = lp } private fun getBrightness(): Float { val window = activity?.window val lp = window?.attributes return lp?.screenBrightness!! } fun MethodCall.getLongArg(key: String): Long { return this.argument<Int>(key)!!.toLong() } fun MethodCall.getLongArg(): Long { return this.arguments<Int>().toLong() } override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(binding.binaryMessenger, "top.kikt/ijkplayer") textureRegistry = binding.textureRegistry binaryMessenger = binding.binaryMessenger } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } override fun onAttachedToActivity(binding: ActivityPluginBinding) { activity = binding.activity manager = IjkManager(textureRegistry, activity!!, binaryMessenger) channel.setMethodCallHandler(this) } override fun onDetachedFromActivityForConfigChanges() { } override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { activity = binding.activity } override fun onDetachedFromActivity() { } }
1
null
1
1
b782a0764507bd8bd7725c901a80a310d24db273
6,583
flutter_ijkplayer
MIT License
checkout/src/main/java/com/checkout/tokenization/error/TokenizationError.kt
checkout
140,300,675
false
null
package com.checkout.tokenization.error import com.checkout.base.error.CheckoutError internal class TokenizationError( errorCode: String, message: String? = null, cause: Throwable? = null, ) : CheckoutError( errorCode, message, cause, ) { companion object { const val INVALID_TOKEN_REQUEST = "TokenizationError.Server:3000" const val INVALID_KEY = "TokenizationError.Server:3002" const val TOKENIZATION_API_RESPONSE_PROCESSING_ERROR = "TokenizationError.Server:3003" const val TOKENIZATION_API_MALFORMED_JSON = "TokenizationError.Server:3004" const val GOOGLE_PAY_REQUEST_PARSING_ERROR = "TokenizationError.Server:3005" } }
14
null
37
51
6eda7b1a9331c5fb1ababa205e3f3123f1b56ff3
698
frames-android
MIT License
checkout/src/main/java/com/checkout/tokenization/error/TokenizationError.kt
checkout
140,300,675
false
null
package com.checkout.tokenization.error import com.checkout.base.error.CheckoutError internal class TokenizationError( errorCode: String, message: String? = null, cause: Throwable? = null, ) : CheckoutError( errorCode, message, cause, ) { companion object { const val INVALID_TOKEN_REQUEST = "TokenizationError.Server:3000" const val INVALID_KEY = "TokenizationError.Server:3002" const val TOKENIZATION_API_RESPONSE_PROCESSING_ERROR = "TokenizationError.Server:3003" const val TOKENIZATION_API_MALFORMED_JSON = "TokenizationError.Server:3004" const val GOOGLE_PAY_REQUEST_PARSING_ERROR = "TokenizationError.Server:3005" } }
14
null
37
51
6eda7b1a9331c5fb1ababa205e3f3123f1b56ff3
698
frames-android
MIT License
app/src/main/java/xyz/michaelobi/paperplayer/presentation/musiclibrary/fragment/miniplayer/MiniPlayerPresenter.kt
MichaelObi
62,844,358
false
null
/* * MIT License * * Copyright (c) 2017 <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 xyz.michaelobi.paperplayer.presentation.musiclibrary.fragment.miniplayer import android.util.Log import rx.Subscriber import rx.functions.Action1 import xyz.michaelobi.paperplayer.data.MusicRepositoryInterface import xyz.michaelobi.paperplayer.data.model.Album import xyz.michaelobi.paperplayer.event.RxBus import xyz.michaelobi.paperplayer.injection.Injector import xyz.michaelobi.paperplayer.mvp.BasePresenter import xyz.michaelobi.paperplayer.playback.events.PlaybackState import xyz.michaelobi.paperplayer.playback.events.action.RequestPlaybackState import xyz.michaelobi.paperplayer.playback.events.action.TogglePlayback /** * PaperPlayer * <NAME> * 08 04 2017 10:50 AM */ class MiniPlayerPresenter(private val musicRepository: MusicRepositoryInterface) : BasePresenter<MiniPlayerContract.View>(), MiniPlayerContract.Presenter { private var bus: RxBus = Injector.provideEventBus() override fun onPlayerStateUpdate() { } override fun initialize() { bus.subscribe(PlaybackState::class.java, this, Action1 { playbackState -> view.updatePlayPauseButton(playbackState.playing) view.updateTitleAndArtist(playbackState) playbackState.song?.albumId?.let { getAlbumArtUri(it) } }) bus.post(RequestPlaybackState()) } fun getAlbumArtUri(albumId: Long) { addSubscription(musicRepository.getAlbum(albumId).subscribe(object : Subscriber<Album>() { override fun onCompleted() {} override fun onError(e: Throwable) { Log.e(TAG, e.localizedMessage, e) view.updateSongArt(null) } override fun onNext(album: Album) { view.updateSongArt(album.artPath) } })) } override fun onPlayButtonClicked() = bus.post(TogglePlayback()) override fun detachView() { super.detachView() bus.cleanup(this) } companion object { const val TAG: String = ".MiniPlayerPresenter" } }
0
null
21
47
954ee6a0115973d1611a9c1b942baf3e19a1c887
3,202
PaperPlayer
MIT License
native/commonizer/src/org/jetbrains/kotlin/descriptors/commonizer/mergedtree/ir/CirFunction.kt
prasenjitghose36
258,198,392
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.descriptors.commonizer.mergedtree.ir import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.commonizer.utils.Interner import org.jetbrains.kotlin.descriptors.commonizer.utils.hashCode import org.jetbrains.kotlin.descriptors.commonizer.utils.appendHashCode import org.jetbrains.kotlin.descriptors.commonizer.utils.intern import org.jetbrains.kotlin.name.Name interface CirFunctionModifiers { val isOperator: Boolean val isInfix: Boolean val isInline: Boolean val isTailrec: Boolean val isSuspend: Boolean val isExternal: Boolean } interface CirCallableMemberWithParameters { val valueParameters: List<CirValueParameter> val hasStableParameterNames: Boolean val hasSynthesizedParameterNames: Boolean } interface CirFunction : CirFunctionOrProperty, CirFunctionModifiers, CirCallableMemberWithParameters data class CirCommonFunction( override val annotations: List<CirAnnotation>, override val name: Name, override val modality: Modality, override val visibility: Visibility, override val extensionReceiver: CirExtensionReceiver?, override val returnType: CirType, override val kind: CallableMemberDescriptor.Kind, private val modifiers: CirFunctionModifiers, override val valueParameters: List<CirValueParameter>, override val typeParameters: List<CirTypeParameter>, override val hasStableParameterNames: Boolean, override val hasSynthesizedParameterNames: Boolean ) : CirCommonFunctionOrProperty(), CirFunction, CirFunctionModifiers by modifiers class CirFunctionImpl(original: SimpleFunctionDescriptor) : CirFunctionOrPropertyImpl<SimpleFunctionDescriptor>(original), CirFunction { override val isOperator = original.isOperator override val isInfix = original.isInfix override val isInline = original.isInline override val isTailrec = original.isTailrec override val isSuspend = original.isSuspend override val valueParameters = original.valueParameters.map(CirValueParameterImpl.Companion::create) override val hasStableParameterNames = original.hasStableParameterNames() override val hasSynthesizedParameterNames = original.hasSynthesizedParameterNames() } interface CirValueParameter { val name: Name val annotations: List<CirAnnotation> val returnType: CirType val varargElementType: CirType? val declaresDefaultValue: Boolean val isCrossinline: Boolean val isNoinline: Boolean } data class CirCommonValueParameter( override val name: Name, override val returnType: CirType, override val varargElementType: CirType?, override val isCrossinline: Boolean, override val isNoinline: Boolean ) : CirValueParameter { override val annotations: List<CirAnnotation> get() = emptyList() override val declaresDefaultValue get() = false } class CirValueParameterImpl private constructor(original: ValueParameterDescriptor) : CirValueParameter { override val name = original.name.intern() override val annotations = original.annotations.map(CirAnnotation.Companion::create) override val returnType = CirType.create(original.returnType!!) override val varargElementType = original.varargElementType?.let(CirType.Companion::create) override val declaresDefaultValue = original.declaresDefaultValue() override val isCrossinline = original.isCrossinline override val isNoinline = original.isNoinline // See also org.jetbrains.kotlin.types.KotlinType.cachedHashCode private var cachedHashCode = 0 private fun computeHashCode() = hashCode(name) .appendHashCode(annotations) .appendHashCode(returnType) .appendHashCode(varargElementType) .appendHashCode(declaresDefaultValue) .appendHashCode(isCrossinline) .appendHashCode(isNoinline) override fun hashCode(): Int { var currentHashCode = cachedHashCode if (currentHashCode != 0) return currentHashCode currentHashCode = computeHashCode() cachedHashCode = currentHashCode return currentHashCode } override fun equals(other: Any?): Boolean = when { other === this -> true other is CirValueParameterImpl -> { name == other.name && returnType == other.returnType && annotations == other.annotations && varargElementType == other.varargElementType && declaresDefaultValue == other.declaresDefaultValue && isCrossinline == other.isCrossinline && isNoinline == other.isNoinline } else -> false } companion object { private val interner = Interner<CirValueParameterImpl>() fun create(original: ValueParameterDescriptor): CirValueParameterImpl = interner.intern(CirValueParameterImpl(original)) } }
1
null
1
2
acced52384c00df5616231fa5ff7e78834871e64
5,110
kotlin
Apache License 2.0
overlay/src/main/java/uk/co/alt236/floatinginfo/overlay/writers/FgProcessTextWriter.kt
alt236
21,360,038
false
null
/* * Copyright 2020 <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 uk.co.alt236.floatinginfo.overlay.writers import uk.co.alt236.floatinginfo.common.data.model.ForegroundAppData import uk.co.alt236.floatinginfo.common.string.StringBuilderHelper /** * */ /*package*/ internal class FgProcessTextWriter : TextWriter<ForegroundAppData> { override fun writeText(input: ForegroundAppData?, sb: StringBuilderHelper) { if (input == null) { return } sb.appendBold("Foreground Application Info") sb.startKeyValueSection() sb.append("App Name", input.appName.toString()) sb.append("Package", input.packageName) sb.append("PID", input.pid.toLong()) sb.endKeyValueSection() sb.appendNewLine() } override fun clear() { // NOOP } }
1
Java
10
37
81239735ea9e1e477dbf1ba57f4acea5621fa2ac
1,358
Floating-Info---Android
Apache License 2.0
app/src/main/java/jp/juggler/subwaytooter/pref/impl/FloatPref.kt
tateisu
89,120,200
false
null
package jp.juggler.subwaytooter.pref.impl import android.content.SharedPreferences class FloatPref(key: String, defVal: Float) : BasePref<Float>(key, defVal) { override operator fun invoke(pref: SharedPreferences): Float = pref.getFloat(key, defVal) override fun put(editor: SharedPreferences.Editor, v: Float) { if (v == defVal) editor.remove(key) else editor.putFloat(key, v) } }
25
null
17
146
4cb780909da1399b27e2e278b34f8db23a88b6c0
413
SubwayTooter
Apache License 2.0
mulighetsrommet-arena-adapter/src/main/kotlin/no/nav/mulighetsrommet/arena/adapter/routes/ManagerRoutes.kt
navikt
435,813,834
false
null
package no.nav.mulighetsrommet.arena.adapter.routes import io.ktor.http.* import io.ktor.server.application.call import io.ktor.server.http.content.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.serialization.Serializable import no.nav.mulighetsrommet.arena.adapter.kafka.KafkaConsumerOrchestrator import no.nav.mulighetsrommet.arena.adapter.repositories.Topic import no.nav.mulighetsrommet.arena.adapter.services.ArenaEventService import no.nav.mulighetsrommet.arena.adapter.tasks.ReplayEvents import no.nav.mulighetsrommet.arena.adapter.tasks.ReplayEventsTaskData import org.koin.ktor.ext.inject fun Route.managerRoutes() { val kafka: KafkaConsumerOrchestrator by inject() val arenaEventService: ArenaEventService by inject() singlePageApplication { useResources = true react("web") } get("/topics") { val topics = kafka.getTopics() call.respond(topics) } put("/topics") { val topics = call.receive<List<Topic>>() kafka.updateRunningTopics(topics) call.respond(HttpStatusCode.OK) } val replayEvents: ReplayEvents by inject() put("/events/replay") { val request = call.receive<ReplayEventsTaskData>() replayEvents.schedule(request) call.respond(HttpStatusCode.Created) } put("/event/replay") { val request = call.receive<ReplayTopicEventRequest>() arenaEventService.replayEvent( table = request.table, id = request.arenaId ) call.respond(HttpStatusCode.Created) } delete("/events") { val request = call.receive<DeleteEventsRequest>() arenaEventService.deleteEntities( table = request.table, ids = request.arenaIds ) call.respond(HttpStatusCode.OK) } } @Serializable data class ReplayTopicEventRequest( val table: String, val arenaId: String ) @Serializable data class DeleteEventsRequest( val table: String, val arenaIds: List<String> )
1
Kotlin
1
3
4a9e295dcd541c61b6e31e92757a2f958c9b351b
2,088
mulighetsrommet
MIT License
sdk/src/main/java/com/ngsoft/getapp/sdk/models/MapImportDeployState.kt
getappsh
735,551,269
false
{"Kotlin": 781523, "Java": 7463, "Python": 589}
package com.ngsoft.getapp.sdk.models class MapImportDeployState { var importRequestId: String? = null var state: MapDeployState? = null var statusCode: Status? = null }
3
Kotlin
1
1
6e04b980478ce672d58ad3f2d714d3355cadb3fd
181
getmap-android-sdk
Apache License 2.0
app/src/main/java/pl/vemu/zsme/util/PostComparator.kt
xVemu
231,614,467
false
null
package pl.vemu.zsme.util import androidx.recyclerview.widget.DiffUtil import pl.vemu.zsme.data.model.PostModel import javax.inject.Inject class PostComparator @Inject constructor() : DiffUtil.ItemCallback<PostModel>() { override fun areItemsTheSame(oldItem: PostModel, newItem: PostModel) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: PostModel, newItem: PostModel) = oldItem == newItem }
0
Kotlin
0
3
42b8d5e8bfcd071939b7eb9caeacc1bc6030356b
423
zsme
MIT License
app/src/main/java/com/hxbreak/animalcrossingtools/ui/art/ArtViewModel.kt
HxBreak
268,269,758
false
null
package com.hxbreak.animalcrossingtools.ui.art import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.* import com.hxbreak.animalcrossingtools.adapter.ItemComparable import com.hxbreak.animalcrossingtools.combinedLiveData import com.hxbreak.animalcrossingtools.data.ArtSaved import com.hxbreak.animalcrossingtools.data.Result import com.hxbreak.animalcrossingtools.data.prefs.PreferenceStorage import com.hxbreak.animalcrossingtools.data.source.DataRepository import com.hxbreak.animalcrossingtools.data.source.entity.ArtEntity import com.hxbreak.animalcrossingtools.data.source.entity.ArtEntityMix import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.lang.Exception class ArtViewModel @ViewModelInject constructor( private val repository: DataRepository, private val preferenceStorage: PreferenceStorage ) : ViewModel(){ val locale = preferenceStorage.selectedLocale val refresh = MutableLiveData<Boolean>(false) val loading = MutableLiveData(false) val error = MutableLiveData<Exception?>() val editMode = MutableLiveData(false) private val savedChange = MutableLiveData<Boolean>(false) private val artEntity = refresh.switchMap { loading.value = true liveData (viewModelScope.coroutineContext + Dispatchers.IO){ when(val result = repository.repoSource().allArts()){ is Result.Success -> { error.postValue(null) emit(result.data) } is Result.Error -> error.postValue(result.exception) } loading.postValue(false) } } private val artWithSaved = combinedLiveData(viewModelScope.coroutineContext + Dispatchers.Default, x = artEntity, y = savedChange, runCheck = {x, y -> x }){ art, y -> val saved = repository.local().artDao().getAllArtSaved() val result = art.orEmpty().map { entity -> ArtEntityMix(entity, saved.firstOrNull { entity.id == it.id }) } emit(result) } val selected = MutableLiveData<List<Int>>(emptyList()) val arts = combinedLiveData(viewModelScope.coroutineContext + Dispatchers.Default, x = selected, y = artWithSaved, runCheck = { x, y -> y }){ x, y -> val result = y.orEmpty().map { ArtEntityMixSelectable(it.art, it.saved, x?.contains(it.art.id) ?: false) } emit(result) } val collectedText = artWithSaved.switchMap { liveData (viewModelScope.coroutineContext + Dispatchers.Default){ emit("${it.count { it.saved?.owned ?: false }}/${it.size}") } } val ownAction = combinedLiveData(viewModelScope.coroutineContext + Dispatchers.Default, x = selected, y = artWithSaved, runCheck = {x, y -> x && y}){x, y -> val result = !x.orEmpty().any { id -> y.orEmpty().firstOrNull { id == it.art.id }?.saved?.owned ?: false } emit(result) } fun toggleArt(id: Int) { val list = mutableListOf<Int>() list.addAll(selected.value.orEmpty()) if (list.contains(id)) { list.remove(id) } else { list.add(id) } selected.value = list } fun toggleOwnArt(){ if (selected.value.isNullOrEmpty()) return val to = ownAction.value!! val value = selected.value!!.map { ArtSaved(it, to, 0) } viewModelScope.launch (viewModelScope.coroutineContext + Dispatchers.IO){ loading.postValue(true) repository.local().artDao().insertArtSaved(value) loading.postValue(false) savedChange.postValue(true) } } fun clearSelected() { selected.postValue(emptyList()) } } data class ArtEntityMixSelectable( private val art1: ArtEntity, private val saved1: ArtSaved?, val selected: Boolean): ArtEntityMix(art1, saved1), ItemComparable<Int>{ override fun id() = art1.id }
0
Kotlin
1
6
ced2cb55e8d6c33da4678b48957428c593c95dbe
3,957
AnimalCrossingTools-Android
MIT License
app/src/verify/java/com/merative/healthpass/network/repository/LoginRepo.kt
digitalhealthpass
563,978,682
false
{"Kotlin": 1047923, "HTML": 79495, "Python": 22113, "Java": 1959}
package com.merative.healthpass.network.repository import com.merative.healthpass.exception.ExpirationException import com.merative.healthpass.extensions.isSuccessfulAndHasBody import com.merative.healthpass.extensions.stringfyAndEncodeBase64 import com.merative.healthpass.models.api.login.LoginResponse import com.merative.healthpass.models.login.LoginWithCredentialRequest import com.merative.healthpass.models.sharedPref.Package import com.merative.healthpass.network.interceptors.LoginInterceptor import com.merative.healthpass.network.serviceinterface.LoginService import com.merative.healthpass.utils.asyncToUiSingle import com.merative.healthpass.utils.pref.SharedPrefUtils import io.reactivex.rxjava3.core.Single import retrofit2.HttpException import retrofit2.Response import javax.inject.Inject class LoginRepo @Inject constructor( private val loginService: LoginService, private val sharedPrefUtils: SharedPrefUtils, ) { fun loginWithCredential(aPackage: Package): Single<Response<LoginResponse>> { return Single.just(aPackage) .map { isCredentialValid(aPackage) } .flatMap { valid -> loginWithCredential(valid, aPackage) } .flatMap { response -> handleResponse(response) } .asyncToUiSingle() } private fun isCredentialValid(aPackage: Package): Boolean { val credential = aPackage.verifiableObject.credential!! return !credential.isExpired() && credential.isValid() } private fun loginWithCredential( valid: Boolean, aPackage: Package ): Single<Response<LoginResponse>> { return if (valid) { val encoded = aPackage.verifiableObject.credential!!.stringfyAndEncodeBase64() val body = LoginWithCredentialRequest(encoded) loginService.loginWithCredential(body) } else { throw ExpirationException("Expired credential") } } private fun handleResponse(response: Response<LoginResponse>): Single<Response<LoginResponse>> { return if (response.isSuccessfulAndHasBody()) { val user = LoginInterceptor.parseLoginResponse(response.body()!!) sharedPrefUtils.saveUser(user) Single.just(response) } else { throw HttpException(response) } } }
0
Kotlin
0
0
2b086f6fad007d1a574f8f0511fff0e65e100930
2,321
dhp-android-app
Apache License 2.0
DuasTelas/app/src/main/java/br/unicamp/duastelas/TelaValores.kt
sergiolmm
611,905,073
false
null
package br.unicamp.duastelas import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class TelaValores : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tela_valores) val btnRetorno = findViewById(R.id.btnVoltar) as Button btnRetorno.setOnClickListener { val txt = findViewById(R.id.txt1) as TextView var msg = txt.text Intent().apply { putExtra("Resultado",msg) setResult(RESULT_OK, this) } finish() } } }
0
Kotlin
0
0
d511e540cc756bb2d66a838fcbe44a519509cca5
755
kotlin
Apache License 2.0
modules/mpesa/src/commonMain/kotlin/com/github/jeffnyauke/mpesa/Mpesa.kt
jeffnyauke
803,735,331
false
{"Kotlin": 153700, "Shell": 2903}
/* * Copyright (c) 2024 Jeffrey Nyauke * * 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.github.jeffnyauke.mpesa import com.github.jeffnyauke.mpesa.config.Environment import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.ACCOUNT_BALANCE import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.B2C import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.C2B import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.C2B_REGISTER import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.DYNAMIC_QR import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.STK_PUSH import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.STK_PUSH_QUERY import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.TRANSACTION_REVERSAL import com.github.jeffnyauke.mpesa.constants.Network.Endpoints.TRANSACTION_STATUS import com.github.jeffnyauke.mpesa.network.AccessToken import com.github.jeffnyauke.mpesa.network.bodyOrThrow import com.github.jeffnyauke.mpesa.network.commonKtorConfiguration import com.github.jeffnyauke.mpesa.network.createHttpClient import com.github.jeffnyauke.mpesa.request.AccountBalanceRequest import com.github.jeffnyauke.mpesa.request.B2cRequest import com.github.jeffnyauke.mpesa.request.C2bRegisterRequest import com.github.jeffnyauke.mpesa.request.C2bRequest import com.github.jeffnyauke.mpesa.request.DynamicQrRequest import com.github.jeffnyauke.mpesa.request.StkPushQueryRequest import com.github.jeffnyauke.mpesa.request.StkPushRequest import com.github.jeffnyauke.mpesa.request.TransactionReversalRequest import com.github.jeffnyauke.mpesa.request.TransactionStatusRequest import com.github.jeffnyauke.mpesa.response.AccountBalanceResponse import com.github.jeffnyauke.mpesa.response.B2cResponse import com.github.jeffnyauke.mpesa.response.C2bRegisterResponse import com.github.jeffnyauke.mpesa.response.C2bResponse import com.github.jeffnyauke.mpesa.response.DynamicQrResponse import com.github.jeffnyauke.mpesa.response.StkPushQueryResponse import com.github.jeffnyauke.mpesa.response.StkPushResponse import com.github.jeffnyauke.mpesa.response.TransactionReversalResponse import com.github.jeffnyauke.mpesa.response.TransactionStatusResponse import io.github.reactivecircus.cache4k.Cache import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.HttpClientEngine import io.ktor.client.request.post import io.ktor.client.request.setBody /** * Provides various methods to interact with the Daraja v2.0 M-PESA API. For the official * documentation, see [Safaricom developer website](https://developer.safaricom.co.ke). * * @param consumerKey Daraja API consumer key. * @param consumerSecret Daraja API consumer secret. * @param environment The [Environment] of the API. Defaults to [Environment.SANDBOX]. * @param shouldEnableLogging Boolean value indicating whether to enable logging. Defaults to true * if the environment is [Environment.SANDBOX], false otherwise. * @param httpClientEngine The HTTP client engine to use. Defaults to null, which uses the default * engine for the current platform. * @param cache A cache to store access tokens. Defaults to a new [Cache] instance. * @param httpClientConfig A lambda expression that configures the HTTP client. Defaults to a * configuration that uses the provided consumer key, consumer secret, environment, and logging * settings. * @param httpClient The HTTP client to use. Defaults to a new client configured with the provided * configuration. */ public class Mpesa( private val consumerKey: String, private val consumerSecret: String, private val environment: Environment = Environment.SANDBOX, private val shouldEnableLogging: Boolean = environment == Environment.SANDBOX, private val httpClientEngine: HttpClientEngine? = null, public val cache: Cache<Long, AccessToken> = Cache.Builder<Long, AccessToken>().build(), private val httpClientConfig: HttpClientConfig<*>.() -> Unit = { commonKtorConfiguration( consumerKey, consumerSecret, environment, shouldEnableLogging, cache ).invoke(this) }, private val httpClient: HttpClient = createHttpClient(httpClientEngine, httpClientConfig) ) { /** * Initiates an STK Push (Lipa na M-Pesa Online) transaction. * * STK Push - Lipa na M-Pesa Online API also known as M-PESA express (STK Push) is a * Merchant/Business initiated C2B (Customer to Business) Payment. * * Once you, our merchant integrate with the API, you will be able to send a payment prompt * on the customer's phone (Popularly known as STK Push Prompt) to your customer's M-PESA * registered phone number requesting them to enter their M-PESA pin to authorize and complete * payment. * * @param stkPushRequest The [StkPushRequest] object containing the request details. * @return A [StkPushResponse] object containing the acknowledgement details. * @throws DarajaException if there is an error with the API call. */ public suspend fun initiateStkPush(stkPushRequest: StkPushRequest): StkPushResponse = executeApiRequest(STK_PUSH, stkPushRequest) /** * STK Push query - Check the status of a Lipa Na M-Pesa Online Payment. * * @param stkPushQueryRequest The [StkPushQueryRequest] request object. * @return The [StkPushQueryResponse] object containing the result of the query. * @throws Exception If the API call fails. */ public suspend fun queryStkPushStatus(stkPushQueryRequest: StkPushQueryRequest): StkPushQueryResponse = executeApiRequest(STK_PUSH_QUERY, stkPushQueryRequest) /** * C2B register - Register validation and confirmation URLs on M-Pesa * * Register URL API works in hand with Customer to Business (C2B) APIs and allows receiving * payment notifications to your paybill. This API enables you to register the callback URLs * via which you shall receive notifications for payments to your pay bill/till number. * * @param c2bRegisterRequest The request object containing the validation and confirmation URLs, * and the short code of the paybill or till number. * @return A successful acknowledgement [C2bRegisterResponse] response object. * @throws DarajaException if there is an error while executing the API request. * @see C2bRegisterRequest * @see C2bRegisterResponse */ public suspend fun registerC2bUrls(c2bRegisterRequest: C2bRegisterRequest): C2bRegisterResponse = executeApiRequest(C2B_REGISTER, c2bRegisterRequest) /** * Initiates a C2B transaction between a phone number and an M-Pesa short code registered on * M-Pesa. * * @param c2bRequest The [C2bRequest] object containing the transaction details. * @return A [C2bResponse] object representing the transaction acknowledgement. * @throws DarajaException if the request fails. */ public suspend fun initiateC2bTransaction(c2bRequest: C2bRequest): C2bResponse = executeApiRequest(C2B, c2bRequest) /** * B2C - Transact between an M-Pesa short code to a phone number registered on M-Pesa. * * @param b2cRequest The B2C request object * @return successful acknowledgement [B2cResponse] response object. * @throws DarajaApiException if there is an error in the API call. */ public suspend fun initiateB2cTransaction(b2cRequest: B2cRequest): B2cResponse = executeApiRequest(B2C, b2cRequest) /** * Transaction status - Check the status of a transaction. * * @param transactionStatusRequest Request object that contains the transactionId for which the * status is to be retrieved. * @return successful acknowledgement [TransactionStatusResponse] response object. * @throws [TransactionStatusException] if the transaction status request failed. * @throws [IllegalArgumentException] if the transaction status request is null. * @see [TransactionStatusRequest] * @see [TransactionStatusResponse] */ public suspend fun getTransactionStatus( transactionStatusRequest: TransactionStatusRequest ): TransactionStatusResponse = executeApiRequest(TRANSACTION_STATUS, transactionStatusRequest) /** * Account balance - Enquire the balance on an M-Pesa BuyGoods (Till Number). * * The Account Balance API is used to request the account balance of a short code. This can be * used for both B2C, buy goods and pay bill accounts. * * @param accountBalanceRequest Account balance request object. * @return successful acknowledgement [AccountBalanceResponse] response object. * @throws MpesaException when there is an error in the request. */ public suspend fun getAccountBalance(accountBalanceRequest: AccountBalanceRequest): AccountBalanceResponse = executeApiRequest(ACCOUNT_BALANCE, accountBalanceRequest) /** * Reversal - Reverses a C2B M-Pesa transaction. * * Once a customer pays and there is a need to reverse the transaction, the organization will * use this API to reverse the amount. * * @param transactionReversalRequest The request object containing the transaction details for * reversal. * @return A [TransactionReversalResponse] object containing the reversal details. * @throws DarajaException if the request is unsuccessful. */ public suspend fun transactionReversal( transactionReversalRequest: TransactionReversalRequest ): TransactionReversalResponse = executeApiRequest(TRANSACTION_REVERSAL, transactionReversalRequest) /** * Dynamic QR - Generates a dynamic M-PESA QR Code. * * Use this API to generate a Dynamic QR which enables Safaricom M-PESA customers who have My * Safaricom App or M-PESA app, to scan a QR (Quick Response) code, to capture till number and * amount then authorize to pay for goods and services at select LIPA NA M-PESA (LNM) merchant * outlets. * * @param dynamicQrRequest The [DynamicQrRequest] request object. * @return A [DynamicQrResponse] object representing the successful response, or an error if the * request fails. */ public suspend fun generateDynamicQr(dynamicQrRequest: DynamicQrRequest): DynamicQrResponse = executeApiRequest(DYNAMIC_QR, dynamicQrRequest) private suspend inline fun <reified T : Any> executeApiRequest( apiEndpoint: String, requestBody: Any ): T = httpClient.post(apiEndpoint) { setBody(requestBody) }.bodyOrThrow<T>() }
0
Kotlin
0
0
5f89cd5082f2425a2e5c78927b524429b9229f47
11,238
mpesa-sdk-kotlin
Apache License 2.0
kbomberx-concurrency/src/main/kotlin/kbomberx/concurrency/atomic/Atomic.kt
LM-96
517,382,094
false
{"Kotlin": 253830}
package kbomberx.concurrency.atomic /* DEFAULT ATOMIC VAR ******************************************************************* */ fun <T> T.asAtomic() : AtomicVar<T> { return SimpleAtomicVar(this) } fun <T> atomicVar(value : T) : AtomicVar<T> { return SimpleAtomicVar(value) } /* SIMPLE ATOMIC VAR ******************************************************************** */ fun <T> T.asSimpleAtomic() : SimpleAtomicVar<T> { return SimpleAtomicVar(this) } fun <T> simpleAtomicVar(value : T) : SimpleAtomicVar<T> { return SimpleAtomicVar(value) } /* READ WRITE ATOMIC VAR **************************************************************** */ fun <T> T.asReadWriteAtomic() : ReadWriteAtomicVar<T> { return ReadWriteAtomicVar(this) } fun <T> readWriteAtomicVar(value : T) : ReadWriteAtomicVar<T> { return ReadWriteAtomicVar(value) } /* MULTIPLE ATOMIC ********************************************************************** */ /** * Executes the given [block] locking both atomic variables [atomic1] and [atomic2] * @param atomic1 the first [AtomicVar] * @param atomic2 the second [AtomicVar] * @param block the function to be executed in mutual exclusion */ suspend fun <T1, T2> withBothLocked(atomic1 : AtomicVar<T1>, atomic2: AtomicVar<T2>, block : (T1, T2) -> Unit) { atomic1.atomicUseValue { v1 -> atomic2.atomicUseValue { v2 -> block(v1, v2) } } }
0
Kotlin
0
2
f5c087635ffcb4cea4fea71a4738adf9d3dbfc74
1,414
KBomber
MIT License
library/src/main/kotlin/repository/GraphExporter.kt
spbu-coding-2023
792,472,343
false
{"Kotlin": 239924, "Shell": 384}
package repository import graph.Graph import java.io.File interface GraphExporter { /** * Exports graph to a file */ fun <V, E>exportGraph(graph: Graph<V, E>, file: File) }
1
Kotlin
0
0
b57a0da78a1303417bee51bb5751c67aac14f0aa
193
graphs-1-1
MIT License
src/jvmMain/kotlin/matt/file/context/context.kt
mgroth0
513,680,528
false
null
package matt.file.context import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import matt.file.FileOrURL import matt.file.MFile import matt.file.commons.GRADLE_PROPERTIES_FILE_NAME import matt.file.commons.USER_HOME import matt.file.commons.lcommons.LocalComputeContextFiles import matt.file.commons.rcommons.OpenMindComputeContextFiles import matt.file.commons.rcommons.OpenMindFiles import matt.file.construct.mFile import matt.lang.context.DEFAULT_LINUX_PROGRAM_PATH_CONTEXT import matt.lang.context.DEFAULT_MAC_PROGRAM_PATH_CONTEXT import matt.lang.context.DEFAULT_WINDOWS_PROGRAM_PATH_CONTEXT import matt.lang.platform.HasOs import matt.lang.platform.OsEnum import matt.lang.platform.OsEnum.Linux import matt.lang.platform.OsEnum.Mac import matt.lang.platform.OsEnum.Windows import java.util.* @Serializable sealed interface ComputeContext: HasOs { val files: ComputeContextFiles val taskLabel: String val needsModules: Boolean val usesJavaInSingularity: Boolean val javaHome: MFile? override val os: OsEnum } val ComputeContext.shellPathContext get() = when (os) { OsEnum.Linux -> DEFAULT_LINUX_PROGRAM_PATH_CONTEXT OsEnum.Mac -> DEFAULT_MAC_PROGRAM_PATH_CONTEXT Windows -> DEFAULT_WINDOWS_PROGRAM_PATH_CONTEXT } @Serializable sealed class ComputeContextImpl : ComputeContext { override fun toString(): String { return this::class.simpleName!! } } @Serializable @SerialName("OM") class OpenMindComputeContext : ComputeContextImpl() { override val needsModules = true override val javaHome = null override val usesJavaInSingularity = true override val taskLabel = "OpenMind" override val os = Linux override val files by lazy { OpenMindComputeContextFiles() } override fun equals(other: Any?): Boolean { return other is OpenMindComputeContext } override fun hashCode(): Int { return javaClass.hashCode() } } @Serializable @SerialName("Local") class LocalComputeContext : ComputeContextImpl() { override val os = Mac override val needsModules = false override val usesJavaInSingularity = false override val javaHome by lazy { GRADLE_JAVA_HOME } override val taskLabel = "Local" override val files by lazy { LocalComputeContextFiles() } override fun equals(other: Any?): Boolean { return other is LocalComputeContextFiles } override fun hashCode(): Int { return javaClass.hashCode() } } val GRADLE_JAVA_HOME by lazy { mFile( Properties().apply { load( (USER_HOME + ".gradle" + GRADLE_PROPERTIES_FILE_NAME).reader() ) }["org.gradle.java.home"].toString() ) } interface ComputeContextFiles { companion object { const val BRIAR_EXTRACT_METADATA_FILE_NAME = "metadata.json" const val BRIAR_EXTRACT_MINIMAL_METADATA_FILE_NAME = "metadata_minimal.json" } val libjprofilertiPath: String val defaultPathPrefix: FileOrURL val briarDataFolder: MFile val om2Home get() = mFile(defaultPathPrefix[OpenMindFiles.OM2_HOME.path.removePrefix(MFile.unixSeparator)].cpath) val jProfilerConfigFile: MFile get() = om2Home[".jprofiler_config.xml"] val jarsFolder get() = om2Home["jars"] val tempFolder get() = om2Home["temp"] val snapshotFolder get() = tempFolder["jprofiler"] val latestJpSnapshot get() = snapshotFolder["latest.jps"] val rTaskOutputs get() = om2Home["rTaskOutputs"] val briarExtractsFolder: MFile val sbatchOutputFolder get() = om2Home["output"] val sBatchScript get() = mFile(defaultPathPrefix["home/mjgroth/extract.sh"].cpath) val sBatchScriptJson get() = mFile(sBatchScript.cpath + ".json") val brs1Folder get() = briarDataFolder["BRS1"] val cacheFolder: MFile }
0
Kotlin
0
0
2166a6861e87f7a93f957bd04e129c3335b67179
3,895
file
MIT License
src/main/kotlin/me/fru1t/slik/annotations/Singleton.kt
fru1tstand
111,973,812
false
null
package me.fru1t.slik.annotations /** * Marks a class as a singleton. Slik will only create a single instance of this class per scope * per [Named]. */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Singleton
0
Kotlin
0
0
78c67882c11588d5f80624ae14353b18b05652da
255
fm-slik-kotlin
MIT License
src/main/kotlin/me/fru1t/slik/annotations/Singleton.kt
fru1tstand
111,973,812
false
null
package me.fru1t.slik.annotations /** * Marks a class as a singleton. Slik will only create a single instance of this class per scope * per [Named]. */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Singleton
0
Kotlin
0
0
78c67882c11588d5f80624ae14353b18b05652da
255
fm-slik-kotlin
MIT License
code/2162. Challenge Improve the Phone Number Lookup 3-003-challenge-improve-phone-number-lookup/3-003-challenge-improve-phone-number-lookup/pre-recording/end/src/main/kotlin/main.kt
iOSDevLog
186,328,282
false
null
import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.BehaviorSubject fun main(args: Array<String>) { exampleOf("Challenge 1") { val subscriptions = CompositeDisposable() val contacts = mapOf( "603-555-1212" to "Florent", "212-555-1212" to "Junior", "408-555-1212" to "Marin", "617-555-1212" to "Scott") val convert: (String) -> Int = { value -> val number = try { value.toInt() } catch (e: NumberFormatException) { val keyMap = mapOf( "abc" to 2, "def" to 3, "ghi" to 4, "jkl" to 5, "mno" to 6, "pqrs" to 7, "tuv" to 8, "wxyz" to 9) keyMap.filter { it.key.contains(value.toLowerCase()) }.map { it.value }.first() } if (number < 10) { number } else { sentinel // RxJava 2 does not allow null in stream, so return sentinel value } } val format: (List<Int>) -> String = { inputs -> val phone = inputs.map { it.toString() }.toMutableList() phone.add(3, "-") phone.add(7, "-") phone.joinToString("") } val dial: (String) -> String = { phone -> val contact = contacts[phone] if (contact != null) { "Dialing $contact ($phone)..." } else { "Contact not found" } } val input = BehaviorSubject.createDefault<String>("$sentinel") // Add your code here subscriptions.add( input .map(convert) .filter { it != sentinel } .skipWhile { it == 0 } .take(10) .toList() .map(format) .map(dial) .subscribeBy(onSuccess = { println(it) }, onError = { println(it) })) input.onNext("617") input.onNext("0") input.onNext("408") input.onNext("6") input.onNext("212") input.onNext("0") input.onNext("3") "JKL1A1B".forEach { input.onNext(it.toString()) // Need toString() or else Char conversion is done } input.onNext("9") } }
0
null
1
4
8b81fbeb046abfeda95f9870c3c29b4998dbb12d
2,129
raywenderlich
MIT License
compiler/fir/analysis-tests/testData/resolveWithStdlib/nullableTypeParameter.kt
JetBrains
3,432,266
false
null
fun test(set: Set<String?>) { val filtered = set.filterNotNull() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
70
kotlin
Apache License 2.0
templates/kotlin-webflux/subsystem/post/component/src/test/kotlin/{{PACKAGE_NAME}}/post/PostServiceTest.kt
cobaltinc
428,097,551
false
null
package {{PACKAGE_NAME}}.post import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.BDDMockito.given import org.mockito.InjectMocks import org.mockito.Mock import org.springframework.http.HttpStatus import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.web.server.ResponseStatusException import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.test.StepVerifier @ExtendWith(SpringExtension::class) internal class PostServiceTest { @Mock lateinit var postRepository: PostRepository @InjectMocks lateinit var postService: PostService @Test fun findAll() { val posts = MockData.posts given(this.postRepository.findAll()) .willReturn(Flux.fromIterable(posts)) StepVerifier.create(this.postService.findAll()) .expectNext(*posts.toTypedArray()) .verifyComplete() } @Test fun findByUserId() { val userId = 1 val posts = MockData.posts.filter { it.userId == userId } given(this.postRepository.findByUserId(userId)) .willReturn(Flux.fromIterable(posts)) StepVerifier.create(this.postService.findByUserId(1)) .expectNext(*posts.toTypedArray()) .verifyComplete() } @Test fun findById() { val post = MockData.posts[2] given(this.postRepository.findById(post.id)) .willReturn(Mono.just(post)) StepVerifier.create(this.postService.findById(post.id)) .expectNext(post) .verifyComplete() } @Test fun notFound() { given(this.postRepository.findById(5)) .willReturn(Mono.empty()) StepVerifier.create(this.postService.findById(5)) .expectError(ResponseStatusException::class.java) .verify() } }
0
null
2
6
74889f08089538c1a0df0783126cc76640e0e0de
1,764
bloom
MIT License
retromock/src/test/kotlin/co/infinum/retromock/RetromockTest.kt
infinum
151,698,084
false
{"Kotlin": 102506, "Java": 86454}
package co.infinum.retromock import co.infinum.retromock.helpers.* import co.infinum.retromock.meta.Mock import co.infinum.retromock.meta.MockResponse import co.infinum.retromock.meta.MockResponses import co.infinum.retromock.meta.MockSequential import okhttp3.ResponseBody import org.assertj.core.api.Java6Assertions.assertThat import org.assertj.core.api.Java6Assertions.entry import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.Mockito.* import retrofit2.Call import retrofit2.Retrofit import retrofit2.http.GET import java.nio.charset.StandardCharsets import java.util.concurrent.Executor import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger class RetromockTest { interface CallMethod { @GET("/") fun getResponseBody(): Call<ResponseBody> } interface MockedMethod { @Mock @GET("/") fun getResponseBody(): Call<ResponseBody> } interface ResponseMethod { @Mock @MockResponse(body = "Body example.") @GET("/") fun getResponseBody(): Call<ResponseBody> } interface ThreeResponsesMethod { @Mock @MockResponses( MockResponse(body = "Body example."), MockResponse(body = "Body example 2."), MockResponse(body = "Body example 3.") ) @MockSequential @GET("/") fun getResponseBody(): Call<ResponseBody> } interface ResponseMethodWithCustomBodyFactory { @Mock @MockResponse(body = "Body example.", bodyFactory = CountDownBodyFactory::class) @GET("/") fun getResponseBody(): Call<ResponseBody> } interface ThreeResponsesMethodWithCustomBodyFactory { @Mock @MockResponses( MockResponse(body = "Body example."), MockResponse(body = "Body example 2.", bodyFactory = PassThroughBodyFactory::class), MockResponse(body = "Body example 3.", bodyFactory = CountDownBodyFactory::class) ) @MockSequential @GET("/") fun getResponseBody(): Call<ResponseBody> } @Test fun objectMethodsStillWork() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() val obj = retromock.create(CallMethod::class.java) assertThat(obj.hashCode()).isNotZero() assertThat(obj == Any()).isFalse() assertThat(obj.toString()).isNotEmpty() } @Test fun cloneSharesStatefulInstances() { val bodyFactory = EmptyBodyFactory() val defaultBodyFactory = EmptyBodyFactory2() val defaultBehavior = mock<Behavior>() val backgroundExecutor = mock<ExecutorService>() val callbackExecutor = mock<Executor>() val first = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .addBodyFactory(bodyFactory) .defaultBodyFactory(defaultBodyFactory) .defaultBehavior(defaultBehavior) .backgroundExecutor(backgroundExecutor) .callbackExecutor(callbackExecutor) .build() val bodyFactory2 = EmptyBodyFactory2() val second = first.newBuilder() .addBodyFactory(bodyFactory2) .build() assertThat(first.bodyFactories().size).isEqualTo(second.bodyFactories().size - 1) assertThat(first.bodyFactories()).contains( entry(EmptyBodyFactory::class.java, bodyFactory) ) assertThat(second.bodyFactories()).contains( entry(EmptyBodyFactory::class.java, bodyFactory), entry(EmptyBodyFactory2::class.java, bodyFactory2) ) assertThat(first.defaultBodyFactory()).isSameAs(second.defaultBodyFactory()) assertThat(first.defaultBehavior()).isSameAs(second.defaultBehavior()) assertThat(first.callbackExecutor()).isSameAs(second.callbackExecutor()) assertThat(first.backgroundExecutor()).isSameAs(second.backgroundExecutor()) } @Test fun builtInFactoryAbsentInCloneBuilder() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.bodyFactories()).isNotEmpty assertThat(retromock.newBuilder().bodyFactories()).isEmpty() } @Test fun passThroughBodyFactoryAddedByDefault() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.bodyFactories().size).isEqualTo(1) assertThat(retromock.bodyFactories().get(PassThroughBodyFactory::class.java)).isNotNull() } @Test fun bodyFactoryNotCalledIfNoResponse() { val countDown = AtomicInteger(1) val factory = CountDownBodyFactory(countDown) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(MockedMethod::class.java) service.getResponseBody().execute() assertThat(countDown.get()).isEqualTo(1) } @Test fun annotationBodyPassedToBodyFactory() { val factory = mock<BodyFactory>() whenever(factory.create(anyString())).thenReturn(byteArrayOf().inputStream()) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethod::class.java) service.getResponseBody().execute() verify(factory).create("Body example.") } @Test fun bodyFactoryCalledExactlyOnce() { val countDown = AtomicInteger(1) val factory = CountDownBodyFactory(countDown) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethod::class.java) service.getResponseBody().execute() assertThat(countDown.get()).isEqualTo(0) } @Test fun bodyFactoryCalledTwice() { val countDown = AtomicInteger(2) val factory = CountDownBodyFactory(countDown) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethod::class.java) service.getResponseBody().execute() assertThat(countDown.get()).isEqualTo(1) service.getResponseBody().execute() assertThat(countDown.get()).isEqualTo(0) } @Test fun bodyFactoryCalledWithCorrectInput() { val factory = mock<BodyFactory>() whenever(factory.create(anyString())).then { (it.arguments[0] as String).byteInputStream(StandardCharsets.UTF_8) } val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ThreeResponsesMethod::class.java) service.getResponseBody().execute() verify(factory).create("Body example.") service.getResponseBody().execute() verify(factory).create("Body example 2.") service.getResponseBody().execute() verify(factory).create("Body example 3.") verifyNoMoreInteractions(factory) } @Test fun correctBodyFactoryCalled() { val countDown = AtomicInteger(1) val factory = CountDownBodyFactory(countDown) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .addBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethodWithCustomBodyFactory::class.java) service.getResponseBody().execute() assertThat(countDown.get()).isEqualTo(0) } @Test fun noMatchingBodyFactoryExceptionThrown() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethodWithCustomBodyFactory::class.java) assertThrows<IllegalStateException> { service.getResponseBody().execute() } } @Test fun defaultBodyFactoryCalledIfNotSpecified() { val factory = mock<BodyFactory>() whenever(factory.create(anyString())).thenReturn("".byteInputStream(StandardCharsets.UTF_8)) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .defaultBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ResponseMethod::class.java) service.getResponseBody().execute() verify(factory).create("Body example.") verifyNoMoreInteractions(factory) } @Test fun correctBodyFactoriesCalledInSequence() { val countDown = AtomicInteger(1) val factory = CountDownBodyFactory(countDown) val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .addBodyFactory(factory) .defaultBehavior(ImmediateBehavior()) .build() val service = retromock.create(ThreeResponsesMethodWithCustomBodyFactory::class.java) val response1 = service.getResponseBody().execute().body()!! assertThat(response1.string()).isEqualTo("Body example.") val response2 = service.getResponseBody().execute().body()!! assertThat(response2.string()).isEqualTo("Body example 2.") val response3 = service.getResponseBody().execute().body()!! assertThat(response3.string()).isEqualTo("Body example 3.") assertThat(countDown.get()).isEqualTo(0) } @Test fun builderInjectsPassThroughBodyFactory() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.bodyFactories()).containsKey(PassThroughBodyFactory::class.java) } @Test fun builderCreatesDefaultExecutorIfNotExplicitlySet() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.backgroundExecutor()).isNotNull() } @Test fun builderUsesExecutorIfExplicitlySet() { val backgroundExecutor = Executors.newSingleThreadExecutor() val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .backgroundExecutor(backgroundExecutor) .build() assertThat(retromock.backgroundExecutor()).isSameAs(backgroundExecutor) } @Test fun builderCreatesDefaultCallbackExecutorIfNotExplicitlySet() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.callbackExecutor()).isInstanceOf(Retromock.SyncExecutor::class.java) } @Test fun builderUsesCallbackExecutorIfExplicitlySet() { val callbackExecutor = Executors.newSingleThreadExecutor() val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .callbackExecutor(callbackExecutor) .build() assertThat(retromock.callbackExecutor()).isSameAs(callbackExecutor) } @Test fun builderUsesRetrofitCallbackExecutorIfNotExplicitlySetInRetromock() { val callbackExecutor = Executors.newSingleThreadExecutor() val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .callbackExecutor(callbackExecutor) .build()) .build() assertThat(retromock.callbackExecutor()).isSameAs(callbackExecutor) } @Test fun builderCreatesBehaviorIfNotExplicitlySet() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.defaultBehavior()).isSameAs(DefaultBehavior.INSTANCE) } @Test fun builderCreatesPassThroughBodyFactoryIfDefaultFactoryIsNotSet() { val retromock = Retromock.Builder() .retrofit(Retrofit.Builder() .baseUrl("http://infinum.co/") .build()) .build() assertThat(retromock.defaultBodyFactory()).isInstanceOf(PassThroughBodyFactory::class.java) } }
2
Kotlin
3
68
db6f5e0facb6c0e4116306a82c86c6836c826723
14,258
Retromock
Apache License 2.0
cocart/src/main/java/me/gilo/cocart/data/requests/CartRequest.kt
syedtehrimabbas
526,100,544
false
null
package me.gilo.cocart.data.requests import com.google.gson.annotations.SerializedName data class CartRequest( @SerializedName("id") var customerId: String? = null, @SerializedName("thumb") var thumb: Boolean? )
0
Kotlin
0
0
705c0d72a2df3ded12f55b7b9baeec85fe645555
230
dida-procop-android
MIT License
src/test/kotlin/com/mattmik/rapira/util/ResultTest.kt
rapira-book
519,693,099
true
{"Kotlin": 226030, "ANTLR": 7912}
package com.mattmik.rapira.util import com.mattmik.rapira.objects.shouldErrorWith import com.mattmik.rapira.objects.shouldSucceedWith import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import java.io.IOException class ResultTest : WordSpec({ "zip" should { "return success pair" { val value1 = "Hello" val value2 = "world" val successResult1 = Result.Success(value1) val successResult2 = Result.Success(value2) Result.zip(successResult1, successResult2) shouldSucceedWith Pair(value1, value2) } "return error" { val errorMessage = "Oops." val successResult = Result.Success("Hello, world!") val errorResult = Result.Error(errorMessage) Result.zip(successResult, errorResult) shouldErrorWith errorMessage Result.zip(errorResult, successResult) shouldErrorWith errorMessage Result.zip(errorResult, errorResult) shouldErrorWith errorMessage } } "map" should { val transformation: (Int) -> Int = { it * 2 } "transform success" { val successResult = Result.Success(10) successResult.map(transformation) shouldSucceedWith 20 } "not transform error" { val errorMessage = "Oops." val errorResult = Result.Error(errorMessage) errorResult.map(transformation) shouldErrorWith errorMessage } } "andThen" should { val transformation: (Int) -> Result<Int> = { Result.Success(it * 2) } "transform success" { val successResult = Result.Success(10) successResult.andThen(transformation) shouldSucceedWith 20 } "not transform error" { val errorMessage = "Oops." val errorResult = Result.Error(errorMessage) errorResult.andThen(transformation) shouldErrorWith errorMessage } } "getOrThrow" should { val buildException: (String) -> Exception = { IOException(it) } "return underlying value for success" { val value = "Hello, world!" val successResult = Result.Success(value) successResult.getOrThrow(buildException) shouldBe value } "throw exception for errors" { val errorMessage = "Oops." val errorResult = Result.Error(errorMessage) val throwable = shouldThrow<IOException> { errorResult.getOrThrow<Unit>(buildException) } throwable.message shouldBe errorMessage } } "toSuccess" should { "convert non-result to successful result" { val value = "Hello, world!" value.toSuccess() shouldSucceedWith value } } })
0
null
0
0
46f294e59c67747e1c00b5acf32b3cbe44281831
2,880
rapture
Apache License 2.0
app/src/main/java/com/smparkworld/hiltbinderexample/sample/supported/generic/nested/intoset/NestedGenericSetSampleModelImpl2.kt
Park-SM
502,595,266
false
{"Kotlin": 110957}
package com.smparkworld.hiltbinderexample.sample.supported.generic.nested.intoset import android.util.Log import com.smparkworld.hiltbinder.HiltSetBinds import com.smparkworld.hiltbinderexample.sample.supported.generic.nested.NestedGenericSampleModel import com.smparkworld.hiltbinderexample.sample.supported.generic.nested.SampleParam import javax.inject.Inject @HiltSetBinds class NestedGenericSetSampleModelImpl2 @Inject constructor( private val testString: String ) : NestedGenericSampleModel<SampleParam<SampleParam<String>>> { override fun printTest(test: SampleParam<SampleParam<String>>) { Log.d("Test!!", "TestString is `$testString` in NestedGenericSetSampleModelImpl2 class. :: $test") } }
1
Kotlin
0
5
7f68a2ec4b36bae86cfc103861107dbbff21891f
723
HiltBinder
Apache License 2.0
buildmetrics-mixpanel/src/main/java/com/nimroddayan/buildmetrics/plugin/BuildMetricsMixpanel.kt
Nimrodda
217,775,239
false
null
/* * Copyright 2019 <NAME> nimroddayan.com * * 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.nimroddayan.buildmetrics.plugin import com.nimroddayan.buildmetrics.plugin.Injection.moshi import com.nimroddayan.buildmetrics.plugin.Injection.retrofit import com.nimroddayan.buildmetrics.publisher.BuildFinishedEvent import com.nimroddayan.buildmetrics.publisher.BuildMetricsListener import com.nimroddayan.buildmetrics.publisher.Client import com.nimroddayan.buildmetrics.publisher.mixpanel.ANALYTICS_URL import com.nimroddayan.buildmetrics.publisher.mixpanel.MixpanelRestApi import mu.KotlinLogging import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property private val log = KotlinLogging.logger {} @Suppress("unused") class BuildMetricsMixpanelPlugin : Plugin<Project>, BuildMetricsListener { private lateinit var mixpanelRestApi: MixpanelRestApi override fun onClientCreated(client: Client) { log.debug { "Updating user profile with Mixpanel" } mixpanelRestApi.updateProfile(client) } override fun onBuildFinished(client: Client, event: BuildFinishedEvent) { log.debug { "Tracking event with Mixpanel" } mixpanelRestApi.trackBuildFinishedEvent(client, event) } @Suppress("UnstableApiUsage") override fun apply(project: Project) { log.debug { "Initializing Mixpanel Build Metrics plugin" } project.pluginManager.apply(BuildMetricsPlugin::class.java) val extension = project.extensions.create("mixpanel", BuildMetricsMixpanelAnalyticsExtension::class.java, project.objects) project.extensions.getByType(BuildMetricsExtensions::class.java).register(this) mixpanelRestApi = MixpanelRestApi(retrofit(ANALYTICS_URL.toHttpUrlOrNull()!!), moshi, extension.token) } } @Suppress("unused", "UnstableApiUsage") abstract class BuildMetricsMixpanelAnalyticsExtension(objectFactory: ObjectFactory) { val token: Property<String> = objectFactory.property(String::class.java) }
2
Kotlin
0
12
392cc022c82b16d12e42af8a970435257f9e74bc
2,664
buildmetrics-gradle-plugin
Apache License 2.0
platform/platform-impl/src/com/intellij/platform/ide/impl/presentationAssistant/KeymapKind.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. /** * @author nik */ package com.intellij.platform.ide.impl.presentationAssistant import com.intellij.ide.IdeBundle import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.ex.KeymapManagerEx import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import org.jetbrains.annotations.Nls internal class KeymapKind(val value: String, @Nls val displayName: String, @Nls val defaultLabel: String) { val keymap = KeymapManager.getInstance().getKeymap(value) val isMac = value.containsMacOS fun getAlternativeKind() = if (isMac) WIN else MAC companion object { val MAC = KeymapKind(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP, IdeBundle.message("presentation.assistant.configurable.keymap.mac"), IdeBundle.message("presentation.assistant.configurable.keymap.mac")) val WIN = KeymapKind(KeymapManager.DEFAULT_IDEA_KEYMAP, IdeBundle.message("presentation.assistant.configurable.keymap.win"), IdeBundle.message("presentation.assistant.configurable.keymap.win.label")); fun from(@NlsSafe value: String): KeymapKind = when(value) { KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP -> MAC KeymapManager.DEFAULT_IDEA_KEYMAP -> WIN else -> KeymapManagerEx.getInstanceEx().getKeymap(value)?.let { KeymapKind(value, it.presentableName, if (it.name.containsMacOS) IdeBundle.message("presentation.assistant.configurable.keymap.mac") else it.presentableName) } ?: KeymapKind(value, value, value) } fun defaultForOS() = when { SystemInfo.isMac -> MAC else -> WIN } } } private val String.containsMacOS: Boolean get() = contains("macOS") || contains("Mac OS") || contains("OSX")
249
null
5023
15,928
9ba394021dc73a3926f13d6d6cdf434f9ee7046d
1,947
intellij-community
Apache License 2.0
extensions/src/main/kotlin/ru/inforion/lab403/common/extensions/enums.kt
inforion
175,944,783
false
{"Kotlin": 551792, "Java": 1271}
package ru.inforion.lab403.common.extensions /** * Created by <NAME> on 02/03/17. */ inline fun <reified T : Enum<T>> find(predicate: (item: T) -> Boolean): T? = enumValues<T>().find { predicate(it) } inline fun <reified T : Enum<T>> first(predicate: (item: T) -> Boolean): T = enumValues<T>().first { predicate(it) } @Deprecated("Use enum() method") inline fun <reified T : Enum<T>> convert(ord: Int): T = enumValues<T>()[ord] inline fun <reified T: Enum<T>> Byte.enum(): T = int_z.enum() inline fun <reified T: Enum<T>> Short.enum(): T = int_z.enum() inline fun <reified T: Enum<T>> Int.enum(): T = enumValues<T>()[this] inline fun <reified T: Enum<T>> Long.enum(): T = int.enum() inline fun <reified T: Enum<T>> UByte.enum(): T = int_z.enum() inline fun <reified T: Enum<T>> UShort.enum(): T = int_z.enum() inline fun <reified T: Enum<T>> UInt.enum(): T = int.enum() inline fun <reified T: Enum<T>> ULong.enum(): T = int.enum()
1
Kotlin
1
1
e42ce78aa5d230025f197b044db4a698736d1630
937
kotlin-extensions
MIT License
app/src/main/java/com/nordkaz/ds24test/data/Repository.kt
ekbandroid
144,299,832
false
null
package com.nordkaz.ds24test.data import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.util.Log import com.nordkaz.ds24test.api.QuotesService import com.nordkaz.ds24test.api.DetailService import com.nordkaz.ds24test.api.getDetails import com.nordkaz.ds24test.api.searchQuotes import com.nordkaz.ds24test.db.LocalCache import com.nordkaz.ds24test.model.Detail import com.nordkaz.ds24test.model.DetailResult import com.nordkaz.ds24test.model.QuoteSearchResult import java.util.concurrent.Executors class QuoteRepository( private val service: QuotesService, private val serviceDetail: DetailService, private val cache: LocalCache ) { val NETWORK_PAGE_SIZE = 10 val QUOTES_REQUEST_DELAY_MS:Long = 200 var quotesOver = false private var lastItemCount = 1 private val networkErrors = MutableLiveData<String>() private var isRequestInProgress = false fun searchQuotes(): QuoteSearchResult { Log.d("QuoteSearchResult", "New query") lastItemCount = 1 requestAndSaveData() val data = cache.getQuotes() return QuoteSearchResult(data, networkErrors) } fun searchDetail(id: Int): DetailResult { Log.d("DetailResult", "New query") requestDetails(id) val data = cache.getDetail(id) return DetailResult(data, networkErrors) } fun requestMore(lastItemCount:Int) { this.lastItemCount = lastItemCount requestAndSaveData() } private fun requestAndSaveData() { if (isRequestInProgress) return isRequestInProgress = true searchQuotes(service, lastItemCount, NETWORK_PAGE_SIZE, { quotes -> if (quotes.size < NETWORK_PAGE_SIZE) quotesOver = true cache.insertQuoteList(quotes, { Executors.newSingleThreadExecutor().run { Thread.sleep(QUOTES_REQUEST_DELAY_MS) isRequestInProgress = false } }) }, { error -> networkErrors.postValue(error) Executors.newSingleThreadExecutor().run { Thread.sleep(QUOTES_REQUEST_DELAY_MS) isRequestInProgress = false } }) } private val liveData = MutableLiveData<List<Detail>>() fun getLiveData():LiveData<List<Detail>> { return liveData } fun requestDetails(id:Int) { isRequestInProgress = true getDetails(serviceDetail, id, { data -> cache.insertDetail(data.get(0), { isRequestInProgress = false }) }, { error -> networkErrors.postValue(error) isRequestInProgress = false }) } }
0
Kotlin
0
0
efef3a436d82b628db79a2071f9eaa4300d9a536
2,779
DS24Test
Apache License 2.0
app/src/main/kotlin/com/maltaisn/notes/model/PrefsManager.kt
maltaisn
258,858,109
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.maltaisn.notes.model import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit import androidx.preference.PreferenceManager import com.maltaisn.notes.OpenForTesting import com.maltaisn.notes.model.entity.NoteType import com.maltaisn.notes.sync.R import com.maltaisn.notes.ui.AppTheme import com.maltaisn.notes.ui.note.ShownDateField import com.maltaisn.notes.ui.note.SwipeAction import com.maltaisn.notes.ui.note.adapter.NoteListLayoutMode import org.jetbrains.annotations.TestOnly import javax.inject.Inject import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.time.Duration /** * Preference manager. This class interacts with [SharedPreferences] * so that other classes don't need knowledge of the keys and their associated type. */ @OpenForTesting class PrefsManager @Inject constructor( private val prefs: SharedPreferences ) { val theme: AppTheme by enumPreference(THEME, AppTheme.SYSTEM) val strikethroughChecked: Boolean by preference(STRIKETHROUGH_CHECKED, false) val moveCheckedToBottom: Boolean by preference(MOVE_CHECKED_TO_BOTTOM, false) var listLayoutMode: NoteListLayoutMode by enumPreference(LIST_LAYOUT_MODE, NoteListLayoutMode.LIST) val swipeAction: SwipeAction by enumPreference(SWIPE_ACTION, SwipeAction.ARCHIVE) val shownDateField: ShownDateField by enumPreference(SHOWN_DATE, ShownDateField.NONE) val maximumPreviewLabels: Int by preference(PREVIEW_LABELS, 0) var shouldAutoExport: Boolean by preference(AUTO_EXPORT, false) var autoExportUri: String by preference(AUTO_EXPORT_URI, "") var autoExportFailed: Boolean by preference(AUTO_EXPORT_FAILED, false) var lastAutoExportTime: Long by preference(LAST_AUTO_EXPORT_TIME, 0) var lastTrashReminderTime: Long by preference(LAST_TRASH_REMIND_TIME, 0) var lastRestrictedBatteryReminderTime: Long by preference(LAST_RESTRICTED_BATTERY_REMIND_TIME, 0) fun getMaximumPreviewLines(layoutMode: NoteListLayoutMode, noteType: NoteType): Int { val key = when (layoutMode) { NoteListLayoutMode.LIST -> when (noteType) { NoteType.TEXT -> PREVIEW_LINES_TEXT_LIST NoteType.LIST -> PREVIEW_LINES_LIST_LIST } NoteListLayoutMode.GRID -> when (noteType) { NoteType.TEXT -> PREVIEW_LINES_TEXT_GRID NoteType.LIST -> PREVIEW_LINES_LIST_GRID } } return prefs.getInt(key, 0) } fun setDefaults(context: Context) { for (prefsRes in PREFS_XML) { // since there are multiple preferences files, readAgain must be true, otherwise // the first call to setDefaultValues marks preferences as read, so subsequent calls // will have no effect (or that's what I presumed at least, since it didn't work). PreferenceManager.setDefaultValues(context, prefsRes, true) } } fun disableAutoExport() { shouldAutoExport = false lastAutoExportTime = 0 autoExportFailed = false autoExportUri = AUTO_EXPORT_NO_URI } @TestOnly fun clear(context: Context) { for (prefsRes in PREFS_XML) { PreferenceManager.getDefaultSharedPreferences(context).edit().clear().apply() } setDefaults(context) } private fun <T> preference(key: String, default: T) = object : ReadWriteProperty<PrefsManager, T> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: PrefsManager, property: KProperty<*>) = thisRef.prefs.all.getOrElse(key) { default } as T override fun setValue(thisRef: PrefsManager, property: KProperty<*>, value: T) { thisRef.prefs.edit { when (value) { is Boolean -> putBoolean(key, value) is Int -> putInt(key, value) is Long -> putLong(key, value) is String -> putString(key, value) else -> error("Unsupported preference type") } } } } private inline fun <reified T> enumPreference(key: String, default: T) where T : ValueEnum<*>, T : Enum<T> = object : ReadWriteProperty<PrefsManager, T> { override fun getValue(thisRef: PrefsManager, property: KProperty<*>): T { val value = thisRef.prefs.all.getOrElse(key) { default.value } return enumValues<T>().first { it.value == value } } override fun setValue(thisRef: PrefsManager, property: KProperty<*>, value: T) { prefs.edit { when (val v = value.value) { is Int -> putInt(key, v) is String -> putString(key, v) else -> error("Unsupported enum preference value type") } } } } companion object { // Settings keys const val THEME = "theme" const val PREVIEW_LABELS = "preview_labels" const val PREVIEW_LINES = "preview_lines" const val PREVIEW_LINES_TEXT_LIST = "preview_lines_text_list" const val PREVIEW_LINES_LIST_LIST = "preview_lines_list_list" const val PREVIEW_LINES_TEXT_GRID = "preview_lines_text_grid" const val PREVIEW_LINES_LIST_GRID = "preview_lines_list_grid" const val STRIKETHROUGH_CHECKED = "strikethrough_checked" const val MOVE_CHECKED_TO_BOTTOM = "move_checked_to_bottom" const val SHOWN_DATE = "shown_date" const val SWIPE_ACTION = "swipe_action" const val EXPORT_DATA = "export_data" const val AUTO_EXPORT = "auto_export" const val IMPORT_DATA = "import_data" const val CLEAR_DATA = "clear_data" const val VIEW_LICENSES = "view_licenses" const val VERSION = "version" // Other keys private const val AUTO_EXPORT_URI = "auto_export_uri" private const val LIST_LAYOUT_MODE = "is_in_list_layout" private const val LAST_TRASH_REMIND_TIME = "last_deleted_remind_time" private const val LAST_RESTRICTED_BATTERY_REMIND_TIME = "last_restricted_battery_remind_time" private const val LAST_AUTO_EXPORT_TIME = "last_auto_export_time" private const val AUTO_EXPORT_FAILED = "auto_export_failed" private val PREFS_XML = listOf( R.xml.prefs, R.xml.prefs_preview_lines, ) /** * Delay after which notes in trash are automatically deleted forever. */ val TRASH_AUTO_DELETE_DELAY = Duration.days(7) /** * Required delay before showing the trash reminder delay after user dismisses it. */ val TRASH_REMINDER_DELAY = Duration.days(60) /** * Required delay before showing a notice that restricted battery mode will impact * reminders, after user dismisses it. */ val RESTRICTED_BATTERY_REMINDER_DELAY = Duration.days(60) /** * Minimum delay between each automatic export. */ val AUTO_EXPORT_DELAY = Duration.days(1) val AUTO_EXPORT_NO_URI = "" } }
24
null
11
82
8b8e723fc8143ca2c18aa9d5d32acf36f5585861
7,914
another-notes-app
Apache License 2.0
tools/sisyphus-protoc/src/main/kotlin/com/bybutter/sisyphus/protobuf/compiler/OneofFieldDescriptor.kt
ButterCam
264,589,207
false
null
package com.bybutter.sisyphus.protobuf.compiler import com.bybutter.sisyphus.string.toCamelCase import com.bybutter.sisyphus.string.toPascalCase import com.google.protobuf.DescriptorProtos import com.squareup.kotlinpoet.ClassName class OneofFieldDescriptor( override val parent: MessageDescriptor, override val descriptor: DescriptorProtos.OneofDescriptorProto ) : DescriptorNode<DescriptorProtos.OneofDescriptorProto>() { fun oneOfClassName(): ClassName { return parent.className().nestedClass(oneOfName()) } fun oneOfName(): String { return descriptor.name.toPascalCase() } fun fieldName(): String { return descriptor.name.toCamelCase() } }
11
Kotlin
11
56
cc78b3e077dc0d02166794b83bfcd89ed70c396d
703
sisyphus
MIT License
app/src/test/java/gustavo/guterres/leite/tcc/BaseApplicationTest.kt
gustavoleite
187,483,847
false
null
package gustavo.guterres.leite.tcc import android.app.Application class BaseApplicationTest : Application()
0
Kotlin
0
0
1f8a26b3a3ebdc03a22e603b05c2697cd955021f
109
tcc
MIT License
src/main/kotlin/com/ruleoftech/vehicledata/api/StatisticsResource.kt
walokra
121,860,621
false
null
package com.ruleoftech.vehicledata import com.github.kittinunf.result.map import com.ruleoftech.exp.ajotektiedot.service.StatisticsService import org.slf4j.LoggerFactory import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Rest Endpoint for getting data. */ @RestController() @RequestMapping("/v1/statistics") class StatisticsResource internal constructor( val service: StatisticsService) { private val log = LoggerFactory.getLogger(StatisticsResource::class.java) @GetMapping("/total") fun countModel( @RequestParam(required = false, defaultValue = "0") model: String ): ResponseEntity<Long> { log.debug( "{'method':'findByModel', 'params':{'model'='{}'}", model) return service.countByModel(model) .map { ResponseEntity.ok(it) } .get() } }
0
Kotlin
0
0
9b1e918b4c62d439346447c9300480232f10cbe2
1,074
ajoneuvotiedot-ws
MIT License
src/main/kotlin/org/arend/ui/ArendDialog.kt
JetBrains
96,068,447
false
{"Kotlin": 2655823, "Lex": 16187, "Java": 5894, "HTML": 2144, "CSS": 1108, "JavaScript": 713}
package org.arend.ui import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.ScrollPaneFactory import org.arend.ui.impl.session.LabeledComponent import javax.swing.JComponent import javax.swing.JLabel class ArendDialog(project: Project, title: String?, private val description: String?, private val component: JComponent?, private val focused: JComponent? = component) : DialogWrapper(project, true) { init { if (title != null) { setTitle(title) } init() } override fun createNorthPanel() = description?.let { JLabel(it) } override fun createCenterPanel() = component?.let { ScrollPaneFactory.createScrollPane(it, true) } override fun getPreferredFocusedComponent() = focused }
36
Kotlin
12
90
7a6608a2e44369e11c5baad3ef2928d6f9c971b2
794
intellij-arend
Apache License 2.0
pulsar-skeleton/src/main/kotlin/ai/platon/pulsar/crawl/fetch/FetchThread.kt
kflyddn
248,429,389
true
{"Java": 9480239, "HTML": 2583850, "Kotlin": 1030345, "Shell": 68406, "JavaScript": 50211, "PLSQL": 10825, "TSQL": 7164, "CSS": 4671, "Rich Text Format": 2235}
package ai.platon.pulsar.crawl.fetch import ai.platon.pulsar.common.ReducerContext import ai.platon.pulsar.common.StringUtil import ai.platon.pulsar.common.Urls import ai.platon.pulsar.common.config.CapabilityTypes.FETCH_MODE import ai.platon.pulsar.common.config.ImmutableConfig import ai.platon.pulsar.crawl.component.FetchComponent import ai.platon.pulsar.crawl.data.PoolId import ai.platon.pulsar.persist.WebPage import ai.platon.pulsar.persist.gora.generated.GWebPage import ai.platon.pulsar.persist.metadata.FetchMode import org.apache.hadoop.io.IntWritable import java.io.IOException import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** * This class picks items from queues and fetches the pages. */ class FetchThread( private val fetchComponent: FetchComponent, private val fetchMonitor: FetchMonitor, private val taskScheduler: TaskScheduler, immutableConfig: ImmutableConfig, private val context: ReducerContext<IntWritable, out IFetchEntry, String, GWebPage> ): Thread(), Comparable<FetchThread> { private val LOG = FetchMonitor.LOG private val id: Int /** * Native, Crowdsourcing, Proxy */ private val fetchMode: FetchMode /** * Fix the thread to a specified queue as possible as we can */ private val currPriority = -1 private var currQueueId: PoolId? = null private val halted = AtomicBoolean(false) private val servedHosts = TreeSet<PoolId>() private var taskCount = 0 val isHalted: Boolean get() = halted.get() init { this.id = instanceSequence.incrementAndGet() this.isDaemon = true this.name = javaClass.simpleName + "-" + id this.fetchMode = immutableConfig.getEnum(FETCH_MODE, FetchMode.NATIVE) } fun halt() { halted.set(true) } fun exitAndJoin() { halted.set(true) try { join() } catch (e: InterruptedException) { LOG.error(e.toString()) } } override fun run() { fetchMonitor.registerFetchThread(this) var task: FetchTask? = null try { while (!fetchMonitor.isMissionComplete && !isHalted) { task = schedule() if (task == null) { sleepAndRecord() continue } val page = fetchOne(task) write(page.key, page) ++taskCount } // while } catch (e: Throwable) { LOG.error("Unexpected throwable : " + StringUtil.stringifyException(e)) } finally { if (task != null) { taskScheduler.finishUnchecked(task) } fetchMonitor.unregisterFetchThread(this) LOG.info("Thread #{} finished", getId()) } } fun report() { if (servedHosts.isEmpty()) { return } val report = StringBuilder() report.appendln(String.format("Thread #%d served %d tasks for %d hosts : \n", getId(), taskCount, servedHosts.size)) servedHosts.map { Urls.reverseHost(it.url) }.sorted().map { Urls.unreverseHost(it) } .joinTo(report, "\n") { String.format("%1$40s", it) } report.appendln() LOG.info(report.toString()) } private fun sleepAndRecord() { fetchMonitor.registerIdleThread(this) try { sleep(1000) } catch (ignored: InterruptedException) {} fetchMonitor.unregisterIdleThread(this) } private fun schedule(): FetchTask? { var fetchTask: FetchTask? = null if (fetchMode == FetchMode.CROWDSOURCING) { val response = taskScheduler.pollFetchResult() if (response != null) { val url = Urls.getURLOrNull(response.queueId) if (url != null) { fetchTask = taskScheduler.tasksMonitor.findPendingTask(response.priority, url, response.itemId) } if (fetchTask == null) { LOG.warn("Bad fetch item id {}-{}", response.queueId, response.itemId) } } } else { fetchTask = if (currQueueId == null) { taskScheduler.schedule() } else { taskScheduler.schedule(currQueueId) } if (fetchTask != null) { // the next time, we fetch items from the same queue as this time currQueueId = PoolId(fetchTask.priority, fetchTask.protocol, fetchTask.host) servedHosts.add(currQueueId!!) } else { // The current queue is empty, fetch item from top queue the next time currQueueId = null } } return fetchTask } private fun fetchOne(task: FetchTask): WebPage { val page = fetchComponent.fetchContent(task.page) val queueId = PoolId(task.priority, task.protocol, task.host) taskScheduler.finish(queueId, task.itemId) return page } private fun write(key: String, page: WebPage) { try { // the page is fetched and status are updated, write to the file system context.write(key, page.unbox()) } catch (e: IOException) { LOG.error("Failed to write to hdfs - {}", StringUtil.stringifyException(e)) } catch (e: InterruptedException) { LOG.error("Interrupted - {}", StringUtil.stringifyException(e)) } catch (e: Throwable) { LOG.error(StringUtil.stringifyException(e)) } } override fun compareTo(other: FetchThread): Int { return id - other.id } companion object { private val instanceSequence = AtomicInteger(0) } }
0
null
0
0
728a9c6dbe852edd686c55b234608abe7e9fb419
5,892
pulsar
Apache License 2.0
app/src/main/java/com/mohit/newsdo/util/swipeDetector/SwipeGestureDetector.kt
MohitGupta121
482,321,677
false
{"Kotlin": 67515}
package com.mohit.newsdo.util.swipeDetector import android.view.GestureDetector import android.view.MotionEvent class SwipeGestureDetector(private val swipeActions: SwipeActions) : GestureDetector.OnGestureListener { private val MIN_X_SWIPE_DISTANCE = 180 private val MIN_Y_SWIPE_DISTANCE = 180 override fun onDown(e: MotionEvent): Boolean { return false } override fun onShowPress(e: MotionEvent) {} override fun onSingleTapUp(e: MotionEvent): Boolean { return false } override fun onScroll( e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float ): Boolean { return false } override fun onLongPress(e: MotionEvent) {} override fun onFling( e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { //TypeCast the difference of co-ordinates to int and store in another variable val distanceSwipedInX = (e1.x - e2.x).toInt() val distanceSwipedInY = (e1.y - e2.y).toInt() // Make Check For Horizontal Swipe if (Math.abs(distanceSwipedInX) > MIN_X_SWIPE_DISTANCE) { // Now Check Which Side Swipe Happened if (distanceSwipedInX > 0) { swipeActions.onSwipeLeft() } return true } // Make Check For Horizontal Swipe if (Math.abs(distanceSwipedInY) > MIN_Y_SWIPE_DISTANCE) { // Now Check Which Side Swipe Happened if (distanceSwipedInY > 0) { swipeActions.onSwipeUp() } else { swipeActions.onSwipeDown() } } return false } }
0
Kotlin
1
3
27537923e0c0fe081163883a1c6616baccee9d58
1,740
NewsDo
Apache License 2.0
harmonysoft-jackson/src/main/kotlin/tech/harmonysoft/oss/jackson/JacksonJsonApi.kt
harmonysoft-tech
517,062,754
false
{"Kotlin": 629287, "Gherkin": 24382, "Shell": 517, "JavaScript": 378}
package tech.harmonysoft.oss.jackson import java.io.ByteArrayOutputStream import jakarta.inject.Named import tech.harmonysoft.oss.json.JsonApi import kotlin.reflect.KClass @Named class JacksonJsonApi( private val mappers: HarmonysoftJacksonMappers ) : JsonApi { override fun <T : Any> parse(content: String, resultClass: KClass<T>): T { return mappers.json.readValue(content, resultClass.java) } override fun writeJson(json: Any): String { val bOut = ByteArrayOutputStream() bOut.writer().use { mappers.json.writeValue(it, json) } return bOut.toString() } }
1
Kotlin
1
2
92ba63acceb9cac96dcde898ea2bd220410c07fa
633
harmonysoft-kotlin-libs
MIT License
app/src/main/java/org/matomocamp/companion/parsers/Parser.kt
MatomoCamp
407,812,766
true
{"Kotlin": 314930}
package org.matomocamp.companion.parsers import okio.BufferedSource interface Parser<out T> { @Throws(Exception::class) fun parse(source: BufferedSource): T }
0
Kotlin
0
0
38556e607435d1ed8b487a684c7711b56a2e9247
168
matomocamp-companion-android
Apache License 2.0
tmp/arrays/youTrackTests/8025.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-13687 sealed class Shape { object Circle : Shape() object Triangle : Shape() object Rectangle : Shape() object Pentagon : Shape() companion object { val shapes = listOf(Circle, Triangle, Rectangle, Pentagon) fun test() { println(shapes.joinToString()) } } } fun main(args: Array<String>) { Shape.test() }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
405
bbfgradle
Apache License 2.0
magellanx-core/src/test/java/com/ryanmoelter/magellanx/core/coroutines/ShownLifecycleScopeTest.kt
ryanmoelter
119,760,054
true
{"Kotlin": 78473}
package com.ryanmoelter.magellanx.core.coroutines import com.ryanmoelter.magellanx.core.lifecycle.LifecycleState.Created import com.ryanmoelter.magellanx.core.lifecycle.LifecycleState.Destroyed import com.ryanmoelter.magellanx.core.lifecycle.LifecycleState.Resumed import com.ryanmoelter.magellanx.core.lifecycle.LifecycleState.Shown import com.ryanmoelter.magellanx.core.lifecycle.transition import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.string.shouldContain import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class, InternalCoroutinesApi::class) internal class ShownLifecycleScopeTest { private lateinit var shownScope: ShownLifecycleScope @Before fun setUp() { shownScope = ShownLifecycleScope() } @Test fun cancelBeforeCreated() { runTest { shownScope.transition(Destroyed, Created) val async = shownScope.async(Dispatchers.Default) { delay(5000) } async.isCancelled.shouldBeTrue() async.getCancellationException().message shouldContain "Not shown yet" shownScope.transition(Created, Resumed) async.isCancelled.shouldBeTrue() shownScope.transition(Resumed, Created) async.isCancelled.shouldBeTrue() async.getCancellationException().message shouldContain "Not shown yet" } } @Test fun cancelAfterShown() { runTest { shownScope.transition(Destroyed, Shown) val async = shownScope.async(Dispatchers.Default) { delay(5000) } async.isCancelled.shouldBeFalse() shownScope.transition(Shown, Resumed) async.isCancelled.shouldBeFalse() shownScope.transition(Resumed, Created) async.isCancelled.shouldBeTrue() async.getCancellationException().message shouldContain "Hidden" } } @Test fun cancelMultipleAfterShown() { runTest { shownScope.transition(Destroyed, Shown) val async = shownScope.async(Dispatchers.Default) { delay(5000) } val async2 = shownScope.async(Dispatchers.Default) { delay(5000) } async.isCancelled.shouldBeFalse() async2.isCancelled.shouldBeFalse() shownScope.transition(Shown, Resumed) async.isCancelled.shouldBeFalse() async2.isCancelled.shouldBeFalse() shownScope.transition(Resumed, Created) async.isCancelled.shouldBeTrue() async.getCancellationException().message shouldContain "Hidden" async2.isCancelled.shouldBeTrue() async2.getCancellationException().message shouldContain "Hidden" } } @Test fun cancelAfterResumed() { runTest { shownScope.transition(Destroyed, Resumed) val async = shownScope.async(Dispatchers.Default) { delay(5000) } async.isCancelled.shouldBeFalse() shownScope.transition(Resumed, Created) async.isCancelled.shouldBeTrue() async.getCancellationException().message shouldContain "Hidden" } } }
3
Kotlin
0
1
05667839f9acc95756addcffe57f3c967bad6f29
3,194
magellanx
Apache License 2.0
src/test/kotlin/tech/relaycorp/relaynet/cogrpc/test/NoopStreamObserver.kt
relaycorp
171,719,072
false
{"Kotlin": 33391}
package tech.relaycorp.relaynet.cogrpc.test import io.grpc.stub.StreamObserver open class NoopStreamObserver<V> : StreamObserver<V> { override fun onNext(value: V) {} override fun onError(t: Throwable) {} override fun onCompleted() {} }
8
Kotlin
0
0
6f13a554994810ddadf4e82cc1f093cb4de7f43b
251
awala-cogrpc-jvm
Apache License 2.0
src/main/kotlin/no/nav/pensjon/simulator/generelt/Person.kt
navikt
753,551,695
false
{"Kotlin": 1687999, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.generelt import no.nav.pensjon.simulator.core.domain.regler.enum.LandkodeEnum import java.time.LocalDate data class Person( val foedselDato: LocalDate, val statsborgerskap: LandkodeEnum )
1
Kotlin
0
0
1f7f146757ea054e29a6d82aa656cb21c9c61961
231
pensjonssimulator
MIT License
actions/src/commands/BisectCommand.kt
hubvd
388,790,188
false
{"Kotlin": 215472, "Python": 20471, "Shell": 7064, "JavaScript": 1219}
package com.github.hubvd.odootools.actions.commands import com.github.ajalt.clikt.core.Abort import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.terminal import com.github.ajalt.mordant.rendering.TextColors.* import com.github.ajalt.mordant.rendering.TextStyles.bold import com.github.hubvd.odootools.actions.utils.* import com.github.hubvd.odootools.workspace.Workspace import com.github.hubvd.odootools.workspace.Workspaces import kotlin.math.roundToInt private data class BisectState( val low: Int, val mid: Int, val high: Int, val batch: ResolvedBatch, val batches: List<ResolvedBatch>, val workspace: Workspace, ) { companion object { operator fun invoke(low: Int, high: Int, batches: List<ResolvedBatch>, workspace: Workspace): BisectState { val mid = (low + high).ushr(1) return BisectState(low, mid, high, batches[mid], batches, workspace) } } } class BisectCommand( private val runbot: Runbot, private val workspaces: Workspaces, private val git: Git, ) : CliktCommand( help = "Bisect odoo across multiple repositories", ) { private lateinit var odooRepository: Repository private lateinit var enterpriseRepository: Repository private lateinit var state: BisectState override fun run() { val workspace = workspaces.current() ?: throw Abort() val steps = runbot.batches(workspace.base) this.state = BisectState(low = 0, high = steps.lastIndex, steps, workspace) with(git) { odooRepository = workspace.odoo() enterpriseRepository = workspace.enterprise() } draw() while (state.low <= state.high) { var (low, mid, high) = state while (true) { when (terminal.readLineOrNull(hideInput = false)) { "good" -> { high = mid - 1 break } "bad" -> { low = mid + 1 break } null -> { terminal.println() throw Abort() } else -> { terminal.cursor.move { up(1) clearLineAfterCursor() } terminal.print(prompt) } } } if (high == -1) { TODO("Every commit is good") } if (low == high) { break } state = BisectState(low = low, high = high, batches = steps, workspace = workspace) draw() } terminal.cursor.move { up(3) startOfLine() clearLineAfterCursor() clearScreenAfterCursor() } val firstGood = steps[state.high + 1] val firstBad = steps[state.high] // TODO: bisect individual commits terminal.print( buildString { appendLine((bold + green)("Possibly bad odoo commits:")) odooRepository.commitsBetween(firstGood.odoo, firstBad.odoo) .forEach { append(yellow(it.hash)) append(' ') appendLine(it.title) } appendLine() appendLine((bold + green)("Possibly bad enterprise commits:")) enterpriseRepository.commitsBetween(firstGood.enterprise, firstBad.enterprise) .forEach { append(yellow(it.hash)) append(' ') appendLine(it.title) } }, ) } var first = true private val prompt by lazy { terminal.theme.style("prompt.default")("good | bad ? ") } private fun draw() { val odooTitle = odooRepository.commitTitle(state.batch.odoo) val enterpriseTitle = enterpriseRepository.commitTitle(state.batch.enterprise) val width = terminal.info.width val total = state.batches.size val ratio = (total.toDouble()) / width // FIXME: rounding val start = (state.low / ratio).roundToInt() val middle = ((state.high - state.low) / ratio).roundToInt() val end = (width - (start + middle)) assert(start + middle + end == width) if (!first) { terminal.cursor.move { up(4) clearScreenAfterCursor() } } terminal.print( buildString { append((black on yellow)("odoo")) append(' ') append(yellow(state.batch.odoo)) append(' ') append(odooTitle) appendLine() append((black on yellow)("enterprise")) append(' ') append(yellow(state.batch.enterprise)) append(' ') append(enterpriseTitle) appendLine() append(terminal.theme.style("danger")(String(CharArray(start) { '━' }))) append(terminal.theme.style("muted")(String(CharArray(middle) { '━' }))) append(terminal.theme.style("success")(String(CharArray(end) { '━' }))) appendLine() append(magenta("Switching branches..")) }, ) odooRepository.switch(state.batch.odoo) enterpriseRepository.switch(state.batch.enterprise) terminal.cursor.move { clearLineBeforeCursor() startOfLine() } terminal.print(prompt) first = false } }
0
Kotlin
5
4
ff752f3ae94cb01f027f7cb556c59051211af4bf
5,874
odoo-tools
MIT License
app/src/main/java/com/zj/example/dagger2/example3/module/Example3OkHttpModule.kt
zhengjiong
106,264,089
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 128, "XML": 20, "Java": 6}
package com.zj.example.dagger2.example3.module import com.zj.example.dagger2.MainActivity import com.zj.example.dagger2.example3.Example3Activity import com.zj.example.dagger2.example3.bean.Dog import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import java.util.concurrent.TimeUnit /** * * CreateTime: 17/10/10 18:04 * @author 郑炯 */ @Module class Example3OkHttpModule() { @Provides fun provideDog(): Dog = Dog("金金") @Provides fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .readTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build() } @Provides fun provideRetrofit(client: OkHttpClient): Retrofit { return Retrofit.Builder() .client(client) .baseUrl("http://www.baidu.com") .build() } }
0
Kotlin
0
0
3cfd16bbbd540a7f8f8b6bf7956d5db3d57a78c4
935
ZJ_Dagger2Example
MIT License
openai/src/main/kotlin/herbaccara/openai/model/completion/TextCompletion.kt
herbaccara
611,054,860
false
null
package herbaccara.openai.model.completion import com.fasterxml.jackson.annotation.JsonProperty data class TextCompletion( val id: String, @field:JsonProperty("object") val `object`: String, val created: Int, val choices: List<CompletionChoice>, val model: String )
1
Kotlin
1
2
7a3558a5e771d9ce5b8c1bf0cf44ade310471c85
292
openai
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DiscreteWaveletData.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: DiscreteWaveletData * * Full name: System`DiscreteWaveletData * * DiscreteWaveletData[{wind  coef , …}, wave, wtrans] yields a discrete wavelet data object with wavelet coefficients coef corresponding to wavelet index wind , wavelet wave, and wavelet transform wtrans. * 1 1 i i * DiscreteWaveletData[{wind  coef , …}, wave, wtrans, {d , …}] yields a discrete wavelet data object assuming data dimensions {d , …}. * Usage: 1 1 1 1 * * Method -> Automatic * Padding -> Periodic * SampleRate -> Automatic * Options: WorkingPrecision -> MachinePrecision * * Protected * Attributes: ReadProtected * * local: paclet:ref/DiscreteWaveletData * Documentation: web: http://reference.wolfram.com/language/ref/DiscreteWaveletData.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun discreteWaveletData(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("DiscreteWaveletData", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,825
mathemagika
Apache License 2.0
app/src/main/java/com/example/flixster1/MainActivity.kt
trinhqale
611,503,260
false
null
package com.example.flixster1 import android.bluetooth.BluetoothStatusCodes import android.graphics.Color import android.graphics.drawable.ColorDrawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.flixster1.R.id import android.util.Log import com.codepath.asynchttpclient.AsyncHttpClient import com.codepath.asynchttpclient.RequestParams import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler import okhttp3.Headers class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val actionBar = supportActionBar if (actionBar != null) { actionBar.setTitle("Flixster") actionBar.setDisplayShowHomeEnabled(true) // actionBar.setLogo(R.drawable.flixster_icon) actionBar.setLogo(R.mipmap.ic_launcher) actionBar.setDisplayUseLogoEnabled(true) } supportActionBar!!.setBackgroundDrawable(ColorDrawable(Color.parseColor("#054504"))) val supportFragmentManager = supportFragmentManager val fragmentTransaction =supportFragmentManager.beginTransaction() fragmentTransaction.replace(id.content, MovieFragment(), null).commit() } }
1
Kotlin
0
0
930cc22e64af98643cd01cca7e8ccb09d8834f3e
1,333
Flixster1
Apache License 2.0
src/main/kotlin/csense/idea/kotlin/assistance/inspections/NamedArgsPositionMismatch.kt
csense-oss
201,449,298
false
null
package csense.idea.kotlin.assistance.inspections import com.intellij.codeHighlighting.* import com.intellij.codeInspection.* import com.intellij.psi.* import csense.idea.base.bll.* import csense.idea.base.bll.kotlin.* import csense.idea.kotlin.assistance.* import csense.idea.kotlin.assistance.suppression.* import org.jetbrains.kotlin.idea.caches.resolve.* import org.jetbrains.kotlin.idea.inspections.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.annotations.* import org.jetbrains.kotlin.types.* class NamedArgsPositionMismatch : AbstractKotlinInspection() { override fun getDisplayName(): String { return "Mismatched naming for parameter names" } override fun getStaticDescription(): String { //the ctrl + f1 box + desc of the inspection. return """ This inspection tells whenever a used name (such as a variable) is passed to / or from a function where that name is also used but at a different location. This generally is an error, such as swapping arguments around or parameter names for that matter. """.trimIndent() } override fun getDescriptionFileName(): String { return "more desc ? " } override fun getShortName(): String { return "NamedArgsPositionMismatch" } override fun getGroupDisplayName(): String { return Constants.InspectionGroupName } override fun isEnabledByDefault(): Boolean { return true } override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction> { return arrayOf( KtExpressionSuppression("Suppress naming mismatch issue", groupDisplayName, shortName) ) } override fun getDefaultLevel(): HighlightDisplayLevel { return HighlightDisplayLevel.ERROR } override fun buildVisitor( holder: ProblemsHolder, isOnTheFly: Boolean ): KtVisitorVoid { return callExpressionVisitor { val call: KtCallExpression = it if (call.valueArguments.isEmpty()) { //no arguments to check return@callExpressionVisitor } val callingFunction = call.resolveToCall()?.resultingDescriptor ?: return@callExpressionVisitor val usedNames = call.findInvocationArgumentNamesNew() val originalParameterNames = callingFunction.findOriginalMethodArgumentNames() val argumentNames = call.findArgumentNames() if (usedNames.size > originalParameterNames.size) { //invalid code, just skip. (invoking with more args than there is). return@callExpressionVisitor } val misMatches = computeMismatchingNames(usedNames, originalParameterNames, argumentNames) if (misMatches.isNotEmpty()) { reportProblem(call, misMatches, holder) } call.lambdaArguments.forEach { lambdaArg -> val argName = lambdaArg.getLambdaExpression() ?: return@forEach val usedLambdaArgumentNames = argName.valueParameters.map { parameters -> ArgumentName(parameters.name ?: "", listOf()) } val namedArgs = callingFunction.valueParameters[0].type.arguments.map { typeArgs -> typeArgs.type.findLambdaParameterName() } val lambdaMisMatch = computeMismatchingNames(usedLambdaArgumentNames, namedArgs, argumentNames) if (lambdaMisMatch.isNotEmpty()) { reportLambdaProblem(call, lambdaMisMatch, holder) } } } } fun reportProblem(atElement: KtCallExpression, mismatches: List<MismatchedName>, holder: ProblemsHolder) { mismatches.forEach { val arg = atElement.valueArguments.getOrNull(it.parameterIndex) val argName = arg?.getArgumentName()?.text when { argName == null -> { val text = "`${it.name}` should be at index ${it.shouldBeAtIndex}, but is at ${it.parameterIndex}" holder.registerProblemSafe(arg ?: atElement, text) } argName != it.name -> { val text = "`${it.name}` matches another argument (not same named argument)" holder.registerProblemSafe(arg, text) } } } } fun reportLambdaProblem(atElement: PsiElement, mismatches: List<MismatchedName>, holder: ProblemsHolder) { val names = mismatches.distinctBy { it.name }.joinToString(",") { "\"${it.name}\" - should be at position ${it.shouldBeAtIndex}" } holder.registerProblemSafe( atElement, "You have mismatched arguments names \n($names)" ) } fun computeMismatchingNames( usedNames: List<ArgumentName?>, originalParameterNames: List<String?>, argumentName: List<String?> ): List<MismatchedName> { val originalNames = originalParameterNames.filterNotNull().toSet() val result = mutableListOf<MismatchedName>() usedNames.forEachIndexed { index, name -> if (name == null || !originalNames.contains(name.resultingName)) { return@forEachIndexed } //only look at those who are contained. val org = originalParameterNames.getOrNull(index) if (org == null || !org.areEqualOrCamelCaseEqual(name)) { //ERROR !! mismatching name but is declared somewhere else. result.add( MismatchedName( name.resultingName, index, originalParameterNames.indexOf(name.resultingName) ) ) } else { val argName = argumentName.getOrNull(index) if (argName != null && argName != name.resultingName) { //todo improve... result.add( MismatchedName( name.resultingName, index, originalParameterNames.indexOf(name.resultingName) ) ) } } } return result } fun String.areEqualOrCamelCaseEqual(argumentName: ArgumentName): Boolean { val isResultingNameEquals = this == argumentName.resultingName if (isResultingNameEquals) { return true } val asString = argumentName.nameParts.joinToString("") return asString.endsWith(this, ignoreCase = true) } } data class MismatchedName(val name: String, val parameterIndex: Int, val shouldBeAtIndex: Int) fun KotlinType.findLambdaParameterName(): String? { return annotations.findAnnotation( Constants.lambdaParameterNameAnnotationFqName )?.argumentValue("name")?.value as? String } /** * Find all argument names in order they are declared. * @receiver KtCallExpression * @return List<String?> */ fun KtCallExpression.findInvocationArgumentNamesNew(): List<ArgumentName?> { return valueArguments.map { it: KtValueArgument? -> it?.getArgumentExpression()?.resolvePotentialArgumentName(listOf()) } } /** * Used to try and find a potential name for a given argument. * @receiver KtExpression * @return String? */ tailrec fun KtExpression.resolvePotentialArgumentName(nameParts: List<String>): ArgumentName? = when (this) { is KtNameReferenceExpression -> ArgumentName(getReferencedName(), nameParts + listOf(getReferencedName())) is KtDotQualifiedExpression -> { (selectorExpression ?: receiverExpression).resolvePotentialArgumentName( nameParts + listOfNotNull(receiverExpression.text) ) } is KtCallExpression -> { calleeExpression?.resolvePotentialArgumentName(nameParts) } else -> null } data class ArgumentName(val resultingName: String, val nameParts: List<String>)
0
Kotlin
0
0
da6b583c4618ffd5a803ebab42661a6aac37ada5
8,165
idea-kotlin-assistance
MIT License
idea/tests/testData/copyPaste/imports/ClassObjectAndDropImports.expected.kt
JetBrains
278,369,660
false
null
// ERROR: Unresolved reference: B // ERROR: Unresolved reference: B // ERROR: Unresolved reference: B // ERROR: A 'return' expression required in a function with a block body ('{...}') package to import a.A import a.T import java.util.* import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicLong as ALong fun g(t: T): Int { g(A) B.f() A B A.Companion B.Companion }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
428
intellij-kotlin
Apache License 2.0
src/test/java/com/tngtech/jgiven/LibraryTestUtil.kt
TNG
89,510,876
false
null
package com.tngtech.jgiven import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess import com.intellij.testFramework.PsiTestUtil import com.tngtech.jgiven.annotation.ScenarioState import java.io.File class LibraryTestUtil constructor(private val myModule: Module) { private val references = ArrayList<Ref<Library>>() private fun addJarContaining(clazz: Class<*>): LibraryTestUtil { val path = getJarPath(clazz) addLibraryAt(path) return this } private fun getJarPath(clazz: Class<*>): String { val className = clazz.name.replace('.', '/') + ".class" val classPath = clazz.classLoader.getResource(className)?.toString() ?: throw IllegalArgumentException("Class $clazz not found") return if (classPath.startsWith("jar")) { classPath.substringAfter("jar:file:").substringBefore('!') } else { throw IllegalArgumentException("Class $clazz is not in a jar file") } } fun addJGiven(): LibraryTestUtil { try { return addJarContaining(ScenarioState::class.java) }catch(e: IllegalArgumentException){ throw IllegalArgumentException("JGiven jar not found. Please add it to the classpath") } } private fun addLibraryAt(path: String) { val parts = path.split("/".toRegex()).filterNot { it.isEmpty() }.toTypedArray() val file = File(path) VfsRootAccess.allowRootAccess(myModule, parts[0]) val fileName = file.name ModuleRootModificationUtil.updateModel(myModule) { model -> references.add(Ref.create(PsiTestUtil.addLibrary( model, fileName, file.parent, fileName ))) } } internal fun removeLibraries() { WriteCommandAction.runWriteCommandAction(null) { val table = LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.project) val model = table.modifiableModel references.forEach { reference -> model.removeLibrary(reference.get()) } model.commit() } } }
5
null
1
13
f0440e7e9c49362a4a88194b7c8e9f89c4535b6a
2,426
jgiven-intellij-plugin
Apache License 2.0
app/src/main/java/com/kickstarter/viewmodels/BackingFragmentViewModel.kt
kickstarter
76,278,501
false
null
package com.kickstarter.viewmodels import android.util.Pair import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.kickstarter.R import com.kickstarter.libs.Either import com.kickstarter.libs.Environment import com.kickstarter.libs.KSString import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair import com.kickstarter.libs.rx.transformers.Transformers.neverErrorV2 import com.kickstarter.libs.rx.transformers.Transformers.takePairWhenV2 import com.kickstarter.libs.utils.DateTimeUtils import com.kickstarter.libs.utils.NumberUtils import com.kickstarter.libs.utils.ProjectViewUtils import com.kickstarter.libs.utils.RewardUtils import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.libs.utils.extensions.backedReward import com.kickstarter.libs.utils.extensions.isErrored import com.kickstarter.libs.utils.extensions.isNotNull import com.kickstarter.libs.utils.extensions.isNull import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.libs.utils.extensions.userIsCreator import com.kickstarter.mock.factories.RewardFactory import com.kickstarter.models.Backing import com.kickstarter.models.PaymentSource import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.StoredCard import com.kickstarter.models.User import com.kickstarter.models.extensions.getCardTypeDrawable import com.kickstarter.ui.data.PledgeStatusData import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.fragments.BackingFragment import com.stripe.android.model.Card import com.stripe.android.model.CardBrand import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import org.joda.time.DateTime import type.CreditCardPaymentType import type.CreditCardTypes import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit interface BackingFragmentViewModel { interface Inputs { /** Configure with current [ProjectData]. */ fun configureWith(projectData: ProjectData) /** Call when the fix payment method button is clicked. */ fun fixPaymentMethodButtonClicked() /** Call when the pledge has been successfully updated. */ fun pledgeSuccessfullyUpdated() /** Call when the mark as received checkbox is checked. */ fun receivedCheckboxToggled(checked: Boolean) /** Call when the swipe refresh layout is triggered. */ fun refreshProject() fun isExpanded(state: Boolean?) } interface Outputs { /** Emits the backer's avatar URL. */ fun backerAvatar(): Observable<String> /** Emits the backer's name. */ fun backerName(): Observable<String> /** Emits the backer's sequence. */ fun backerNumber(): Observable<String> /** Emits the expiration of the backing's card. */ fun cardExpiration(): Observable<String> /** Emits the name of the card issuer from [Card.CardBrand] or Google Pay or Apple Pay string resources. */ fun cardIssuer(): Observable<Either<String, Int>> /** Emits the last four digits of the backing's card. */ fun cardLastFour(): Observable<String> /** Emits the card brand drawable to display. */ fun cardLogo(): Observable<Int> /** Emits a boolean determining if the fix payment method button should be visible. */ fun fixPaymentMethodButtonIsGone(): Observable<Boolean> /** Emits a boolean determining if the fix payment method message should be visible. */ fun fixPaymentMethodMessageIsGone(): Observable<Boolean> /** Emits when we should notify the [BackingFragment.BackingDelegate] to refresh the project. */ fun notifyDelegateToRefreshProject(): Observable<Unit> /** Call when the [BackingFragment.BackingDelegate] should be notified to show the fix pledge flow. */ fun notifyDelegateToShowFixPledge(): Observable<Unit> /** Emits a boolean determining if the payment method section should be visible. */ fun paymentMethodIsGone(): Observable<Boolean> /** Emits the amount pledged minus the shipping. */ fun pledgeAmount(): Observable<CharSequence> /** Emits the date the backing was pledged on. */ fun pledgeDate(): Observable<String> /** Emits the string resource ID that best represents the pledge status and associated data. */ fun pledgeStatusData(): Observable<PledgeStatusData> /** Emits a boolean determining if the pledge summary should be visible. */ fun pledgeSummaryIsGone(): Observable<Boolean> /** Emits the [ProjectData] and currently backed [Reward]. */ fun projectDataAndReward(): Observable<Pair<ProjectData, Reward>> /** Emits the [ProjectData] and currently selected AddOns: [List<Reward>]. */ fun projectDataAndAddOns(): Observable<Pair<ProjectData, List<Reward>>> /** Emits a boolean that determines if received checkbox should be checked. */ fun receivedCheckboxChecked(): Observable<Boolean> /** Emits a boolean determining if the delivered section should be visible for the backer perspective. */ fun receivedSectionIsGone(): Observable<Boolean> /** Emits a boolean determining if the delivered section should be visible for the creator perspective. */ fun receivedSectionCreatorIsGone(): Observable<Boolean> /** Emits the shipping amount of the backing. */ fun shippingAmount(): Observable<CharSequence> /** Emits the shipping location of the backing. */ fun shippingLocation(): Observable<String> /** Emits a boolean determining if the shipping summary should be visible. */ fun shippingSummaryIsGone(): Observable<Boolean> /** Emits when the backing has successfully been updated. */ fun showUpdatePledgeSuccess(): Observable<Unit> /** Emits a boolean determining if the swipe refresher is visible. */ fun swipeRefresherProgressIsVisible(): Observable<Boolean> /** Emits the total amount pledged. */ fun totalAmount(): Observable<CharSequence> /** Emits the bonus support added to the pledge, if any **/ fun bonusSupport(): Observable<CharSequence> /** Emits the estimated delivery date of this reward **/ fun estimatedDelivery(): Observable<String> /** Emits a boolean determining if the delivery disclaimer section is visible **/ fun deliveryDisclaimerSectionIsGone(): Observable<Boolean> } class BackingFragmentViewModel(val environment: Environment) : ViewModel(), Inputs, Outputs { private val fixPaymentMethodButtonClicked = PublishSubject.create<Unit>() private val pledgeSuccessfullyCancelled = PublishSubject.create<Unit>() private val projectDataInput = PublishSubject.create<ProjectData>() private val receivedCheckboxToggled = PublishSubject.create<Boolean>() private val refreshProject = PublishSubject.create<Unit>() private val isExpanded = PublishSubject.create<Boolean>() private val backerAvatar = BehaviorSubject.create<String>() private val backerName = BehaviorSubject.create<String>() private val backerNumber = BehaviorSubject.create<String>() private val cardExpiration = BehaviorSubject.create<String>() private val cardIssuer = BehaviorSubject.create<Either<String, Int>>() private val cardLastFour = BehaviorSubject.create<String>() private val cardLogo = BehaviorSubject.create<Int>() private val fixPaymentMethodButtonIsGone = BehaviorSubject.create<Boolean>() private val fixPaymentMethodMessageIsGone = BehaviorSubject.create<Boolean>() private val notifyDelegateToRefreshProject = PublishSubject.create<Unit>() private val notifyDelegateToShowFixPledge = PublishSubject.create<Unit>() private val paymentMethodIsGone = BehaviorSubject.create<Boolean>() private val pledgeAmount = BehaviorSubject.create<CharSequence>() private val pledgeDate = BehaviorSubject.create<String>() private val pledgeStatusData = BehaviorSubject.create<PledgeStatusData>() private val pledgeSummaryIsGone = BehaviorSubject.create<Boolean>() private val projectDataAndReward = BehaviorSubject.create<Pair<ProjectData, Reward>>() private val receivedCheckboxChecked = BehaviorSubject.create<Boolean>() private val receivedSectionIsGone = BehaviorSubject.create<Boolean>() private val receivedSectionCreatorIsGone = BehaviorSubject.create<Boolean>() private val shippingAmount = BehaviorSubject.create<CharSequence>() private val shippingLocation = BehaviorSubject.create<String>() private val shippingSummaryIsGone = BehaviorSubject.create<Boolean>() private val showUpdatePledgeSuccess = PublishSubject.create<Unit>() private val swipeRefresherProgressIsVisible = BehaviorSubject.create<Boolean>() private val totalAmount = BehaviorSubject.create<CharSequence>() private val addOnsList = BehaviorSubject.create<Pair<ProjectData, List<Reward>>>() private val bonusSupport = BehaviorSubject.create<CharSequence>() private val estimatedDelivery = BehaviorSubject.create<String>() private val deliveryDisclaimerSectionIsGone = BehaviorSubject.create<Boolean>() private val apiClient = requireNotNull(this.environment.apiClientV2()) private val apolloClient = requireNotNull(this.environment.apolloClientV2()) private val ksCurrency = requireNotNull(this.environment.ksCurrency()) private val analyticEvents = requireNotNull(this.environment.analytics()) val ksString: KSString? = this.environment.ksString() private val currentUser = requireNotNull(this.environment.currentUserV2()) private val disposables = CompositeDisposable() val inputs: Inputs = this val outputs: Outputs = this init { this.pledgeSuccessfullyCancelled .subscribe { this.showUpdatePledgeSuccess.onNext(it) } .addToDisposable(disposables) this.projectDataInput .filter { it.project().isBacking() || it.project().userIsCreator(it.user()) } .map { projectData -> joinProjectDataAndReward(projectData) } .subscribe { this.projectDataAndReward.onNext(it) } .addToDisposable(disposables) val backedProject = this.projectDataInput .map { it.project() } val backing = this.projectDataInput .switchMap { getBackingInfo(it) } .compose(neverErrorV2()) .filter { it.isNotNull() } .share() val rewardA = backing .filter { it.reward().isNotNull() } .map { requireNotNull(it.reward()) } val rewardB = projectDataAndReward .filter { it.second.isNotNull() } .map { requireNotNull(it.second) } val reward = Observable.merge(rewardA, rewardB) .distinctUntilChanged() val isCreator = Observable.combineLatest(this.currentUser.observable(), backedProject) { user, project -> Pair(user, project) } .map { it.second.userIsCreator(it.first.getValue()) } backing .filter { it.backerName().isNotNull() } .map { requireNotNull(it.backerName()) } .subscribe { this.backerName.onNext(it) } .addToDisposable(disposables) backing .filter { it.backerUrl().isNotNull() } .map { requireNotNull(it.backerUrl()) } .subscribe { this.backerAvatar.onNext(it) } .addToDisposable(disposables) backing .map { NumberUtils.format(it.sequence().toFloat()) } .distinctUntilChanged() .subscribe { this.backerNumber.onNext(it) } .addToDisposable(disposables) backing .filter { it.pledgedAt().isNotNull() } .map { DateTimeUtils.longDate(requireNotNull(it.pledgedAt())) } .distinctUntilChanged() .subscribe { this.pledgeDate.onNext(it) } .addToDisposable(disposables) backing .map { it.amount() - it.shippingAmount() - it.bonusAmount() } .filter { it.isNotNull() } .compose<Pair<Double, Project>>(combineLatestPair(backedProject)) .map { ProjectViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) } .distinctUntilChanged() .subscribe { this.pledgeAmount.onNext(it) } .addToDisposable(disposables) backing .map { shouldHideShipping(it) } .distinctUntilChanged() .subscribe { this.shippingSummaryIsGone.onNext(it) }.addToDisposable(disposables) backing .map { it.reward().isNull() } .distinctUntilChanged() .subscribe { this.pledgeSummaryIsGone.onNext(it) }.addToDisposable(disposables) Observable.combineLatest(backedProject, backing, this.currentUser.loggedInUser()) { p, b, user -> Triple(p, b, user) } .map { pledgeStatusData(it.first, it.second, it.third) } .distinctUntilChanged() .subscribe { this.pledgeStatusData.onNext(it) } .addToDisposable(disposables) backing .filter { it.shippingAmount().isNotNull() } .map { requireNotNull(it.shippingAmount()) } .compose<Pair<Float, Project>>(combineLatestPair(backedProject)) .map { ProjectViewUtils.styleCurrency(it.first.toDouble(), it.second, this.ksCurrency) } .distinctUntilChanged() .subscribe { this.shippingAmount.onNext(it) } .addToDisposable(disposables) backing .filter { it.locationName().isNotNull() } .map { requireNotNull(it.locationName()) } .distinctUntilChanged() .subscribe { this.shippingLocation.onNext(it) } .addToDisposable(disposables) backing .filter { it.amount().isNotNull() } .map { it.amount() } .compose<Pair<Double, Project>>(combineLatestPair(backedProject)) .map { ProjectViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) } .distinctUntilChanged() .subscribe { this.totalAmount.onNext(it) } .addToDisposable(disposables) backing .map { CreditCardPaymentType.safeValueOf(it.paymentSource()?.paymentType()) } .map { it == CreditCardPaymentType.ANDROID_PAY || it == CreditCardPaymentType.APPLE_PAY || it == CreditCardPaymentType.CREDIT_CARD } .map { it.negate() } .distinctUntilChanged() .subscribe { this.paymentMethodIsGone.onNext(it) } .addToDisposable(disposables) val paymentSource = backing .filter { it.paymentSource().isNotNull() } .map { requireNotNull(it.paymentSource()) } .ofType(PaymentSource::class.java) val simpleDateFormat = SimpleDateFormat(StoredCard.DATE_FORMAT, Locale.getDefault()) paymentSource .map { source -> source.expirationDate()?.let { simpleDateFormat.format(it) } ?: "" } .distinctUntilChanged() .subscribe { this.cardExpiration.onNext(it) } .addToDisposable(disposables) paymentSource .map { cardIssuer(it) } .distinctUntilChanged() .subscribe { this.cardIssuer.onNext(it) } .addToDisposable(disposables) paymentSource .map { it.lastFour() ?: "" } .distinctUntilChanged() .subscribe { this.cardLastFour.onNext(it) } .addToDisposable(disposables) paymentSource .map { cardLogo(it) } .distinctUntilChanged() .subscribe { this.cardLogo.onNext(it) } .addToDisposable(disposables) val backingIsNotErrored = backing .map { it.isErrored() } .distinctUntilChanged() .map { it.negate() } backingIsNotErrored .subscribe { this.fixPaymentMethodButtonIsGone.onNext(it) } .addToDisposable(disposables) backingIsNotErrored .subscribe { this.fixPaymentMethodMessageIsGone.onNext(it) } .addToDisposable(disposables) this.fixPaymentMethodButtonClicked .subscribe { this.notifyDelegateToShowFixPledge.onNext(Unit) } .addToDisposable(disposables) backing .map { it.completedByBacker() } .distinctUntilChanged() .subscribe { this.receivedCheckboxChecked.onNext(it) } .addToDisposable(disposables) backing .compose<Pair<Backing, Project>>(combineLatestPair(backedProject)) .compose(takePairWhenV2(this.receivedCheckboxToggled)) .switchMap { this.apiClient.postBacking(it.first.second, it.first.first, it.second).compose(neverErrorV2()) } .share() .subscribe() this.isExpanded .filter { it } .compose(combineLatestPair(backing)) .map { it.second } .compose<Pair<Backing, ProjectData>>(combineLatestPair(projectDataInput)) .subscribe { this.analyticEvents.trackManagePledgePageViewed(it.first, it.second) }.addToDisposable(disposables) val rewardIsReceivable = reward .map { RewardUtils.isReward(it) && it.estimatedDeliveryOn().isNotNull() } val backingIsCollected = backing .map { it.status() } .map { it == Backing.STATUS_COLLECTED } .distinctUntilChanged() val sectionShouldBeGone = rewardIsReceivable .compose(combineLatestPair<Boolean, Boolean>(backingIsCollected)) .map { it.first && it.second } .map { it.negate() } .distinctUntilChanged() sectionShouldBeGone .compose<Pair<Boolean, Boolean>>(combineLatestPair(isCreator)) .subscribe { val isUserCreator = it.second val shouldBeGone = it.first if (isUserCreator) { this.receivedSectionIsGone.onNext(true) this.receivedSectionCreatorIsGone.onNext(shouldBeGone) } else { this.receivedSectionIsGone.onNext(shouldBeGone) this.receivedSectionCreatorIsGone.onNext(true) } }.addToDisposable(disposables) this.refreshProject .subscribe { this.notifyDelegateToRefreshProject.onNext(Unit) this.swipeRefresherProgressIsVisible.onNext(true) }.addToDisposable(disposables) val refreshTimeout = this.notifyDelegateToRefreshProject .delay(10, TimeUnit.SECONDS) Observable.merge(refreshTimeout, backedProject.skip(1)) .map { false } .subscribe { this.swipeRefresherProgressIsVisible.onNext(it) } .addToDisposable(disposables) val addOns = backing .map { it.addOns()?.toList() ?: emptyList() } projectDataInput .compose<Pair<ProjectData, List<Reward>>>(combineLatestPair(addOns)) .subscribe { this.addOnsList.onNext(it) } .addToDisposable(disposables) backing .filter { it.bonusAmount().isNotNull() } .map { requireNotNull(it.bonusAmount()) } .compose<Pair<Double, Project>>(combineLatestPair(backedProject)) .map { ProjectViewUtils.styleCurrency(it.first, it.second, this.ksCurrency) } .distinctUntilChanged() .subscribe { this.bonusSupport.onNext(it) } .addToDisposable(disposables) reward .filter { RewardUtils.isReward(it) && it.estimatedDeliveryOn().isNotNull() } .map<DateTime> { it.estimatedDeliveryOn() } .map { DateTimeUtils.estimatedDeliveryOn(it) } .subscribe { this.estimatedDelivery.onNext(it) } .addToDisposable(disposables) isCreator .subscribe { this.deliveryDisclaimerSectionIsGone.onNext(it) } .addToDisposable(disposables) } private fun shouldHideShipping(it: Backing) = it.locationId().isNull() || it.reward()?.let { rw -> RewardUtils.isLocalPickup(rw) } ?: true private fun getBackingInfo(it: ProjectData): Observable<Backing> { return if (it.backing() == null) { this.apolloClient.getProjectBacking(it.project().slug() ?: "") } else { Observable.just(it.backing()) } } private fun joinProjectDataAndReward(projectData: ProjectData): Pair<ProjectData, Reward> { val reward = projectData.backing()?.reward() ?: projectData.project().backing()?.backedReward(projectData.project()) ?: RewardFactory.noReward().toBuilder() .minimum(projectData.backing()?.amount() ?: 1.0) .build() return Pair(projectData, reward) } private fun cardIssuer(paymentSource: PaymentSource): Either<String, Int> { return when (CreditCardPaymentType.safeValueOf(paymentSource.paymentType())) { CreditCardPaymentType.ANDROID_PAY -> Either.Right(R.string.googlepay_button_content_description) CreditCardPaymentType.APPLE_PAY -> Either.Right(R.string.apple_pay_content_description) CreditCardPaymentType.CREDIT_CARD -> Either.Left(StoredCard.issuer(CreditCardTypes.safeValueOf(paymentSource.type()))) else -> Either.Left(CardBrand.Unknown.code) } } private fun cardLogo(paymentSource: PaymentSource): Int { return when (CreditCardPaymentType.safeValueOf(paymentSource.paymentType())) { CreditCardPaymentType.ANDROID_PAY -> R.drawable.google_pay_mark CreditCardPaymentType.APPLE_PAY -> R.drawable.apple_pay_mark CreditCardPaymentType.CREDIT_CARD -> paymentSource.getCardTypeDrawable() else -> R.drawable.generic_bank_md } } private fun pledgeStatusData(project: Project, backing: Backing, user: User): PledgeStatusData { var statusStringRes: Int? if (!project.userIsCreator(user)) { statusStringRes = when (project.state()) { Project.STATE_CANCELED -> R.string.The_creator_canceled_this_project_so_your_payment_method_was_never_charged Project.STATE_FAILED -> R.string.This_project_didnt_reach_its_funding_goal_so_your_payment_method_was_never_charged else -> when (backing.status()) { Backing.STATUS_CANCELED -> R.string.You_canceled_your_pledge_for_this_project Backing.STATUS_COLLECTED -> R.string.We_collected_your_pledge_for_this_project Backing.STATUS_DROPPED -> R.string.Your_pledge_was_dropped_because_of_payment_errors Backing.STATUS_ERRORED -> R.string.We_cant_process_your_pledge_Please_update_your_payment_method Backing.STATUS_PLEDGED -> R.string.If_the_project_reaches_its_funding_goal_you_will_be_charged_total_on_project_deadline Backing.STATUS_PREAUTH -> R.string.We_re_processing_your_pledge_pull_to_refresh else -> null } } } else { statusStringRes = when (project.state()) { Project.STATE_CANCELED -> R.string.You_canceled_this_project_so_the_backers_payment_method_was_never_charged Project.STATE_FAILED -> R.string.Your_project_didnt_reach_its_funding_goal_so_the_backers_payment_method_was_never_charged else -> when (backing.status()) { Backing.STATUS_CANCELED -> R.string.The_backer_canceled_their_pledge_for_this_project Backing.STATUS_COLLECTED -> R.string.We_collected_the_backers_pledge_for_this_project Backing.STATUS_DROPPED -> R.string.This_pledge_was_dropped_because_of_payment_errors Backing.STATUS_ERRORED -> R.string.We_cant_process_this_pledge_because_of_a_problem_with_the_backers_payment_method Backing.STATUS_PLEDGED -> R.string.If_your_project_reaches_its_funding_goal_the_backer_will_be_charged_total_on_project_deadline Backing.STATUS_PREAUTH -> R.string.We_re_processing_this_pledge_pull_to_refresh else -> null } } } val projectDeadline = project.deadline()?.let { DateTimeUtils.longDate(it) } val pledgeTotal = backing.amount() val pledgeTotalString = this.ksCurrency.format(pledgeTotal, project) return PledgeStatusData(statusStringRes, pledgeTotalString, projectDeadline) } override fun configureWith(projectData: ProjectData) { this.projectDataInput.onNext(projectData) } override fun fixPaymentMethodButtonClicked() { this.fixPaymentMethodButtonClicked.onNext(Unit) } override fun pledgeSuccessfullyUpdated() { this.showUpdatePledgeSuccess.onNext(Unit) } override fun receivedCheckboxToggled(checked: Boolean) { this.receivedCheckboxToggled.onNext(checked) } override fun refreshProject() { this.refreshProject.onNext(Unit) } override fun isExpanded(state: Boolean?) { state?.let { this.isExpanded.onNext(it) } } override fun backerAvatar(): Observable<String> = this.backerAvatar override fun backerName(): Observable<String> = this.backerName override fun backerNumber(): Observable<String> = this.backerNumber override fun cardExpiration(): Observable<String> = this.cardExpiration override fun cardIssuer(): Observable<Either<String, Int>> = this.cardIssuer override fun cardLastFour(): Observable<String> = this.cardLastFour override fun cardLogo(): Observable<Int> = this.cardLogo override fun fixPaymentMethodButtonIsGone(): Observable<Boolean> = this.fixPaymentMethodButtonIsGone override fun fixPaymentMethodMessageIsGone(): Observable<Boolean> = this.fixPaymentMethodMessageIsGone override fun notifyDelegateToRefreshProject(): Observable<Unit> = this.notifyDelegateToRefreshProject override fun notifyDelegateToShowFixPledge(): Observable<Unit> = this.notifyDelegateToShowFixPledge override fun paymentMethodIsGone(): Observable<Boolean> = this.paymentMethodIsGone override fun pledgeAmount(): Observable<CharSequence> = this.pledgeAmount override fun pledgeDate(): Observable<String> = this.pledgeDate override fun pledgeStatusData(): Observable<PledgeStatusData> = this.pledgeStatusData override fun pledgeSummaryIsGone(): Observable<Boolean> = this.pledgeSummaryIsGone override fun projectDataAndReward(): Observable<Pair<ProjectData, Reward>> = this.projectDataAndReward override fun projectDataAndAddOns(): Observable<Pair<ProjectData, List<Reward>>> = this.addOnsList override fun receivedCheckboxChecked(): Observable<Boolean> = this.receivedCheckboxChecked override fun receivedSectionIsGone(): Observable<Boolean> = this.receivedSectionIsGone override fun receivedSectionCreatorIsGone(): Observable<Boolean> = this.receivedSectionCreatorIsGone override fun shippingAmount(): Observable<CharSequence> = this.shippingAmount override fun shippingLocation(): Observable<String> = this.shippingLocation override fun shippingSummaryIsGone(): Observable<Boolean> = this.shippingSummaryIsGone override fun showUpdatePledgeSuccess(): Observable<Unit> = this.showUpdatePledgeSuccess override fun swipeRefresherProgressIsVisible(): Observable<Boolean> = this.swipeRefresherProgressIsVisible override fun totalAmount(): Observable<CharSequence> = this.totalAmount override fun bonusSupport(): Observable<CharSequence> = this.bonusSupport override fun estimatedDelivery(): Observable<String> = this.estimatedDelivery override fun deliveryDisclaimerSectionIsGone(): Observable<Boolean> = this.deliveryDisclaimerSectionIsGone override fun onCleared() { disposables.clear() super.onCleared() } } class Factory(private val environment: Environment) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return BackingFragmentViewModel(environment) as T } } }
8
null
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
30,453
android-oss
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/web_event/GetAllH5ActivityInfoReq.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.web_event import org.anime_game_servers.core.base.Version.GI_1_5_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand @AddedIn(GI_1_5_0) @ProtoCommand(REQUEST) internal interface GetAllH5ActivityInfoReq { }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
412
anime-game-multi-proto
MIT License
app/src/main/java/com/nfd/libgenscan/openLibrary/OpenLibraryService.kt
moomooshin
208,666,505
true
{"Kotlin": 13317, "Java": 660}
package com.nfd.libgenscan.openLibrary import com.google.gson.GsonBuilder import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query /** * This interface contacts the Open Library API to get a book's title and author, given its ISBN. */ interface OpenLibraryService { /** * bibkeys will need to start with "ISBN:", followed by the isbn number. * Other queries shouldn't be changed. */ @GET("books") fun getBook( @Query("bibkeys") isbn: String, @Query("format") format: String = "json", @Query("jscmd") jscmd: String = "data"): Call<BookResponse> companion object { private var instance: OpenLibraryService? = null fun getInstance(): OpenLibraryService { if (instance == null) { val bookDeserializer = GsonBuilder() .setLenient() .registerTypeAdapter(BookResponse::class.java, BookResponseDeserializer()) .create() val retrofit = Retrofit.Builder() .baseUrl("https://openlibrary.org/api/") .addConverterFactory(GsonConverterFactory.create(bookDeserializer)) .build() instance = retrofit.create(OpenLibraryService::class.java) } return instance!! } } }
0
Kotlin
0
0
de458e06d526271dcc585c6b35d5ce32357f06f8
1,477
Libgen-Scan
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/PanFood.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.PanFood: ImageVector get() { if (_panFood != null) { return _panFood!! } _panFood = Builder(name = "PanFood", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(10.0f, 15.018f) verticalLineToRelative(2.251f) curveToRelative(0.0f, 0.449f, -0.409f, 0.809f, -0.848f, 0.716f) curveToRelative(-1.569f, -0.332f, -2.805f, -1.568f, -3.137f, -3.137f) curveToRelative(-0.093f, -0.439f, 0.267f, -0.848f, 0.716f, -0.848f) horizontalLineToRelative(2.251f) curveToRelative(0.562f, 0.0f, 1.018f, 0.456f, 1.018f, 1.018f) close() moveTo(13.0f, 11.5f) curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f) reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f) reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f) close() moveTo(9.848f, 8.985f) curveToRelative(1.569f, -0.332f, 2.805f, -1.568f, 3.137f, -3.137f) curveToRelative(0.093f, -0.439f, -0.267f, -0.848f, -0.716f, -0.848f) horizontalLineToRelative(-2.251f) curveToRelative(-0.562f, 0.0f, -1.018f, 0.456f, -1.018f, 1.018f) verticalLineToRelative(2.251f) curveToRelative(0.0f, 0.449f, 0.409f, 0.809f, 0.848f, 0.716f) close() moveTo(8.0f, 10.5f) curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f) reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f) reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f) close() moveTo(13.5f, 16.0f) curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f) reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f) reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f) close() moveTo(17.268f, 11.404f) lineToRelative(-1.397f, 1.397f) curveToRelative(-0.555f, 0.555f, -0.554f, 1.187f, -0.163f, 1.578f) lineToRelative(1.559f, 1.559f) curveToRelative(0.317f, 0.317f, 0.859f, 0.271f, 1.102f, -0.107f) curveToRelative(0.843f, -1.311f, 0.843f, -3.007f, 0.0f, -4.319f) curveToRelative(-0.243f, -0.378f, -0.783f, -0.426f, -1.1f, -0.108f) close() moveTo(24.0f, 12.0f) curveToRelative(0.0f, 6.617f, -5.383f, 12.0f, -12.0f, 12.0f) curveToRelative(-1.945f, 0.0f, -3.777f, -0.479f, -5.403f, -1.305f) lineToRelative(-1.19f, 0.747f) curveToRelative(-1.389f, 0.893f, -3.212f, 0.697f, -4.379f, -0.471f) reflectiveCurveToRelative(-1.363f, -2.991f, -0.471f, -4.379f) lineToRelative(0.776f, -1.126f) curveToRelative(-0.845f, -1.642f, -1.334f, -3.496f, -1.334f, -5.467f) curveTo(0.0f, 5.383f, 5.383f, 0.0f, 12.0f, 0.0f) curveToRelative(1.97f, 0.0f, 3.825f, 0.488f, 5.467f, 1.334f) lineToRelative(1.126f, -0.776f) curveToRelative(1.389f, -0.893f, 3.212f, -0.697f, 4.379f, 0.47f) reflectiveCurveToRelative(1.363f, 2.991f, 0.471f, 4.379f) lineToRelative(-0.747f, 1.19f) curveToRelative(0.826f, 1.627f, 1.305f, 3.458f, 1.305f, 5.403f) close() moveTo(21.0f, 12.0f) curveToRelative(0.0f, -4.963f, -4.038f, -9.0f, -9.0f, -9.0f) reflectiveCurveTo(3.0f, 7.037f, 3.0f, 12.0f) reflectiveCurveToRelative(4.038f, 9.0f, 9.0f, 9.0f) reflectiveCurveToRelative(9.0f, -4.037f, 9.0f, -9.0f) close() moveTo(16.5f, 10.0f) curveToRelative(0.828f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f) reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f) reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f) close() } } .build() return _panFood!! } private var _panFood: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,421
icons
MIT License
feed/src/main/java/com/abhat/feed/ui/FeedViewModel.kt
AnirudhBhat
257,323,871
false
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "INI": 5, "Proguard": 6, "Kotlin": 96, "XML": 86, "Java": 1, "YAML": 1}
package com.abhat.feed.ui import android.widget.RelativeLayout import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.abhat.core.SortType.SortType import com.abhat.core.common.CoroutineContextProvider import com.abhat.feed.data.FeedRepository import com.abhat.feed.ui.state.FeedViewResult import com.abhat.feed.ui.state.FeedViewState import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Created by <NAME> on 20,April,2020 */ open class FeedViewModel( private val feedRepository: FeedRepository, private val contextProvider: CoroutineContextProvider ) : ViewModel() { private lateinit var sortTypeList: List<SortType> val feedViewState: MutableLiveData<FeedViewState> = MutableLiveData() private var currentViewState = FeedViewState(subreddit = "all") set(value) { field = value feedViewState.postValue(value) } val isNsfwLiveData: MutableLiveData<Pair<Boolean, RelativeLayout?>> = MutableLiveData() fun showProgressBar() { currentViewState = currentViewState.copy(isLoading = true, feedList = null, error = null) } fun hideProgressBar() { currentViewState = currentViewState.copy(isLoading = false, feedList = null, error = null) } fun subredditBottomSheetOpened() { currentViewState = currentViewState.copy(isSubredditBottomSheetOpen = true) } fun subredditBottomSheetClosed() { currentViewState = currentViewState.copy(isSubredditBottomSheetOpen = false) } fun sortBottomSheetOpened() { currentViewState = currentViewState.copy(isSortBottomSheetOpen = true) } fun sortBottomSheetClosed() { currentViewState = currentViewState.copy(isSortBottomSheetOpen = false) } fun getFeed(subreddit: String, after: String, sortType: SortType) { showProgressBar() viewModelScope.launch(contextProvider.Main) { val feedViewResult = withContext(viewModelScope.coroutineContext + contextProvider.IO) { feedRepository.getFeed(subreddit, after, sortType) } feedViewResult?.let { feedViewResult -> sortTypeList = if (shouldShowBestOptionInSortList(subreddit)) { returnSortTypeList() } else { returnSortTypeListWithoutBestOption() } when (feedViewResult) { is FeedViewResult.Success -> { currentViewState = currentViewState.copy( isLoading = false, feedList = feedViewResult.feedData, subreddit = subreddit, sortType = returnSortType(sortType, subreddit), sortList = sortTypeList, error = null ) } is FeedViewResult.Error.NetworkError -> { currentViewState = currentViewState.copy( isLoading = false, feedList = null, subreddit = subreddit, sortType = returnSortType(sortType, subreddit), sortList = sortTypeList, error = feedViewResult.throwable ) } is FeedViewResult.Error.AuthorizationError -> { currentViewState = currentViewState.copy( isLoading = false, feedList = null, subreddit = subreddit, sortType = returnSortType(sortType, subreddit), sortList = sortTypeList, authorizationError = feedViewResult.throwable ) } } } } } fun shouldShowBestOptionInSortList(subreddit: String? = null): Boolean { return subreddit == null || subreddit.isEmpty() || subreddit.equals("frontpage", ignoreCase = true) } private fun returnSortTypeListWithoutBestOption(): List<SortType> { return listOf( SortType.hot, SortType.new, SortType.rising ) } private fun returnSortTypeList(): List<SortType> { return listOf( SortType.best, SortType.hot, SortType.new, SortType.rising ) } fun returnSortType(sortType: SortType, subreddit: String): SortType { if (sortType == SortType.empty && shouldShowBestOptionInSortList(subreddit)) { return SortType.best } return sortType } }
1
null
1
1
9036e653ed15d34241dcc5397efc687bae89328f
5,031
Reddit-client
Apache License 2.0
app/src/main/java/uk/ac/ncl/openlab/irismsg/model/UserEntity.kt
iris-msg
154,692,717
false
null
package uk.ac.ncl.openlab.irismsg.model import android.support.annotation.Nullable import com.squareup.moshi.Json import java.util.Date data class UserEntity( @Json(name = "_id") override val id: String, @Json(name = "createdAt") override val createdAt: Date, @Json(name = "updatedAt") override val updatedAt: Date, @Json(name = "phoneNumber") val phoneNumber: String, @Json(name = "locale") @Nullable val locale: String, @Json(name = "verifiedOn") @Nullable val verifiedOn: Date?, @Json(name = "fcmToken") @Nullable val fcmToken: String? ) : ApiEntity { companion object { var current : UserEntity? = null } }
0
Kotlin
1
1
a58ca326170521b206dc22db0ea97c03bd499d2b
662
android-app
MIT License
graphql-api/src/main/kotlin/io/zeebe/zeeqs/graphql/resolvers/query/WorkflowInstanceQueryResolver.kt
strawhat5
348,548,259
true
{"Kotlin": 81040, "Shell": 973}
package io.zeebe.zeeqs.data.resolvers import graphql.kickstart.tools.GraphQLQueryResolver import io.zeebe.zeeqs.data.entity.WorkflowInstance import io.zeebe.zeeqs.data.entity.WorkflowInstanceState import io.zeebe.zeeqs.data.repository.WorkflowInstanceRepository import io.zeebe.zeeqs.graphql.resolvers.connection.WorkflowInstanceConnection import org.springframework.data.domain.PageRequest import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Component @Component class WorkflowInstanceQueryResolver( val workflowInstanceRepository: WorkflowInstanceRepository ) : GraphQLQueryResolver { fun workflowInstances(perPage: Int, page: Int, stateIn: List<WorkflowInstanceState>): WorkflowInstanceConnection { return WorkflowInstanceConnection( getItems = { workflowInstanceRepository.findByStateIn(stateIn, PageRequest.of(page, perPage)).toList() }, getCount = { workflowInstanceRepository.countByStateIn(stateIn) } ) } fun workflowInstance(key: Long): WorkflowInstance? { return workflowInstanceRepository.findByIdOrNull(key) } }
0
null
0
0
9c5e03ef372021b7aa214caf30d5492e1f6bd06e
1,152
zeeqs
Apache License 2.0
graphql-api/src/main/kotlin/io/zeebe/zeeqs/graphql/resolvers/query/WorkflowInstanceQueryResolver.kt
strawhat5
348,548,259
true
{"Kotlin": 81040, "Shell": 973}
package io.zeebe.zeeqs.data.resolvers import graphql.kickstart.tools.GraphQLQueryResolver import io.zeebe.zeeqs.data.entity.WorkflowInstance import io.zeebe.zeeqs.data.entity.WorkflowInstanceState import io.zeebe.zeeqs.data.repository.WorkflowInstanceRepository import io.zeebe.zeeqs.graphql.resolvers.connection.WorkflowInstanceConnection import org.springframework.data.domain.PageRequest import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Component @Component class WorkflowInstanceQueryResolver( val workflowInstanceRepository: WorkflowInstanceRepository ) : GraphQLQueryResolver { fun workflowInstances(perPage: Int, page: Int, stateIn: List<WorkflowInstanceState>): WorkflowInstanceConnection { return WorkflowInstanceConnection( getItems = { workflowInstanceRepository.findByStateIn(stateIn, PageRequest.of(page, perPage)).toList() }, getCount = { workflowInstanceRepository.countByStateIn(stateIn) } ) } fun workflowInstance(key: Long): WorkflowInstance? { return workflowInstanceRepository.findByIdOrNull(key) } }
0
null
0
0
9c5e03ef372021b7aa214caf30d5492e1f6bd06e
1,152
zeeqs
Apache License 2.0
app/src/main/java/com/ludoven/mvp/presenter/HomePresenter.kt
ApacheJondy
642,767,869
false
null
package com.ludoven.mvp.presenter import android.util.Log import com.example.myapplication.base.BasePresenter import com.ludoven.mvp.base.BaseBean import com.ludoven.mvp.contract.MainContract import com.ludoven.mvp.contract.MainContract.Presenter import com.ludoven.mvp.http.Api import com.ludoven.mvp.http.BaseResourceObserver import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers class HomePresenter : BasePresenter<MainContract.View>(), MainContract.Presenter { override fun testPresenter() { Api.getInstance().getApiService() .getData() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe (object : BaseResourceObserver<String>() { override fun onSubscribe(d: Disposable) { addReqs(d) } override fun onNext(t: String) { mView!!.testView(t) } }) } }
0
Kotlin
0
0
27cc25cc838e1fc61626f0085c9dbe7d8d6e0a26
1,063
Kotlin_Mvp
Mulan Permissive Software License, Version 2
src/main/kotlin/nl/toefel/blog/exposed/MainWithPostgresAndHikari.kt
toefel18
191,971,928
false
null
package nl.toefel.blog.exposed import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import nl.toefel.blog.exposed.rest.Router import org.jetbrains.exposed.sql.Database import org.slf4j.Logger import org.slf4j.LoggerFactory import kotlin.math.min /** * Connects to a Postgres database using a HikariCP connection pool and configures the schema and test data, * then starts a REST API at 8080. * * Using docker, you can start a local Postgres database as follows: * ``` * docker run --name exposed-db -p 5432:5432 -e POSTGRES_USER=exposed -e POSTGRES_PASSWORD=exposed -d postgres * ``` * * If postgres is not running, it will retry connecting with a back-off */ class MainWithPostgresAndHikari { companion object { private val logger: Logger = LoggerFactory.getLogger(MainWithPostgresAndHikari::class.java) @JvmStatic fun main(args: Array<String>) { logger.info("Creating a HikariCP data source") val hikariDataSource = createHikariDataSourceWithRetry( jdbcUrl = "jdbc:postgresql://127.0.0.1:5432/exposed", username = "exposed", password = "<PASSWORD>") val db = Database.connect(hikariDataSource) db.useNestedTransactions = true // see https://github.com/JetBrains/Exposed/issues/605 DatabaseInitializer.createSchemaAndTestData() Router(8080).start().printHints() } /** * Creates a HikariDataSource and returns it. If any exception is thrown, the operation is retried after x millis as * defined in the backoff sequence. If the sequence runs out of entries, the operation fails with the last * encountered exception. */ tailrec fun createHikariDataSourceWithRetry(jdbcUrl: String, username: String, password: String, backoffSequenceMs: Iterator<Long> = defaultBackoffSequenceMs.iterator()): HikariDataSource { try { val config = HikariConfig() config.jdbcUrl = jdbcUrl config.username = username config.password = <PASSWORD> config.driverClassName = "org.postgresql.Driver" return HikariDataSource(config) } catch (ex: Exception) { logger.error("Failed to create data source ${ex.message}") if (!backoffSequenceMs.hasNext()) throw ex } val backoffMillis = backoffSequenceMs.next() logger.info("Trying again in $backoffMillis millis") Thread.sleep(backoffMillis) return createHikariDataSourceWithRetry(jdbcUrl, username, password, backoffSequenceMs) } val maxBackoffMs = 16000L val defaultBackoffSequenceMs = generateSequence(1000L) { min(it * 2, maxBackoffMs) } } }
15
Kotlin
3
13
7ed2887fbbe07302aeb7064b5e123851e965ff05
2,915
kotlin-exposed-blog
MIT License
android/app/src/main/kotlin/com/root101/citmatel_strawberry/tools/citmatel_strawberry_tools/MainActivity.kt
Root-101
444,591,045
false
{"Dart": 72243, "Java": 535, "Swift": 404, "Kotlin": 168, "Objective-C": 38}
package com.root101.citmatel_strawberry.tools.citmatel_strawberry_tools import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
6dd8fdd80d882e790f84b7a2907178b974c7c96d
168
citmatel_strawberry_tools
Apache License 2.0
core/network/src/androidMain/kotlin/dev/sasikanth/rss/reader/core/network/parser/AndroidFeedParser.kt
msasikanth
632,826,313
false
{"Kotlin": 652834, "Swift": 8741, "Shell": 227, "Ruby": 102}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.sasikanth.rss.reader.core.network.parser import android.util.Xml import dev.sasikanth.rss.reader.core.model.remote.FeedPayload import dev.sasikanth.rss.reader.core.network.parser.FeedParser.Companion.ATOM_TAG import dev.sasikanth.rss.reader.core.network.parser.FeedParser.Companion.HTML_TAG import dev.sasikanth.rss.reader.core.network.parser.FeedParser.Companion.RSS_TAG import dev.sasikanth.rss.reader.exceptions.XmlParsingError import dev.sasikanth.rss.reader.util.DispatchersProvider import kotlinx.coroutines.withContext import me.tatarka.inject.annotations.Inject import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException @Inject class AndroidFeedParser(private val dispatchersProvider: DispatchersProvider) : FeedParser { override suspend fun parse(xmlContent: String, feedUrl: String): FeedPayload { return try { withContext(dispatchersProvider.io) { val parser = Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) } return@withContext xmlContent.reader().use { reader -> parser.setInput(reader) parser.nextTag() when (parser.name) { RSS_TAG -> AndroidRssParser(parser, feedUrl).parse() ATOM_TAG -> AndroidAtomParser(parser, feedUrl).parse() HTML_TAG -> throw HtmlContentException() else -> throw UnsupportedOperationException("Unknown feed type: ${parser.name}") } } } } catch (e: XmlPullParserException) { throw XmlParsingError(e.stackTraceToString()) } } }
9
Kotlin
30
734
f38829160f9983c96be447c142b860853c551d4f
2,192
twine
Apache License 2.0
app/src/main/java/dev/alejo/triqui/ui/game/GameScreen.kt
jimmyale3102
798,526,370
false
{"Kotlin": 41359}
package dev.alejo.triqui.ui.game import android.content.Context import android.content.Intent import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import dev.alejo.triqui.R import dev.alejo.triqui.ui.game.components.GameResult import dev.alejo.triqui.ui.game.components.GameVictories import dev.alejo.triqui.ui.home.components.TriquiButton import dev.alejo.triqui.ui.model.GameModel import dev.alejo.triqui.ui.model.PlayerType import dev.alejo.triqui.ui.theme.Blue40 import dev.alejo.triqui.ui.theme.GeneralRoundCorner import dev.alejo.triqui.ui.theme.Gold80 import dev.alejo.triqui.ui.theme.TransparentBlack80 import dev.alejo.triqui.ui.theme.TransparentGold10 @Composable fun GameScreen( gameViewModel: GameViewModel = hiltViewModel(), gameId: String, playerId: String, isOwner: Boolean, isSinglePlayer: Boolean, onGoHome: () -> Unit ) { LaunchedEffect(true) { gameViewModel.joinToGame(gameId, playerId, isOwner, isSinglePlayer) } val game: GameModel? by gameViewModel.game.collectAsState() val winner: PlayerType? by gameViewModel.winner.collectAsState() val playerType = game?.let { if (it.isGameReady) { gameViewModel.getPlayer() } else { PlayerType.Main } } ?: PlayerType.Main if (winner != null) { GameResult( game = game!!, winner = winner!!, playerType = playerType, onGoHome = { onGoHome() }, onPlayAgain = { gameViewModel.onPlayAgain() } ) } else { val context = LocalContext.current Game( game = game, playerType = playerType, shareGameId = { shareGameId(context, game?.gameId) } ) { position -> gameViewModel.updateGame(position) } } } private fun shareGameId(context: Context, gameId: String?) { val sendIntent: Intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, gameId) type = "text/plain" } val shareIntent = Intent.createChooser(sendIntent, null) context.startActivity(shareIntent) } @Composable fun Game( game: GameModel?, playerType: PlayerType, shareGameId: () -> Unit, onPressed: (Int) -> Unit ) { if (game == null) return Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) { Spacer(modifier = Modifier.weight(0.5f)) GameStatus(game) Spacer(modifier = Modifier.weight(1f)) GameVictories(gameVictories = game.victories, playerType = playerType) Spacer(modifier = Modifier.weight(1f)) Board(game) { position -> onPressed(position) } Spacer(modifier = Modifier.weight(1f)) if (playerType == PlayerType.Main && !game.singlePlayer) { ShareGame { shareGameId() } } Spacer(modifier = Modifier.weight(0.5f)) } } @Composable fun GameStatus(game: GameModel) { if (game.isGameReady) { val gameTurn = if (game.isMyTurn) { stringResource(R.string.your_turn) } else { stringResource(R.string.opponent_turn) } Text(text = gameTurn) } else { if (!game.singlePlayer) { Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { CircularProgressIndicator(modifier = Modifier.size(24.dp)) Text(text = stringResource(R.string.waiting_for_your_opponent)) } } } } @Composable fun Board(game: GameModel, onPressed: (Int) -> Unit) { Row { GameItem(game.board[0]) { onPressed(0) } BoardVerticalDivider() GameItem(game.board[1]) { onPressed(1) } BoardVerticalDivider() GameItem(game.board[2]) { onPressed(2) } } BoardHorizontalDivider() Row { GameItem(game.board[3]) { onPressed(3) } BoardVerticalDivider() GameItem(game.board[4]) { onPressed(4) } BoardVerticalDivider() GameItem(game.board[5]) { onPressed(5) } } BoardHorizontalDivider() Row { GameItem(game.board[6]) { onPressed(6) } BoardVerticalDivider() GameItem(game.board[7]) { onPressed(7) } BoardVerticalDivider() GameItem(game.board[8]) { onPressed(8) } } } @Composable private fun BoardVerticalDivider() { Divider( modifier = Modifier .height(92.dp) .width(1.dp), thickness = 1.dp, color = TransparentBlack80 ) } @Composable private fun BoardHorizontalDivider() { Divider( modifier = Modifier .height(1.dp) .width(276.dp), thickness = 1.dp, color = TransparentBlack80 ) } @Composable fun GameItem(playerType: PlayerType, onPressed: () -> Unit) { Box( Modifier .size(92.dp) .padding(8.dp) .clip(RoundedCornerShape(GeneralRoundCorner)) .background(TransparentGold10) .clickable { onPressed() }, contentAlignment = Alignment.Center ) { val playerColor = if (playerType is PlayerType.Main) Gold80 else Blue40 Text(playerType.symbol, fontSize = 32.sp, fontWeight = FontWeight.Bold, color = playerColor) } } @Composable fun ShareGame(shareGameId: () -> Unit) { TriquiButton( icon = R.drawable.ic_share, text = R.string.share_game_id ) { shareGameId() } }
0
Kotlin
0
0
2ce249cf0da367050917189116592da788ee2802
6,830
tictactoe_triqui
MIT License
module_login/src/main/java/com/czl/module_login/viewmodel/RegisterViewModel.kt
cdalwyn
336,133,347
false
{"Kotlin": 630994, "Java": 115105}
package com.czl.module_login.viewmodel import android.view.View import androidx.databinding.ObservableField import com.czl.lib_base.base.BaseBean import com.czl.lib_base.base.BaseViewModel import com.czl.lib_base.base.MyApplication import com.czl.lib_base.binding.command.BindingAction import com.czl.lib_base.binding.command.BindingCommand import com.czl.lib_base.binding.command.BindingConsumer import com.czl.lib_base.data.DataRepository import com.czl.lib_base.event.LiveBusCenter import com.czl.lib_base.extension.ApiSubscriberHelper import com.czl.lib_base.util.RxThreadHelper import com.czl.module_login.R /** * @author Alwyn * @Date 2020/10/15 * @Description */ class RegisterViewModel(application: MyApplication, model: DataRepository) : BaseViewModel<DataRepository>(application, model) { val tvAccount: ObservableField<String> = ObservableField("") val tvPwd: ObservableField<String> = ObservableField("") val tvRePwd: ObservableField<String> = ObservableField("") val onAccountChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer { tvAccount.set(it) }) val onPwdChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer { tvPwd.set(it) }) val onRePwdChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer { tvRePwd.set(it) }) val onBackClick:View.OnClickListener = View.OnClickListener { finish() } // 注册 val onRegisterClickCommand: BindingCommand<Void> = BindingCommand(BindingAction { if (tvPwd.get()!=tvRePwd.get()){ showNormalToast("两次密码输入不一致") return@BindingAction } model.register(tvAccount.get()!!, tvPwd.get()!!, tvRePwd.get()!!) .compose(RxThreadHelper.rxSchedulerHelper(this)) .doOnSubscribe { showLoading() } .subscribe(object : ApiSubscriberHelper<BaseBean<*>>() { override fun onResult(t: BaseBean<*>) { dismissLoading() if (t.errorCode == 0) { showSuccessToast(application.getString(R.string.login_register_success)) LiveBusCenter.postRegisterSuccessEvent(tvAccount.get(), tvPwd.get()) finish() } } override fun onFailed(msg: String?) { dismissLoading() showErrorToast(msg) } }) }) // 前往登录 val onBackToLoginCommand: BindingCommand<Void> = BindingCommand(BindingAction { finish() }) }
1
Kotlin
70
267
77298b416cc15f168499c0b29c8f9017e6c187ca
2,617
PlayAndroid
Apache License 2.0
app/src/main/kotlin/io/orangebuffalo/simpleaccounting/services/integration/downloads/DownloadsRepository.kt
orange-buffalo
154,902,725
false
{"Kotlin": 1102242, "TypeScript": 575198, "Vue": 277186, "SCSS": 30742, "JavaScript": 6817, "HTML": 633, "CSS": 10}
package io.orangebuffalo.simpleaccounting.services.integration.downloads import io.orangebuffalo.simpleaccounting.services.integration.EntityNotFoundException import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.springframework.stereotype.Component import jakarta.annotation.PreDestroy private const val tokenLifetimeInMs = 120_000L @Component class DownloadsRepository { private val scope = CoroutineScope(Dispatchers.Default) private val mutex = Mutex() private val requestsStorage = mutableMapOf<String, PersistentDownloadRequest>() @PreDestroy fun cancelAsyncJobs() { scope.cancel() } suspend fun storeDownloadRequest(token: String, providerId: String, metadata: Any, userName: String) { mutex.withLock { requestsStorage[token] = PersistentDownloadRequest( providerId = providerId, metadata = metadata, userName = userName ) } scope.launch { delay(tokenLifetimeInMs) mutex.withLock { requestsStorage.remove(token) } } } suspend fun getRequestByToken(token: String): PersistentDownloadRequest = requestsStorage[token] ?: throw EntityNotFoundException("Token $token is not found") } data class PersistentDownloadRequest( val providerId: String, val metadata: Any, val userName: String )
69
Kotlin
0
1
dec521702827283d9c1e9273830d061bada1cd5d
1,482
simple-accounting
Creative Commons Attribution 3.0 Unported
MultiModuleApp2/module2/src/main/java/com/github/yamamotoj/module2/package41/Foo04100.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.module2.package41 import com.github.yamamotoj.module2.package40.Foo04099 class Foo04100 { fun method0() { Foo04099().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
403
android_multi_module_experiment
Apache License 2.0
src/main/kotlin/io/github/imagineDevit/giwt/kt/assertions/ShouldMatch.kt
imagineDevit
780,972,448
false
{"Kotlin": 27685}
package io.github.imagineDevit.giwt.kt.assertions import io.github.imagineDevit.giwt.core.ATestCaseResult import io.github.imagineDevit.giwt.core.utils.TextUtils import java.util.function.Predicate @Suppress("unused") data class ShouldMatch<T>(val result: ATestCaseResult.ResultValue.Ok<T>) { data class Matching<T>(val description: String, val predicate: Predicate<T>) { fun shouldTest(value: T) { if (!predicate.test(value)) { throw AssertionError("Matching < ${TextUtils.yellow(description)} > failed ") } } } fun <T> matching(description: String, predicate: Predicate<T>): Matching<T> = Matching(description, predicate) infix fun one(matching: Matching<T>): ShouldMatch<T> = matching.shouldTest(result.value).let { this } fun one(description: String, predicate: Predicate<T>): ShouldMatch<T> = one(matching(description, predicate)) fun all(vararg matchings: Matching<T>): ShouldMatch<T> = matchings .filter { !it.predicate.test(result.value) } .map { "👉 ${it.description}" } .let { if (it.isNotEmpty()) { it.joinToString("\n") throw AssertionError("\n Following matchings failed: \n ${it.joinToString("\n")} \n") } this } fun none(vararg matchings: Matching<T>): ShouldMatch<T> = matchings .filter { it.predicate.test(result.value) } .map { "👉 ${it.description}" } .let { if (it.isNotEmpty()) { it.joinToString("\n") throw AssertionError( "\n Following matchings are expected to fail but succeed: \n ${ it.joinToString( "\n" ) } \n" ) } this } }
0
Kotlin
0
0
65965bb853319151384049944f65f98d645cdbf4
1,988
giwt-kt
MIT License
sdk/src/commonMain/kotlin/gitfox/model/interactor/LabelInteractor.kt
dector
341,706,824
false
null
package gitfox.model.interactor import gitfox.entity.Label import gitfox.model.data.server.GitlabApi import gitfox.model.data.state.ServerChanges import kotlinx.coroutines.flow.Flow /** * @author <NAME> (MaxMyalkin) on 30.10.2018. */ class LabelInteractor internal constructor( private val api: GitlabApi, serverChanges: ServerChanges, private val defaultPageSize: Int ) { val labelChanges: Flow<Long> = serverChanges.labelChanges suspend fun getLabelList( projectId: Long, page: Int ): List<Label> = api.getProjectLabels(projectId, page, defaultPageSize) suspend fun createLabel( projectId: Long, name: String, color: String, description: String?, priority: Int? ): Label = api.createLabel(projectId, name, color, description, priority) suspend fun deleteLabel( projectId: Long, name: String ) { api.deleteLabel(projectId, name) } suspend fun subscribeToLabel( projectId: Long, labelId: Long ): Label = api.subscribeToLabel(projectId, labelId) suspend fun unsubscribeFromLabel( projectId: Long, labelId: Long ): Label = api.unsubscribeFromLabel(projectId, labelId) }
0
Kotlin
0
1
7258eb2bc4ca9fcd1ebf3029217d80d6fd2de4b9
1,250
gitfox-mirror
Apache License 2.0
ultron/src/main/java/com/atiurin/ultron/listeners/LogLifecycleListener.kt
alex-tiurin
312,407,423
false
null
package com.atiurin.ultron.listeners import android.util.Log import com.atiurin.ultron.core.common.Operation import com.atiurin.ultron.core.common.OperationResult import com.atiurin.ultron.core.config.UltronConfig class LogLifecycleListener : UltronLifecycleListener() { override fun before(operation: Operation) { Log.d(UltronConfig.LOGCAT_TAG, "Before execution of ${operation.name}.") } override fun afterSuccess(operationResult: OperationResult<Operation>) { Log.d(UltronConfig.LOGCAT_TAG, "Successfully executed ${operationResult.operation.name}.") } override fun afterFailure(operationResult: OperationResult<Operation>) { Log.d(UltronConfig.LOGCAT_TAG, "Failed description: ${operationResult.description}") } }
1
Kotlin
3
8
795fc6ce2a06e8686efce2fdb175b20b913eac84
769
ultron
Apache License 2.0
sample-compose-fragments/src/main/java/uk/gov/hmrc/sample_compose_fragments/presentation/screens/molecules/BoldTitleBodyViewScreen.kt
hmrc
299,591,950
false
{"Kotlin": 559754, "Ruby": 10016, "Shell": 1395}
/* * Copyright 2023 HM Revenue & Customs * * 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 uk.gov.hmrc.sample_compose_fragments.presentation.screens.molecules import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import uk.gov.hmrc.components.compose.molecule.titleBody.BoldTitleBodyView import uk.gov.hmrc.components.compose.organism.HmrcCardView import uk.gov.hmrc.components.compose.ui.theme.HmrcTheme import uk.gov.hmrc.sample_compose_components.R import uk.gov.hmrc.sample_compose_fragments.presentation.screens.sampletemplate.ExamplesSlot import uk.gov.hmrc.sample_compose_fragments.presentation.screens.sampletemplate.PlaceholderSlot import uk.gov.hmrc.sample_compose_fragments.presentation.screens.sampletemplate.ScreenScrollViewColumn @Composable fun BoldTitleBodyViewScreen() { ScreenScrollViewColumn { PlaceholderSlot { BoldTitleBodyView( titleText = stringResource(id = R.string.bold_placeholder_title), bodyText = stringResource(id = R.string.bold_placeholder_body), ) } ExamplesSlot { HmrcCardView(modifier = Modifier.padding(bottom = HmrcTheme.dimensions.hmrcSpacing16)) { BoldTitleBodyView( titleText = stringResource(id = R.string.bold_example_title), bodyText = stringResource(id = R.string.bold_example_body), modifier = Modifier.padding(HmrcTheme.dimensions.hmrcSpacing16) ) } HmrcCardView(modifier = Modifier.padding(top = HmrcTheme.dimensions.hmrcSpacing16)) { BoldTitleBodyView( titleText = stringResource(id = R.string.longer_text), bodyText = stringResource(id = R.string.longest_text), modifier = Modifier.padding(HmrcTheme.dimensions.hmrcSpacing16) ) } } } }
4
Kotlin
3
7
f51ffb49fac6d44fad0fbc2df95b02ea989840da
2,561
android-components
Apache License 2.0
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/clients/person/VeilarbpersonClient.kt
navikt
435,813,834
false
null
package no.nav.mulighetsrommet.api.clients.person import no.nav.mulighetsrommet.api.domain.PersonDTO interface VeilarbpersonClient { suspend fun hentPersonInfo(fnr: String, accessToken: String): PersonDTO? }
1
Kotlin
1
3
4a9e295dcd541c61b6e31e92757a2f958c9b351b
214
mulighetsrommet
MIT License
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/clients/person/VeilarbpersonClient.kt
navikt
435,813,834
false
null
package no.nav.mulighetsrommet.api.clients.person import no.nav.mulighetsrommet.api.domain.PersonDTO interface VeilarbpersonClient { suspend fun hentPersonInfo(fnr: String, accessToken: String): PersonDTO? }
1
Kotlin
1
3
4a9e295dcd541c61b6e31e92757a2f958c9b351b
214
mulighetsrommet
MIT License
android/anko_blogpost/UserlistAnko/app/src/main/java/com/wayfair/userlistanko/ui/HomeModule.kt
wayfair-archive
31,389,433
false
{"Jupyter Notebook": 176912, "Kotlin": 37763, "Python": 18859, "Java": 2218}
package com.wayfair.userlistanko.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.wayfair.userlistanko.interactor.UserInteractor import com.wayfair.userlistanko.interactor.UserInteractorContract import com.wayfair.userlistanko.repository.UserRepository import com.wayfair.userlistanko.repository.UserRepositoryContract import dagger.Binds import dagger.MapKey import dagger.Module import dagger.multibindings.IntoMap import kotlin.reflect.KClass @Module abstract class HomeModule { @Binds abstract fun provideUserInteractor(userInteractor: UserInteractor): UserInteractorContract @Binds abstract fun provideUserRepository(userRepository: UserRepository): UserRepositoryContract @Binds abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory @Binds abstract fun provideHomeViewModel(viewModel: HomeViewModel): ViewModel }
1
Jupyter Notebook
2
8
39365dbb1c9085aac104940bf1d49ac047419c7d
935
gists
MIT License
waltid-wallet-api/src/main/kotlin/id/walt/webwallet/service/endpoint/EntraServiceEndpointProvider.kt
walt-id
701,058,624
false
{"Kotlin": 2129639, "Vue": 327721, "TypeScript": 93015, "JavaScript": 20560, "Dockerfile": 7261, "Shell": 1651, "CSS": 404}
package id.walt.webwallet.service.endpoint import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonObject import kotlinx.uuid.UUID class EntraServiceEndpointProvider( private val http: HttpClient, ) : ServiceEndpointProvider { override suspend fun get(url: String, did: String, descriptor: JsonObject): String = http.post(url) { setBody( IdentityHubRequest( requestId = UUID().toString(), target = did, messages = listOf( IdentityHubRequest.Message( descriptor = descriptor, ) ) ) ) }.bodyAsText() @Serializable private data class IdentityHubRequest( val requestId: String, val target: String, val messages: List<Message>, ) { @Serializable data class Message( val descriptor: JsonObject, ) } }
24
Kotlin
33
98
a86bd0c843d594f6afe6e747d3c4de7d8a4789a8
1,067
waltid-identity
Apache License 2.0