path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/kawaii/nahida/actest/module/modules/commnds/CommandEnderChestModule.kt
NahidaLing
864,875,780
false
{"Kotlin": 37171}
package kawaii.nahida.actest.module.modules.commnds import kawaii.nahida.actest.module.Module import org.bukkit.event.EventHandler import org.bukkit.event.player.PlayerCommandPreprocessEvent @Suppress("Unused") class CommandEnderChestModule : Module("CommandEnderChest") { @EventHandler fun onPlayerCommand(event: PlayerCommandPreprocessEvent) { if ( arrayOf( event.message.startsWith("/ec", true), event.message.startsWith("/enderChest", true) ).any { it } ) { event.isCancelled = true event.player.openInventory(event.player.enderChest) } } }
0
Kotlin
0
1
5f87acab61e6468feaf37b5f984842869193d132
667
ACTestPlugin
MIT License
hero/ui-heroList/src/main/kotlin/com/mitch/ui_herolist/ui/HeroListEvents.kt
AlekseevArtem
400,860,573
false
null
package com.mitch.ui_herolist.ui sealed class HeroListEvents{ object GetHeroes: HeroListEvents() }
0
Kotlin
0
0
4707e885a931dc4a46382a29e74d687943452ac8
105
Dota2Heroes
Apache License 2.0
presentation/src/main/java/com/bikcodeh/mubi/presentation/screens/profile/ProfileScreen.kt
Bikcodeh
553,763,395
false
{"Kotlin": 253338}
package com.bikcodeh.mubi.presentation.screens.profile import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.bikcodeh.mubi.presentation.screens.login.LoginViewModel @ExperimentalLifecycleComposeApi @Composable fun ProfileScreen( loginViewModel: LoginViewModel = hiltViewModel(), profileViewModel: ProfileViewModel = hiltViewModel(), onLogOut: () -> Unit, onBack: () -> Unit ) { val favorites by profileViewModel.favoritesTvShows.collectAsStateWithLifecycle() LaunchedEffect(key1 = true) { profileViewModel.getFavorites() } ProfileContent( onLogOut = { loginViewModel.saveLogin(isLoggedIn = false) onLogOut() }, onBack = onBack, favorites = favorites ) }
0
Kotlin
0
1
25929e402744a1070357ff1af9b05eb7d8bd345c
1,027
Mubi
MIT License
Async/app/src/main/java/com/leo/async/usecases/GetInformation.kt
leonelgomez1990
456,679,517
false
{"Kotlin": 10666}
package com.leo.async.usecases import com.leo.async.data.InformationRepository class GetInformation ( val informationRepository: InformationRepository ) { suspend operator fun invoke() = informationRepository.getInformation() }
0
Kotlin
0
0
b1cf41e5b7ec21062a67fc86c8a910db14cb6a54
245
kotlin-arch
MIT License
feature/home/src/main/java/com/tmdb/feature/home/HomeScreen.kt
ductam1987
670,563,569
false
null
package com.tmdb.feature.home import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tmdb.core.model.Movie import com.tmdb.feature.home.view.CategoryView import com.tmdb.feature.home.view.PopularView import com.tmdb.feature.home.view.RecommendationView import com.tmdb.feature.home.view.TopRatedView import com.tmdb.feature.home.view.UpcomingView import org.koin.androidx.compose.koinViewModel import theme.colorCrimson /** * Created by Tam Nguyen on 17/07/2023. */ @Composable fun HomeScreen( recommendViewModel: RecommendViewModel = koinViewModel(), navToMovieDetail: (Int) -> Unit, ) { /** * Movie Recommend */ val moviesRecommendation = remember { mutableStateListOf<Movie>() } val totalMoviesRecommend: MutableState<Int> = remember { mutableStateOf(0) } val pagingMoviesRecommend = remember { mutableStateOf(1) } /** * Movie Gender */ val genreList = recommendViewModel.genre.collectAsState() /** * Movie Popular */ val moviesPopular = remember { mutableStateListOf<Movie>() } val totalMoviesPopular: MutableState<Int> = remember { mutableStateOf(0) } val pagingMoviesPopular = remember { mutableStateOf(1) } /** * Movie Top Rated */ val moviesTopRated = remember { mutableStateListOf<Movie>() } val totalMoviesTopRated: MutableState<Int> = remember { mutableStateOf(0) } val pagingMoviesTopRated = remember { mutableStateOf(1) } /** * Movie Upcoming */ val moviesUpcoming = remember { mutableStateListOf<Movie>() } val totalMoviesUpcoming: MutableState<Int> = remember { mutableStateOf(0) } val pagingMoviesUpcoming = remember { mutableStateOf(1) } /** * LaunchedEffect: Shouldn't call multiple functions inside LaunchEffect. * Each function should be run independently and is not affected by the other. * This provides better isolation and control over the execution flow. */ LaunchedEffect(Unit) { recommendViewModel.getTMDBRecommend(paging = pagingMoviesRecommend.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesRecommendation.addAll(_movies.results) totalMoviesRecommend.value = _movies.total_results } } } LaunchedEffect(Unit) { recommendViewModel.getTMDBGender() } LaunchedEffect(Unit) { recommendViewModel.getTMDBPopular(paging = pagingMoviesPopular.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesPopular.addAll(_movies.results) totalMoviesPopular.value = _movies.total_results } } } LaunchedEffect(Unit) { recommendViewModel.getTMDBTopRated(paging = pagingMoviesTopRated.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesTopRated.addAll(_movies.results) totalMoviesTopRated.value = _movies.total_results } } } LaunchedEffect(Unit) { recommendViewModel.getTMDBUpcoming(paging = pagingMoviesUpcoming.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesUpcoming.addAll(_movies.results) totalMoviesUpcoming.value = _movies.total_results } } } Column( modifier = Modifier .padding(start = 10.dp, end = 10.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Box( modifier = Modifier .height(45.dp) .fillMaxWidth(), contentAlignment = Alignment.Center ) { Text( text = "TMDB COMPOSE", modifier = Modifier.padding(start = 10.dp), fontSize = 25.sp, color = colorCrimson, fontWeight = FontWeight.Bold ) } RecommendationView(totalMoviesRecommend = totalMoviesRecommend, movies = moviesRecommendation) { pagingMoviesRecommend.value += 1 recommendViewModel.getTMDBRecommend(paging = pagingMoviesRecommend.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesRecommendation.addAll(_movies.results) } } } CategoryView(listGenre = genreList.value?.genres ?: emptyList()) PopularView( totalMoviesPopular = totalMoviesPopular, movies = moviesPopular, navToMovieDetail = { navToMovieDetail.invoke(it) } ) { pagingMoviesPopular.value += 1 recommendViewModel.getTMDBPopular(paging = pagingMoviesPopular.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesPopular.addAll(_movies.results) } } } TopRatedView( totalMoviesTopRated = totalMoviesTopRated, movies = moviesTopRated, navToMovieDetail = { navToMovieDetail.invoke(it) } ) { pagingMoviesTopRated.value += 1 recommendViewModel.getTMDBTopRated(paging = pagingMoviesTopRated.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesTopRated.addAll(_movies.results) } } } UpcomingView( totalMoviesUpcoming = totalMoviesUpcoming, movies = moviesUpcoming, navToMovieDetail = { navToMovieDetail.invoke(it) } ) { pagingMoviesUpcoming.value += 1 recommendViewModel.getTMDBUpcoming(paging = pagingMoviesUpcoming.value) { _movies -> if (_movies?.results?.isNotEmpty() == true) { moviesUpcoming.addAll(_movies.results) } } } } }
0
Kotlin
0
2
0ea1ae15bbfff390c341e3376af2c884a050af3e
6,876
TMDB-Compose-Koin-UDF
Apache License 2.0
src/main/kotlin/xyz/gameoholic/partigon/particle/loop/ReverseLoop.kt
Gameoholic
680,129,215
false
{"Kotlin": 73114}
package xyz.gameoholic.partigon.particle.loop import org.bstats.charts.AdvancedPie import xyz.gameoholic.partigon.PartigonPlugin import xyz.gameoholic.partigon.util.inject /** * When loop reaches end, reverses the animation, playing it the same way but from point 2 to point 1, * and vice versa. * @param duration The duration of the loop, both directions included. * * @throws IllegalArgumentException If loop duration is not above 0. */ class ReverseLoop(override val duration: Int): Loop { private val plugin: PartigonPlugin by inject() override val envelopeDuration = duration / 2 init { if (duration <= 0) throw IllegalArgumentException("Reverse loop duration must be above 0.") plugin.metrics.addCustomChart(AdvancedPie("loopsCreated") { mapOf("Reverse" to 1) }) // bstats } override fun applyLoop(frameIndex: Int): Int { // For loop index 0,1,2,3,4,5 half loop index will be 0,1,2,0,1,2 val loopIndex = frameIndex % duration val halfLoopIndex = loopIndex % (duration / 2) // If animation needs to be reversed: if (loopIndex >= duration / 2) return duration / 2 - 1 - halfLoopIndex return halfLoopIndex } }
0
Kotlin
0
3
9f8765134aa9d8aed47d7ebcd9180096dd045501
1,234
Partigon
MIT License
androidApp/src/main/java/com/gosunet/krepesmultiplatform/androidApp/features/crepeslist/CrepesList.kt
tonicfx
316,340,241
true
{"Kotlin": 34942, "Swift": 17994, "Ruby": 386, "HTML": 191}
package com.gosunet.krepesmultiplatform.androidApp.features.crepeslist import android.graphics.Bitmap import android.graphics.drawable.Drawable import androidx.compose.foundation.Image import androidx.compose.foundation.Text import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredSize import androidx.compose.foundation.lazy.LazyColumnFor import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageAsset import androidx.compose.ui.platform.ContextAmbient import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.ui.tooling.preview.Preview import androidx.ui.tooling.preview.PreviewParameter import com.bumptech.glide.Glide import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.gosunet.krepesmultiplatform.shared.data.City import com.gosunet.krepesmultiplatform.shared.data.Crepe @Composable fun CrepesList(crepesListViewModel: CrepesListViewModel, city: City = City.Brest) { val crepesList = crepesListViewModel.getCrepes(city) Scaffold( topBar = { TopAppBar(title = { Text("Crepes liste") }) }, bodyContent = { LazyColumnFor( items = crepesList, itemContent = { crepe -> CrepeView(crepe) } ) } ) } @Composable fun CrepeView(crepe: Crepe) { Row( modifier = Modifier.fillMaxWidth() then Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { // var bitmap by remember { mutableStateOf<Bitmap?>(null) } // Glide.with(ContextAmbient.current).asBitmap() // .load(crepe.image) // .into(object : CustomTarget<Bitmap>() { // override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { // bitmap = resource // } // // override fun onLoadCleared(placeholder: Drawable?) {} // }) // if (bitmap != null) // Image( // bitmap!!.asImageAsset(), // Modifier.preferredSize(60.dp).clip(shape = RoundedCornerShape(4.dp)) // ) // else Spacer(modifier = Modifier.preferredSize(20.dp)) Column { Text(text = crepe.name, style = TextStyle(fontSize = 20.sp)) Text( text = crepe.description, style = TextStyle(color = Color.DarkGray, fontSize = 14.sp) ) } } } @Preview @Composable fun DefaultPreview(@PreviewParameter(CrepesProvider::class) crepe: Crepe) { MaterialTheme { CrepeView(crepe) } }
0
Kotlin
0
0
921c60eeb8e5f346deaa9717485a14f672c9a7fe
3,530
KrepesMultiPlatform
MIT License
analyzer/src/test/kotlin/si/ivory/analyzer/example/EventPublisher.kt
simvetanylen
594,891,290
false
null
package si.ivory.analyzer.example interface EventPublisher { fun publish(event: Any) }
0
Kotlin
0
0
bd547d0ee0c559a29659811febcf715fa11be033
91
ivory
Apache License 2.0
src/test/kotlin/nl/jackploeg/aoc/_2022/calendar/day14/Day14Test.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day14 import javax.inject.Inject import nl.jackploeg.aoc._2022.DaggerTestDayComponent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class Day14Test { @Inject lateinit var day14: Day14 @BeforeEach fun setup() { DaggerTestDayComponent.create().inject(this) } @Test fun testDay14PartOneTestInput() { assertEquals(24, day14.partOne(DAY_14_TEST)) } @Test fun testDay14PartTwoTestInput() { assertEquals(93, day14.partTwo(DAY_14_TEST)) } @Test fun testDay14PartOne() { assertEquals(1078, day14.partOne(DAY_14)) } @Test fun testDay14PartTwo() { assertEquals(30157, day14.partTwo(DAY_14)) } companion object { private const val DAY_14: String = "advent-of-code-input/2022/day14.input" private const val DAY_14_TEST: String = "advent-of-code-input/2022/day14.test" } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
965
advent-of-code
MIT License
alchemy-core/src/androidMain/kotlin/com/alchemy/sdk/util/Dispatchers.kt
tguerin
534,856,094
false
null
package com.alchemy.sdk.util import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers actual class Dispatchers( actual val io: CoroutineDispatcher = Dispatchers.IO, actual val main: CoroutineDispatcher = Dispatchers.Main ) { actual constructor() : this( Dispatchers.IO, Dispatchers.Main, ) }
4
Kotlin
0
3
9768a7ab07d9955e3036c32b1f4497527f237b34
352
alchemy-sdk-kotlin
MIT License
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/BinocularsSolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineawesomeicons 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 compose.icons.LineAwesomeIcons public val LineAwesomeIcons.BinocularsSolid: ImageVector get() { if (_binocularsSolid != null) { return _binocularsSolid!! } _binocularsSolid = Builder(name = "BinocularsSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.0f, 5.0f) curveTo(9.031f, 5.0f, 7.461f, 6.441f, 7.125f, 8.313f) curveTo(5.234f, 8.789f, 3.594f, 10.02f, 2.875f, 11.969f) lineTo(2.844f, 11.969f) lineTo(0.719f, 17.938f) curveTo(0.266f, 18.863f, 0.0f, 19.902f, 0.0f, 21.0f) curveTo(0.0f, 24.855f, 3.145f, 28.0f, 7.0f, 28.0f) curveTo(10.473f, 28.0f, 13.367f, 25.449f, 13.906f, 22.125f) curveTo(14.449f, 22.66f, 15.188f, 23.0f, 16.0f, 23.0f) curveTo(16.813f, 23.0f, 17.551f, 22.66f, 18.094f, 22.125f) curveTo(18.633f, 25.449f, 21.527f, 28.0f, 25.0f, 28.0f) curveTo(28.855f, 28.0f, 32.0f, 24.855f, 32.0f, 21.0f) curveTo(32.0f, 20.027f, 31.801f, 19.094f, 31.438f, 18.25f) lineTo(29.156f, 11.875f) lineTo(29.125f, 11.844f) lineTo(29.125f, 11.813f) curveTo(28.395f, 10.039f, 26.777f, 8.801f, 24.875f, 8.313f) curveTo(24.539f, 6.441f, 22.969f, 5.0f, 21.0f, 5.0f) curveTo(19.145f, 5.0f, 17.637f, 6.285f, 17.188f, 8.0f) lineTo(14.813f, 8.0f) curveTo(14.363f, 6.285f, 12.855f, 5.0f, 11.0f, 5.0f) close() moveTo(11.0f, 7.0f) curveTo(12.191f, 7.0f, 13.0f, 7.809f, 13.0f, 9.0f) lineTo(13.0f, 10.0f) lineTo(19.0f, 10.0f) lineTo(19.0f, 9.0f) curveTo(19.0f, 7.809f, 19.809f, 7.0f, 21.0f, 7.0f) curveTo(22.191f, 7.0f, 23.0f, 7.809f, 23.0f, 9.0f) lineTo(23.0f, 9.906f) lineTo(23.906f, 10.0f) curveTo(25.391f, 10.156f, 26.672f, 11.191f, 27.25f, 12.531f) curveTo(27.258f, 12.551f, 27.273f, 12.574f, 27.281f, 12.594f) lineTo(28.031f, 14.719f) curveTo(27.113f, 14.273f, 26.086f, 14.0f, 25.0f, 14.0f) curveTo(22.074f, 14.0f, 19.574f, 15.816f, 18.531f, 18.375f) curveTo(17.996f, 17.543f, 17.051f, 17.0f, 16.0f, 17.0f) curveTo(14.949f, 17.0f, 14.004f, 17.543f, 13.469f, 18.375f) curveTo(12.426f, 15.816f, 9.926f, 14.0f, 7.0f, 14.0f) curveTo(5.93f, 14.0f, 4.91f, 14.254f, 4.0f, 14.688f) lineTo(4.75f, 12.656f) lineTo(4.75f, 12.625f) curveTo(5.332f, 11.078f, 6.559f, 10.16f, 8.094f, 10.0f) lineTo(9.0f, 9.906f) lineTo(9.0f, 9.0f) curveTo(9.0f, 7.809f, 9.809f, 7.0f, 11.0f, 7.0f) close() moveTo(7.0f, 16.0f) curveTo(9.773f, 16.0f, 12.0f, 18.227f, 12.0f, 21.0f) curveTo(12.0f, 23.773f, 9.773f, 26.0f, 7.0f, 26.0f) curveTo(4.227f, 26.0f, 2.0f, 23.773f, 2.0f, 21.0f) curveTo(2.0f, 20.293f, 2.176f, 19.641f, 2.438f, 19.031f) curveTo(2.453f, 18.992f, 2.453f, 18.945f, 2.469f, 18.906f) curveTo(3.258f, 17.191f, 4.98f, 16.0f, 7.0f, 16.0f) close() moveTo(25.0f, 16.0f) curveTo(27.773f, 16.0f, 30.0f, 18.227f, 30.0f, 21.0f) curveTo(30.0f, 23.773f, 27.773f, 26.0f, 25.0f, 26.0f) curveTo(22.227f, 26.0f, 20.0f, 23.773f, 20.0f, 21.0f) curveTo(20.0f, 18.227f, 22.227f, 16.0f, 25.0f, 16.0f) close() moveTo(16.0f, 19.0f) curveTo(16.563f, 19.0f, 17.0f, 19.438f, 17.0f, 20.0f) curveTo(17.0f, 20.563f, 16.563f, 21.0f, 16.0f, 21.0f) curveTo(15.438f, 21.0f, 15.0f, 20.563f, 15.0f, 20.0f) curveTo(15.0f, 19.438f, 15.438f, 19.0f, 16.0f, 19.0f) close() } } .build() return _binocularsSolid!! } private var _binocularsSolid: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
5,092
compose-icons
MIT License
http4k-typesafe-openapi/src/test/kotlin/org/http4k/typesafe/openapi/HeadersTest.kt
savagematt
251,337,496
true
{"Kotlin": 1938601, "JavaScript": 133282, "Java": 31515, "Shell": 10427, "HTML": 2049, "Handlebars": 1130, "Pug": 944, "CSS": 832}
package org.http4k.typesafe.openapi import com.natpryce.Result import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Status.Companion.BAD_REQUEST import org.http4k.openapi.OpenApiParameter import org.http4k.openapi.ParameterLocation.HEADER import org.http4k.openapi.Referenceable import org.http4k.openapi.real import org.http4k.typesafe.openapi.routing.document import org.http4k.typesafe.openapi.routing.request.header import org.http4k.typesafe.openapi.routing.required import org.http4k.typesafe.routing.RoutingError import org.http4k.typesafe.routing.RoutingError.Companion.routeFailed import org.junit.jupiter.api.Test class HeaderAppendLensTest { @Test fun `docs work`() { val lens = header("X-My-Header") assertThat( lens.document().operation.operation.parameters, equalTo<List<Referenceable<OpenApiParameter>>>( listOf(OpenApiParameter( HEADER, "X-My-Header" ).real())) ) } @Test fun `required() docs are ok`() { val lens = header("X-My-Header").required() assertThat( lens.document().operation.operation.parameters, equalTo<List<Referenceable<OpenApiParameter>>>( listOf(OpenApiParameter( HEADER, "X-My-Header", required = true ).real())) ) } @Test fun `required() routing message is ok`() { val lens: OpenApiLens<Request, String> = header("X-My-Header").required() assertThat( lens.get(Request(GET, "/")), equalTo<Result<String, RoutingError>>( routeFailed("Header 'X-My-Header' is required", BAD_REQUEST)) ) } }
0
Kotlin
0
0
9cc8ef11121bfbe10a1cd0ca58a17885c297af52
1,911
http4k
Apache License 2.0
kontroller/src/test/kotlin/no/ssb/kostra/validation/rule/barnevern/individrule/Melding03Test.kt
statisticsnorway
414,216,275
false
{"Kotlin": 1603185, "TypeScript": 57803, "Batchfile": 6608, "HTML": 694, "SCSS": 110}
package no.ssb.kostra.validation.rule.barnevern.individrule import io.kotest.core.spec.style.BehaviorSpec import no.ssb.kostra.validation.report.Severity import no.ssb.kostra.validation.rule.ForAllRowItem import no.ssb.kostra.validation.rule.KostraTestFactory.validationRuleWithArgsTest import no.ssb.kostra.validation.rule.barnevern.individrule.IndividRuleTestData.dateInTest import no.ssb.kostra.validation.rule.barnevern.individrule.IndividRuleTestData.individInTest import no.ssb.kostra.validation.rule.barnevern.individrule.IndividRuleTestData.meldingTypeInTest class Melding03Test : BehaviorSpec({ include( validationRuleWithArgsTest( sut = Melding03(), expectedSeverity = Severity.WARNING, expectedContextId = meldingTypeInTest.id, ForAllRowItem( "individ without melding", individInTest ), ForAllRowItem( "melding without sluttDato", individInTest.copy( melding = mutableListOf(meldingTypeInTest) ) ), ForAllRowItem( "melding with sluttDato less than 8 days from startDato", individInTest.copy( melding = mutableListOf( meldingTypeInTest.copy(sluttDato = dateInTest.plusDays(4)) ) ) ), ForAllRowItem( "melding with sluttDato more than 8 days from startDato", individInTest.copy( melding = mutableListOf( meldingTypeInTest.copy(sluttDato = dateInTest.plusDays(14)) ) ), expectedErrorMessage = "Melding (${meldingTypeInTest.id}). Fristoverskridelse på behandlingstid " + "for melding, (${meldingTypeInTest.startDato} -> ${dateInTest.plusDays(14)})" ) ) ) })
2
Kotlin
0
1
298df2fc967ad79edbdfe50ceaabbb1ce2c9d969
1,986
kostra-kontrollprogram
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/BoxingGlove.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.BoxingGlove: ImageVector get() { if (_boxingGlove != null) { return _boxingGlove!! } _boxingGlove = Builder(name = "BoxingGlove", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 7.0f) arcTo(7.008f, 7.008f, 0.0f, false, true, 8.0f, 0.0f) horizontalLineToRelative(5.0f) arcToRelative(7.01f, 7.01f, 0.0f, false, true, 6.713f, 5.029f) arcTo(4.993f, 4.993f, 0.0f, false, false, 15.0f, 10.0f) verticalLineToRelative(4.0f) horizontalLineToRelative(2.0f) verticalLineTo(10.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 6.0f, 0.0f) verticalLineToRelative(3.075f) arcTo(7.48f, 7.48f, 0.0f, false, true, 19.752f, 19.0f) horizontalLineTo(2.827f) lineToRelative(-0.377f, -0.539f) arcTo(7.958f, 7.958f, 0.0f, false, true, 1.0f, 13.868f) verticalLineTo(10.444f) arcTo(3.959f, 3.959f, 0.0f, false, false, 3.0f, 11.0f) horizontalLineTo(13.0f) verticalLineTo(9.0f) horizontalLineTo(3.0f) arcTo(2.0f, 2.0f, 0.0f, false, true, 1.0f, 7.0f) close() moveTo(3.0f, 21.0f) verticalLineToRelative(3.0f) horizontalLineTo(19.0f) verticalLineTo(21.0f) close() } } .build() return _boxingGlove!! } private var _boxingGlove: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,515
icons
MIT License
okkeyboard/src/main/java/com/kelin/okkeyboard/handlers/CarKeyboardHandler.kt
kelinZhou
344,328,104
false
null
package com.kelin.okkeyboard.handlers import android.inputmethodservice.Keyboard import android.text.Editable import android.text.Selection import com.kelin.okkeyboard.* /** * **描述:** 车牌号键盘提供者。 * * **创建人:** kelin * * **创建时间:** 2021/3/2 4:56 PM * * **版本:** v 1.0.0 */ sealed class CarKeyboardHandler : KeyboardHandlerImpl() { override val keyboardTitle: Int = R.string.license_plate_keyboard override fun getKeyboard(receiver: OkKeyboardView, target: Editable?): KeyboardHandler { if (keyboard == null) { keyboard = Keyboard(receiver.context, keyboardRes) } return if (target == null) { if (receiver.keyboard != keyboard) { receiver.keyboard = keyboard } this } else { when (Selection.getSelectionStart(target)) { 0 -> { Capital } 1 -> { Registry } else -> { CarNumber } }.getKeyboard(receiver, null) } } override fun onKey(keyboardView: OkKeyboardView, target: Editable, primaryCode: Int, keyCodes: IntArray?) { val selectionStart = Selection.getSelectionStart(target) when (primaryCode) { Keyboard.KEYCODE_MODE_CHANGE -> if (this is Capital) { if (selectionStart == 1) { Registry } else { CarNumber } } else { Capital }.also { if (keyboardView.keyboard != it.keyboard) { keyboardView.keyboard = it.keyboard } } else -> { if (target.length < 8 || selectionStart < target.length) { val capitalsLabel = Capital.getKeys(keyboardView.context).map { it.label } if (selectionStart == 0 && capitalsLabel.contains(target.firstOrNull()?.toString() ?: " ")) { target.replace(0, 1, "") } onInput(target, primaryCode) } } } } override val especialKeyCodes: IntArray? = intArrayOf(Keyboard.KEYCODE_MODE_CHANGE, Keyboard.KEYCODE_DELETE) object Capital : CarKeyboardHandler() { override val keyboardRes: Int = R.xml.keyboard_car_capital } object Registry : CarKeyboardHandler() { override val keyboardRes: Int = R.xml.keyboard_car_number //override val disabledKeyCodes: IntArray? = intArrayOf(48, 49, 50, 51, 52, 53, 54, 55, 56, 57) } object CarNumber : CarKeyboardHandler() { override val keyboardRes: Int = R.xml.keyboard_car_number } }
0
Kotlin
0
0
a88cff5079338e63d21d3e59e6ac0eeb413294a4
2,801
OkKeyboard
Apache License 2.0
presentation/src/main/java/com/ezzy/presentation/profile/ProfileScreen.kt
EzekielWachira
742,792,801
false
{"Kotlin": 231925}
package com.ezzy.presentation.profile import android.widget.Toast import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.ezzy.designsystem.components.CommonAppBarWithTitle import com.ezzy.designsystem.components.CustomDivider import com.ezzy.designsystem.theme.DarkBlue import com.ezzy.designsystem.utils.DpDimensions import com.ezzy.presentation.R import com.ezzy.presentation.auth.viewmodel.LoginViewModel import com.ezzy.presentation.home.viewmodel.HomeViewModel import com.ezzy.presentation.navigation.Screens import com.ezzy.presentation.profile.components.AccountDetailsSection import com.ezzy.presentation.profile.components.LogoutConfirmationBottomSheet import com.ezzy.presentation.profile.components.LogoutItem import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions @OptIn(ExperimentalMaterial3Api::class) @Composable fun ProfileScreen( navController: NavController, isSystemInDarkMode: Boolean = isSystemInDarkTheme() ) { val systemUiController = rememberSystemUiController() val useDarkIcons = !isSystemInDarkMode val viewModel: HomeViewModel = hiltViewModel() val loginViewModel: LoginViewModel = hiltViewModel() val user by viewModel.firebaseUser.collectAsStateWithLifecycle(initialValue = null) val scrollState = rememberScrollState() val bottomSheetState = rememberModalBottomSheetState() var isLogoutSheetOpen by rememberSaveable { mutableStateOf(false) } val context = LocalContext.current val token = stringResource(id = R.string.web_client_id) val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(token) .requestEmail() .requestProfile() .build() SideEffect { systemUiController.setSystemBarsColor( color = if (useDarkIcons) Color.White else DarkBlue, darkIcons = useDarkIcons ) } Scaffold( topBar = { CommonAppBarWithTitle( title = "Profile", backIcon = R.drawable.back, onBackClick = { navController.popBackStack() } ) } ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .fillMaxSize() ) { Column( modifier = Modifier.fillMaxSize() ) { AccountDetailsSection( modifier = Modifier.fillMaxWidth(), onClick = { }, user = user ) Spacer(modifier = Modifier.height(DpDimensions.Small)) Column( modifier = Modifier .padding(horizontal = DpDimensions.Normal) ) { CustomDivider( text = stringResource(R.string.general), modifier = Modifier.fillMaxWidth() ) LogoutItem( icon = R.drawable.logout, title = stringResource(R.string.logout), modifier = Modifier.fillMaxWidth() ) { isLogoutSheetOpen = true } } } if (isLogoutSheetOpen) { LogoutConfirmationBottomSheet( bottomSheetState = bottomSheetState, onDismiss = { isLogoutSheetOpen = false }, onLogout = { navController.navigate(Screens.Auth.route) { popUpTo(Screens.Main.route) { inclusive = false } }.also { GoogleSignIn.getClient(context, gso) .signOut() .addOnCompleteListener { if (it.isSuccessful) { Toast.makeText(context, "Logged out", Toast.LENGTH_SHORT).show() } } loginViewModel.saveIsLoggedIn(false) } }, onCancel = { isLogoutSheetOpen = false } ) } } } }
0
Kotlin
0
0
4021ffb25fdb7aa82c57bae5de02379c319b19fe
6,001
Tripitaca
MIT License
app/src/main/java/com/app/moodtrack_android/messaging/MessageJobIntentService.kt
martinheitmann
431,879,047
false
{"Kotlin": 272822}
package com.app.moodtrack_android.messaging import android.app.PendingIntent import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Base64 import android.util.Log import androidx.core.app.JobIntentService import androidx.navigation.NavDeepLinkBuilder import com.app.moodtrack_android.R import com.app.moodtrack_android.model.StoredFile import com.app.moodtrack_android.model.notificationquestionnaire.NQNode import com.app.moodtrack_android.model.notificationquestionnaire.query_objects.NotificationQuestionnaireByTimeOfDay import com.app.moodtrack_android.model.notificationquestionnaire.question.NQQuestionChoice import com.app.moodtrack_android.repository.FileRepository import com.google.gson.Gson import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import org.apache.commons.io.FilenameUtils import java.io.IOException import java.util.* import javax.inject.Inject @Deprecated("Service is no longer needed and uses deprecated features.") @AndroidEntryPoint class MessageJobIntentService : JobIntentService() { val TAG = "MessageJobIntentService" private val serviceJob = Job() private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob) @Inject lateinit var gson: Gson @Inject lateinit var fileRepository: FileRepository @Inject lateinit var notificationBuilder: NotificationBuilder override fun onHandleWork(intent: Intent) { serviceScope.launch(Dispatchers.IO) { try { val notificationNode = intent.getSerializableExtra(applicationContext.getString(R.string.notification_node)) as NQNode? val notificationQuestionnaire = intent.getSerializableExtra(applicationContext.getString(R.string.notification_questionnaire)) as NotificationQuestionnaireByTimeOfDay? val messageId = intent.getSerializableExtra(getString(R.string.notification_message_id)) as String val notificationId = generateNotificationId() notificationQuestionnaire?.let { questionnaire -> notificationNode?.let { node -> when (node.data.type) { getString(R.string.in_app_questionnaire) -> { val b = Bundle() b.putString(getString(R.string.notification_node_id), node._id) b.putString( getString(R.string.in_app_questionnaire_id), node.data.appquestionnaire.qid ) val pi = NavDeepLinkBuilder(applicationContext) .setGraph(R.navigation.nav_graph) .setDestination(R.id.questionnaireFragment) .setArguments(b) .createPendingIntent() pi.send() } getString(R.string.question) -> { val notificationData = createNotificationViewData( node, questionnaire, notificationId, messageId ) notificationBuilder.createQuestionNotification( text = node.data.question.questionText, buttons = notificationData, notificationId = notificationId ) } } } } } catch (e: Throwable) { Log.d(TAG, e.stackTraceToString()) } } } private fun generateNotificationId(): Int { return System.currentTimeMillis().toInt() } private suspend fun createNotificationViewData( questionNode: NQNode, questionnaire: NotificationQuestionnaireByTimeOfDay, notificationId: Int, messageId: String ): List<Pair<Bitmap, PendingIntent>> { val pendingIntents = createPendingIntentsForQuestionNode( questionNode, questionnaire, notificationId, messageId ) val bitmaps = getBitmapsForQuestionNode(questionNode) val notificationData = stitchPendingIntentsAndBitmaps(pendingIntents, bitmaps) return notificationData } private fun stitchPendingIntentsAndBitmaps( pendingIntents: List<PendingIntent>, bitmaps: List<Bitmap> ): List<Pair<Bitmap, PendingIntent>> { if (pendingIntents.size == bitmaps.size) { return pendingIntents.mapIndexed { i, pendingIntent -> Pair(bitmaps[i], pendingIntent) } } else throw IOException("Unable to stitch list of different sizes: ${pendingIntents.size}, ${bitmaps.size}") } private fun createPendingIntentsForQuestionNode( questionNode: NQNode, notificationQuestionnaire: NotificationQuestionnaireByTimeOfDay, notificationId: Int, messageId: String ): List<PendingIntent> { return questionNode.data.question.questionChoices.map { createPendingIntentForQuestion( it, questionNode, notificationQuestionnaire, notificationId, messageId ) } } private suspend fun getBitmapsForQuestionNode(questionNode: NQNode): List<Bitmap> { val storedFiles = getStoredFiles(questionNode.data.question.questionChoices) return storedFiles.map { sf -> convertStoredFileToBitmap(sf) } } private suspend fun getStoredFiles(choices: List<NQQuestionChoice>): List<StoredFile> { val fileNames = choices.map { c -> c.choiceIcon } return fileRepository.fetchFiles(fileNames) } private fun convertStoredFileToBitmap(storedFile: StoredFile): Bitmap { try { val filename = storedFile.filename var bitmap: Bitmap? val ext = FilenameUtils.getExtension(filename) // returns file extension // Check since only png, jpg and bmp is supported if (ext == "png" || ext == "jpg") { val data: String = storedFile.data val decodedString: ByteArray = Base64.decode(data, Base64.DEFAULT) val bitmapFromString = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) bitmap = bitmapFromString return bitmap ?: throw IOException("Could not convert bitmap for file with name $filename.") } else { throw IOException("Invalid file format received. Found $ext.") } } catch (e: Throwable) { throw e } } private fun createPendingIntentForQuestion( questionChoice: NQQuestionChoice, questionNode: NQNode, notificationQuestionnaire: NotificationQuestionnaireByTimeOfDay, notificationId: Int, messageId: String ): PendingIntent { if (questionNode.data.type == getString(R.string.question)) { val intent = Intent(applicationContext, MessagingBroadcastReceiver::class.java) val nid = notificationId val icon = questionChoice.choiceIcon val value = questionChoice.choiceValue val type = questionChoice.choiceValueType intent.putExtra(getString(R.string.notification_message_id), messageId) intent.putExtra(getString(R.string.choice_icon), icon) intent.putExtra(getString(R.string.choice_value), value) intent.putExtra(getString(R.string.choice_type), type) intent.putExtra(getString(R.string.notification_id), nid) intent.putExtra(getString(R.string.notification_node), questionNode) intent.putExtra( getString(R.string.notification_questionnaire), notificationQuestionnaire ) intent.setPackage(applicationContext.packageName) return PendingIntent.getBroadcast( application.applicationContext, Random().nextInt(), intent, 0 ) } throw IOException("Invalid NQNode passed: type must be 'question'.") } }
0
Kotlin
1
0
9b774c65c5e99e646c50370f17d97575b07ac46b
8,851
moodtrack-android
MIT License
src/test/kotlin/PredicateTest.kt
solid-resourcepack
822,729,366
false
{"Kotlin": 28644}
import io.github.solid.resourcepack.api.builder.AdvancedResourcePack import io.github.solid.resourcepack.api.builder.config.Predicate import io.github.solid.resourcepack.material.SolidMaterial import net.kyori.adventure.key.Key import team.unnamed.creative.ResourcePack val BOOST_ARROW = Key.key("test", "item/boost_arrow") fun main() { val pack = AdvancedResourcePack(ResourcePack.resourcePack()) pack.apply( Predicate.customModelData(SolidMaterial.from(Key.key("minecraft", "item/stick"))).models(BOOST_ARROW).build() ) val mapper = TestMapper() pack.map( mapper, AdvancedResourcePack.Filters.MINECRAFT_FILTER, { model -> model.key().value().startsWith("item/") }) println(mapper.get(BOOST_ARROW)) }
0
Kotlin
0
2
c9811b294dcb41ae33d39310b2d2212a718fae60
759
solid-api
Apache License 2.0
app/src/main/java/com/fappslab/mbchallenge/application/KoinDeclaration.kt
F4bioo
845,138,188
false
{"Kotlin": 241952}
package com.fappslab.mbchallenge.application import android.app.Application import com.fappslab.mbchallenge.BuildConfig import com.fappslab.mbchallenge.libraries.arch.koin.koinshot.ModuleInitializer import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.KoinApplication import org.koin.core.logger.Level import org.koin.dsl.KoinAppDeclaration import timber.log.Timber object KoinDeclaration { fun get(application: Application): KoinAppDeclaration = { Timber.plant(Timber.DebugTree()) androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE) androidContext(application) setupKoinShot() } private fun KoinApplication.setupKoinShot() { modules(ModuleInitializer.modules.toList()) } }
0
Kotlin
0
0
7c8c26161507ad6f0d521f79eeeab3a65a90bb70
811
MBChallenge
MIT License
sushilib/src/main/java/com/zomato/sushilib/atoms/textviews/SushiTextView.kt
Zomato
453,048,414
false
null
package com.zomato.sushilib.atoms.textviews import android.content.Context import android.content.res.ColorStateList import android.graphics.PorterDuff import android.os.Build import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.annotation.StyleRes import androidx.appcompat.widget.AppCompatTextView import com.zomato.sushilib.R import com.zomato.sushilib.annotations.FontWeight import com.zomato.sushilib.utils.text.TextFormatUtils import com.zomato.sushilib.utils.theme.ResourceThemeResolver.getThemeWrappedContext import com.zomato.sushilib.utils.widgets.DrawableSetters import com.zomato.sushilib.utils.widgets.TextViewUtils open class SushiTextView @JvmOverloads constructor( ctx: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : AppCompatTextView( getThemeWrappedContext(ctx, defStyleRes), attrs, defStyleAttr ), DrawableSetters { @get:FontWeight @setparam:FontWeight var textFontWeight: Int = FontWeight.REGULAR set(value) { field = value setTextAppearance(TextFormatUtils.textFontWeightToTextAppearance(value)) } init { context?.theme?.obtainStyledAttributes( attrs, R.styleable.SushiTextView, defStyleAttr, defStyleRes )?.let { val attrTextFontWeight = it.getInt(R.styleable.SushiTextView_textFontWeight, -1) // Only do this is someone has actually set this attr in xml if (attrTextFontWeight != -1) { textFontWeight = attrTextFontWeight } it.recycle() } TextViewUtils.apply { applyDrawables( attrs, defStyleAttr, currentTextColor, textSize.toInt() ) } } override fun setTextAppearance(resId: Int) { @Suppress("DEPRECATION") super.setTextAppearance(context, resId) } fun setCompoundDrawableColor(color: Int) { compoundDrawables.forEach { d -> d?.setColorFilter(color, PorterDuff.Mode.SRC_IN) } compoundDrawablesRelative.forEach { d -> d?.setColorFilter(color, PorterDuff.Mode.SRC_IN) } } override fun setCompoundDrawableTintList(tintList: ColorStateList?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { super.setCompoundDrawableTintList(tintList) } else { compoundDrawables.forEach { d -> d?.setTintList(tintList) } compoundDrawablesRelative.forEach { d -> d?.setTintList(tintList) } } } }
0
Kotlin
7
93
3e976aa7b8b327826c3154b17b8c373987d0369a
2,709
sushi-ui-android
Apache License 2.0
src/main/kotlin/org/randomcat/agorabot/setup/features/RuleCommands.kt
randomnetcat
291,139,813
false
null
package org.randomcat.agorabot.setup.features import org.randomcat.agorabot.Feature import org.randomcat.agorabot.config.parsing.features.readRuleCommandsConfig import org.randomcat.agorabot.features.rulesCommandsFeature import org.randomcat.agorabot.setup.BotDataPaths fun setupRuleCommandsFeature(paths: BotDataPaths): Feature? { return readRuleCommandsConfig( paths.featureConfigDir.resolve("rule_commands.json"), )?.let { rulesCommandsFeature( ruleIndexUri = it.ruleIndexUri, ) } }
0
Kotlin
2
4
dd8d0317af2830dbac6412c98b108d2f50777a80
536
AgoraBot
MIT License
scientist4k-http-core/src/main/kotlin/com/github/squirrelgrip/scientist4k/http/core/model/ExperimentRequest.kt
SquirrelGrip
247,915,957
true
{"Kotlin": 234965, "JavaScript": 2164, "HTML": 1653, "CSS": 930}
package com.github.squirrelgrip.scientist4k.http.core.model import javax.servlet.http.Cookie import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpSession /** * TODO Handle Headers with multiple values * TODO Handle Cookies */ data class ExperimentRequest( val method: String, val url: String, val protocol: String, val headers: Map<String, String> = emptyMap(), val cookies: Array<Cookie> = emptyArray(), val contentType: String?, val body: ByteArray = ByteArray(0), val session: HttpSession, val parameters: Map<String, Array<String>> = emptyMap(), val uri: String ) { companion object { fun create(inboundRequest: HttpServletRequest): ExperimentRequest { val headers = inboundRequest.headerNames.toList().map { it to inboundRequest.getHeader(it) }.toMap() return ExperimentRequest( inboundRequest.method, getUrl(inboundRequest), inboundRequest.protocol, headers, inboundRequest.cookies ?: emptyArray(), inboundRequest.contentType, inboundRequest.inputStream.readBytes(), inboundRequest.getSession(true), inboundRequest.parameterMap, inboundRequest.requestURI ) } private fun getUrl(inboundRequest: HttpServletRequest): String { val url = StringBuffer("${inboundRequest.requestURI}") if (!inboundRequest.queryString.isNullOrEmpty()) { url.append("?${inboundRequest.queryString}") } return url.toString() } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ExperimentRequest if (method != other.method) return false if (uri != other.uri) return false if (protocol != other.protocol) return false if (headers != other.headers) return false if (parameters != other.parameters) return false if (!cookies.contentEquals(other.cookies)) return false if (!body.contentEquals(other.body)) return false return true } override fun hashCode(): Int { var result = method.hashCode() result = 31 * result + url.hashCode() result = 31 * result + protocol.hashCode() result = 31 * result + headers.hashCode() result = 31 * result + cookies.contentHashCode() result = 31 * result + body.contentHashCode() return result } }
0
Kotlin
0
2
5c88eb2bf0275c1c8ad139a78c9a1222f499ce4e
2,732
Scientist4K
MIT License
src/main/kotlin/com/github/demicod/theoldreader/exception/ApiException.kt
demicod
143,927,260
false
null
package com.github.demicod.theoldreader.exception class ApiException : Exception { constructor(message: String?) : super(message) constructor(message: String?, cause: Throwable?) : super(message, cause) }
0
Kotlin
0
0
7baf031f300ca7c0ecd37b2eb3d7780bf231819f
210
theoldreader
MIT License
app/src/main/java/de/lukasneugebauer/nextcloudcookbook/recipe/data/YieldCalculatorImpl.kt
lneugebauer
397,373,765
false
{"Kotlin": 331000, "Ruby": 2906, "Shell": 255}
package de.lukasneugebauer.nextcloudcookbook.recipe.data import de.lukasneugebauer.nextcloudcookbook.recipe.domain.YieldCalculator import java.text.NumberFormat import java.util.Locale class YieldCalculatorImpl(customLocale: Locale? = null) : YieldCalculator { private val numberFormat = if (customLocale != null) { NumberFormat.getNumberInstance(customLocale) } else { NumberFormat.getNumberInstance() }.apply { minimumFractionDigits = 0 maximumFractionDigits = 2 } override fun isValidIngredientSyntax(ingredient: String): Boolean { val startsWithDoubleHash = ingredient.startsWith(DOUBLE_HASH_PREFIX) val hasValidSyntax = SYNTAX_REGEX.matches(ingredient) val hasMultipleSeparators = MULTIPLE_SEPARATORS_REGEX.matches(ingredient) return startsWithDoubleHash || (hasValidSyntax && !hasMultipleSeparators) } override fun recalculateIngredients( ingredients: List<String>, currentYield: Int, originalYield: Int, ): List<String> { return ingredients.map { ingredient -> if (ingredient.startsWith(DOUBLE_HASH_PREFIX)) return@map ingredient if (originalYield < 1) return@map ingredient val matchResult = FRACTION_REGEX.matchEntire(ingredient) if (matchResult !== null) { val (fractionMatch, wholeNumberPartRaw, numeratorRaw, denominatorRaw) = matchResult.destructured val wholeNumberPart = wholeNumberPartRaw.toDoubleOrNull() ?: 0.0 val numerator = numeratorRaw.toDouble() val denominator = denominatorRaw.toDouble() val decimalAmount = wholeNumberPart + numerator / denominator val newAmount = (decimalAmount / originalYield) * currentYield return@map ingredient.replace(fractionMatch, numberFormat.format(newAmount)) } if (isValidIngredientSyntax(ingredient)) { val possibleUnit = ingredient.split(" ") .firstOrNull() ?.replace(Regex("""[^a-zA-Z]"""), "") ?: "" val amount = ingredient.split(" ") .firstOrNull() ?.split("-") ?.firstOrNull() ?.filter { it.isDigit() || it == ',' || it == '.' } ?.replace(",", ".") ?.toDoubleOrNull() ?: 0.0 val unitAndIngredient = ingredient.split(" ") .drop(1) .joinToString(" ") val newAmount = numberFormat.format((amount / originalYield) * currentYield) return@map "$newAmount$possibleUnit $unitAndIngredient" } ingredient } } companion object { const val DOUBLE_HASH_PREFIX = "## " val MULTIPLE_SEPARATORS_REGEX = Regex("""^-?\d+(?:[.,]\d+){2,}.*""") val FRACTION_REGEX = Regex("""^((\d+\s+)?(\d+)\s*/\s*(\d+)).*""") val SYNTAX_REGEX = Regex("""^\d+(?:\.\d+)?(?:/\d+)?\s?.*$""") } }
14
Kotlin
8
46
ac9a366e030b8420b456d773a152a945d016867f
3,236
nextcloud-cookbook
MIT License
processor-common/src/main/java/boringyuri/processor/common/FileWriter.kt
anton-novikau
252,574,617
false
{"Kotlin": 210266, "Java": 63079, "Shell": 2935}
/* * 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 boringyuri.processor.common import androidx.room.compiler.processing.XFiler import boringyuri.processor.common.base.AbortProcessingException import com.squareup.javapoet.ClassName import com.squareup.javapoet.JavaFile import com.squareup.javapoet.TypeSpec import java.io.IOException class FileWriter(private val logger: Logger, private val xFiler: XFiler) { fun writeSourceFile( className: ClassName, classContent: TypeSpec, xFilerMode: XFiler.Mode ) { try { val javaFile = JavaFile.builder(className.packageName(), classContent) .indent(DEFAULT_INDENTATION) .addFileComment(DEFAULT_FILE_COMMENT) .build() xFiler.write(javaFile, xFilerMode) } catch (e: IOException) { throw AbortProcessingException( logger, null, e, "Could not write generated class $className: ${e.message}" ) } } private companion object { const val DEFAULT_INDENTATION = " " const val DEFAULT_FILE_COMMENT = "Boring YURI generated this code for you. Do not modify!" } }
2
Kotlin
2
12
ff4e4e1436cf0913207271ed0f777aeba810fdc5
1,794
boringYURI
Apache License 2.0
oauth/src/main/java/jp/co/soramitsu/oauth/feature/change/email/model/ChangeEmailState.kt
sora-xor
610,919,196
false
{"Kotlin": 321971}
package jp.co.soramitsu.oauth.feature.change.email.model import jp.co.soramitsu.oauth.feature.verify.model.ButtonState import jp.co.soramitsu.ui_core.component.input.InputTextState data class ChangeEmailState( val inputTextState: InputTextState, val buttonState: ButtonState )
12
Kotlin
1
3
f07bbcd675088bbbc74d6f32487b92768dba5ff2
287
sora-card-android
Apache License 2.0
app/src/main/java/com/aredruss/mangatana/view/media/list/MediaListFragment.kt
Aredruss
344,616,186
false
null
package com.aredruss.mangatana.view.media.list import android.os.Bundle import android.view.View import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.recyclerview.widget.GridLayoutManager import by.kirich1409.viewbindingdelegate.viewBinding import com.aredruss.mangatana.R import com.aredruss.mangatana.data.database.MediaDb import com.aredruss.mangatana.databinding.FragmentMediaListBinding import com.aredruss.mangatana.modo.ScreenCategory import com.aredruss.mangatana.modo.Screens import com.aredruss.mangatana.repo.JikanRepository import com.aredruss.mangatana.view.extensions.changeLayersColor import com.aredruss.mangatana.view.extensions.clear import com.aredruss.mangatana.view.extensions.getColor import com.aredruss.mangatana.view.extensions.getString import com.aredruss.mangatana.view.extensions.hide import com.aredruss.mangatana.view.extensions.hideViews import com.aredruss.mangatana.view.extensions.visible import com.aredruss.mangatana.view.util.BaseFragment import com.github.terrakok.modo.back import com.github.terrakok.modo.forward import com.github.terrakok.modo.replace import com.google.android.material.tabs.TabLayout import org.koin.androidx.viewmodel.ext.android.sharedViewModel class MediaListFragment : BaseFragment(R.layout.fragment_media_list) { private val viewModel: MediaListViewModel by sharedViewModel() private val binding: FragmentMediaListBinding by viewBinding() private val mediaRvAdapter = MediaRvAdapter(this::openMedia) private var mediaType: String = JikanRepository.TYPE_MANGA private var screenCategory = 0 private var isSearch: Boolean = false override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycle.addObserver(viewModel) screenCategory = this.arguments?.getInt(CATEGORY) ?: ScreenCategory.EXPLORE setupViews() setupAction() } override fun setupViews() = with(binding) { setupToolbar() setupTabs() setupRv() setupSearch() loadingAv.changeLayersColor(R.color.colorAccent) } private fun setupAction() { viewModel.getMediaList(mediaType, screenCategory) observeListState() } private fun setupToolbar() = with(binding) { labelTv.text = binding.getString(getFragmentTitle(screenCategory)) backBtn.setOnClickListener { modo.back() } } private fun setupRv() = with(binding) { mediaRv.adapter = mediaRvAdapter mediaRv.itemAnimator = null mediaRv.layoutManager = GridLayoutManager(context, 2) mediaRv.scrollToPosition(0) } private fun setupSearch() = with(binding) { searchIb.setOnClickListener { if (searchSv.isVisible) { searchSv.hide() isSearch = false } else { isSearch = true searchIb.backgroundTintList searchSv.visible() } resolveSearchIbBg() } with(searchSv) { clear() setOnClickListener { isIconified = false } setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { if (!query.isNullOrEmpty()) { viewModel.searchForMedia(query, mediaType) mediaRv.scrollToPosition(0) isSearch = true } else { isSearch = false searchSv.hide() } resolveSearchIbBg() return false } @Suppress("EmptyFunctionBlock") override fun onQueryTextChange(newText: String?): Boolean { return false } }) setOnCloseListener { if (this.query.isNullOrEmpty()) { hide() isSearch = false viewModel.getMediaList(mediaType, screenCategory) mediaRv.scrollToPosition(0) } else { clear() } resolveSearchIbBg() return@setOnCloseListener true } } } private fun setupTabs() = with(binding) { when (viewModel.mediaType) { JikanRepository.TYPE_ANIME -> { mediaType = JikanRepository.TYPE_ANIME mediaTypeTl.getTabAt(1)?.select() } else -> { mediaType = JikanRepository.TYPE_MANGA mediaTypeTl.getTabAt(0)?.select() } } isSearch = false mediaTypeTl.addOnTabSelectedListener( object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab?) { mediaRv.scrollToPosition(0) mediaType = when (tab?.position) { 1 -> JikanRepository.TYPE_ANIME else -> JikanRepository.TYPE_MANGA } if (isSearch) { viewModel.searchForMedia(searchSv.query.toString(), mediaType) } else { viewModel.getMediaList(mediaType, screenCategory) } } override fun onTabUnselected(tab: TabLayout.Tab?) { mediaRv.scrollToPosition(0) } override fun onTabReselected(tab: TabLayout.Tab?) { mediaRv.scrollToPosition(0) } } ) } private fun observeListState() { viewModel.listState.observe( viewLifecycleOwner, { when (it) { is ListState.Loading -> { onLoading() } is ListState.Empty -> { onEmpty() } is ListState.Success -> { onLoaded(it.payload) } is ListState.Error -> { onError(it.error) } } } ) } private fun onLoading() = with(binding) { hideViews(listOf(mediaRv, infoMv, infoActionTv)) loadingAv.visible() } private fun onEmpty() = with(binding) { hideViews(listOf(loadingAv, mediaRv)) infoMv.apply { setIcon(R.drawable.ic_empty_msg) setText(R.string.empty_result_message) visible() } infoActionTv.apply { setText(R.string.media_list_find_new) setOnClickListener(null) setOnClickListener { modo.replace( Screens.MediaList(screenCategory), Screens.MediaList(ScreenCategory.EXPLORE) ) } visible() } } private fun onLoaded(payload: ArrayList<MediaDb>) = with(binding) { hideViews(listOf(loadingAv, infoMv, infoActionTv)) mediaRv.visible() mediaRvAdapter.setMedia(payload) } private fun onError(e: Throwable) = with(binding) { hideViews(listOf(loadingAv, mediaRv)) infoMv.apply { setIcon(R.drawable.ic_error_logo) setText(e.localizedMessage ?: e::class.java.name) visible() } infoActionTv.apply { text = binding.getString(R.string.media_list_reload) setOnClickListener(null) setOnClickListener { viewModel.getMediaList(mediaType, screenCategory) } visible() } } private fun openMedia(id: Long) { viewModel.mediaType = mediaType modo.forward(Screens.MediaInfo(id, mediaType)) } private fun getFragmentTitle(screenCategory: Int): Int { return when (screenCategory) { ScreenCategory.ON_GOING -> R.string.fr_ongoing_title ScreenCategory.BACKLOG -> R.string.fr_backlog_title ScreenCategory.FINISHED -> R.string.fr_finished_title ScreenCategory.EXPLORE -> R.string.fr_explore_title else -> R.string.fr_starred_title } } private fun resolveSearchIbBg() = with(binding) { searchIb.apply { if (isSearch) { setColorFilter(binding.getColor(R.color.colorAccent)) } else { setColorFilter(binding.getColor(R.color.barIconTint)) } } } companion object { private const val CATEGORY = "category" fun create(category: Int) = MediaListFragment().apply { arguments = Bundle().apply { putInt(CATEGORY, category) } } } }
0
Kotlin
2
17
834e540aebde85e31b409d21dc22f8a75527a37f
8,999
Mangatana
Apache License 2.0
app/src/main/java/com/liang/yuanshenalbum/widget/ViewPagerHelper.kt
MoonShadow66
521,549,062
false
null
package com.liang.yuanshenalbum.widget import androidx.viewpager.widget.ViewPager class ViewPagerHelper(private val viewPager: ViewPager) { init { val scroller = VScroller(viewPager.context) val cl = ViewPager::class.java try { //利用反射设置mScroller域为自己定义的WScroller,这里的命名(‘mScroller’)不能随意改 val field = cl.getDeclaredField("mScroller") field.isAccessible = true field[viewPager] = scroller } catch (e: NoSuchFieldException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } } }
0
Kotlin
0
0
e0c4d49d91554955542122f9f9ee582bc3645950
636
YuanShenAlbum
Apache License 2.0
server/src/test/kotlin/io/rippledown/persistence/inmemory/InMemoryVerifiedTextStoreTest.kt
TimLavers
513,037,911
false
{"Kotlin": 940517, "Gherkin": 32098, "Java": 138}
package io.rippledown.persistence.inmemory import io.kotest.matchers.shouldBe import kotlin.test.Test class InMemoryVerifiedTextStoreTest { @Test fun `should store the verified text corresponding to an id`() { with(InMemoryVerifiedTextStore()) { // given get(0) shouldBe null // when put(0, "text") // then get(0) shouldBe "text" } } }
2
Kotlin
0
0
b53def050b700e81e4bbaf53c5715aafdffd2c02
440
OpenRDR
MIT License
nebulosa-retrofit/src/main/kotlin/nebulosa/retrofit/RawAsString.kt
tiagohm
568,578,345
false
{"Kotlin": 2741033, "TypeScript": 513674, "HTML": 249994, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 317}
package nebulosa.retrofit @Target(AnnotationTarget.FUNCTION) annotation class RawAsString
29
Kotlin
2
4
f228706acd2c83397198a7606c0d8fa349213845
91
nebulosa
MIT License
app/src/main/kotlin/com/peecock/ymusic/ui/screens/player/Player.kt
geekeie
852,991,746
false
{"Kotlin": 3810622, "Batchfile": 445}
package com.peecock.ymusic.ui.screens.player import android.annotation.SuppressLint import android.content.ActivityNotFoundException import android.content.Intent import android.media.audiofx.AudioEffect import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.AnimationVector1D import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.SpringSpec import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animateDp import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.DraggableState import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.neverEqualPolicy import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.paint import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.LinearGradientShader import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.media3.common.MediaItem import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi import androidx.media3.exoplayer.offline.Download import androidx.navigation.NavController import coil.compose.AsyncImage import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import com.peecock.ymusic.Database import com.peecock.ymusic.LocalPlayerServiceBinder import com.peecock.ymusic.R import com.peecock.ymusic.enums.BackgroundProgress import com.peecock.ymusic.enums.ColorPaletteMode import com.peecock.ymusic.enums.DurationInSeconds import com.peecock.ymusic.enums.NavRoutes import com.peecock.ymusic.enums.PlayerBackgroundColors import com.peecock.ymusic.enums.PlayerThumbnailSize import com.peecock.ymusic.enums.PopupType import com.peecock.ymusic.enums.UiType import com.peecock.ymusic.models.Info import com.peecock.ymusic.models.Song import com.peecock.ymusic.models.ui.toUiMedia import com.peecock.ymusic.query import com.peecock.ymusic.ui.components.LocalMenuState import com.peecock.ymusic.ui.components.rememberBottomSheetState import com.peecock.ymusic.ui.components.themed.CircularSlider import com.peecock.ymusic.ui.components.themed.ConfirmationDialog import com.peecock.ymusic.ui.components.themed.DefaultDialog import com.peecock.ymusic.ui.components.themed.DownloadStateIconButton import com.peecock.ymusic.ui.components.themed.IconButton import com.peecock.ymusic.ui.components.themed.MiniPlayerMenu import com.peecock.ymusic.ui.components.themed.PlayerMenu import com.peecock.ymusic.ui.components.themed.SecondaryTextButton import com.peecock.ymusic.ui.components.themed.SmartMessage import com.peecock.ymusic.ui.components.themed.animateBrushRotation import com.peecock.ymusic.ui.styling.Dimensions import com.peecock.ymusic.ui.styling.LocalAppearance import com.peecock.ymusic.ui.styling.collapsedPlayerProgressBar import com.peecock.ymusic.ui.styling.dynamicColorPaletteOf import com.peecock.ymusic.ui.styling.favoritesOverlay import com.peecock.ymusic.ui.styling.px import com.peecock.ymusic.utils.BlurTransformation import com.peecock.ymusic.utils.DisposableListener import com.peecock.ymusic.utils.UiTypeKey import com.peecock.ymusic.utils.actionspacedevenlyKey import com.peecock.ymusic.utils.audioFadeIn import com.peecock.ymusic.utils.audioFadeOut import com.peecock.ymusic.utils.backgroundProgressKey import com.peecock.ymusic.utils.colorPaletteModeKey import com.peecock.ymusic.utils.currentWindow import com.peecock.ymusic.utils.disableClosingPlayerSwipingDownKey import com.peecock.ymusic.utils.disablePlayerHorizontalSwipeKey import com.peecock.ymusic.utils.downloadedStateMedia import com.peecock.ymusic.utils.durationTextToMillis import com.peecock.ymusic.utils.effectRotationKey import com.peecock.ymusic.utils.expandedplayerKey import com.peecock.ymusic.utils.expandedplayertoggleKey import com.peecock.ymusic.utils.forceSeekToNext import com.peecock.ymusic.utils.formatAsDuration import com.peecock.ymusic.utils.formatAsTime import com.peecock.ymusic.utils.getBitmapFromUrl import com.peecock.ymusic.utils.getDownloadState import com.peecock.ymusic.utils.isLandscape import com.peecock.ymusic.utils.manageDownload import com.peecock.ymusic.utils.playbackFadeDurationKey import com.peecock.ymusic.utils.playerBackgroundColorsKey import com.peecock.ymusic.utils.playerThumbnailSizeKey import com.peecock.ymusic.utils.positionAndDurationState import com.peecock.ymusic.utils.rememberPreference import com.peecock.ymusic.utils.semiBold import com.peecock.ymusic.utils.shouldBePlaying import com.peecock.ymusic.utils.showButtonPlayerAddToPlaylistKey import com.peecock.ymusic.utils.showButtonPlayerArrowKey import com.peecock.ymusic.utils.showButtonPlayerDownloadKey import com.peecock.ymusic.utils.showButtonPlayerLoopKey import com.peecock.ymusic.utils.showButtonPlayerLyricsKey import com.peecock.ymusic.utils.showButtonPlayerMenuKey import com.peecock.ymusic.utils.showButtonPlayerShuffleKey import com.peecock.ymusic.utils.showButtonPlayerSleepTimerKey import com.peecock.ymusic.utils.showButtonPlayerSystemEqualizerKey import com.peecock.ymusic.utils.showNextSongsInPlayerKey import com.peecock.ymusic.utils.showTotalTimeQueueKey import com.peecock.ymusic.utils.shuffleQueue import com.peecock.ymusic.utils.thumbnail import com.peecock.ymusic.utils.thumbnailTapEnabledKey import com.peecock.ymusic.utils.trackLoopEnabledKey import com.peecock.ymusic.utils.windows import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.math.RoundingMode import kotlin.math.absoluteValue import com.peecock.ymusic.utils.showlyricsthumbnailKey import com.peecock.ymusic.utils.showthumbnailKey import com.peecock.ymusic.utils.visualizerEnabledKey @ExperimentalTextApi @SuppressLint("SuspiciousIndentation", "RememberReturnType") @ExperimentalFoundationApi @ExperimentalAnimationApi @UnstableApi @Composable fun Player( navController: NavController, layoutState: PlayerSheetState, //BottomSheetState, modifier: Modifier = Modifier, shape: RoundedCornerShape = RoundedCornerShape( topStart = 12.dp, topEnd = 12.dp ), onDismiss: () -> Unit, ) { val menuState = LocalMenuState.current //val localSheetState = LocalPlayerSheetState.current //println("mediaItem localsheetstate collapsed ${localSheetState.isCollapsed}") val uiType by rememberPreference(UiTypeKey, UiType.RiMusic) val effectRotationEnabled by rememberPreference(effectRotationKey, true) val playerThumbnailSize by rememberPreference( playerThumbnailSizeKey, PlayerThumbnailSize.Biggest ) var disablePlayerHorizontalSwipe by rememberPreference(disablePlayerHorizontalSwipeKey, false) var showlyricsthumbnail by rememberPreference(showlyricsthumbnailKey, false) val (colorPalette, typography, thumbnailShape) = LocalAppearance.current val binder = LocalPlayerServiceBinder.current binder?.player ?: return var nullableMediaItem by remember { mutableStateOf(binder.player.currentMediaItem, neverEqualPolicy()) } var shouldBePlaying by remember { mutableStateOf(binder.player.shouldBePlaying) } val shouldBePlayingTransition = updateTransition(shouldBePlaying, label = "shouldBePlaying") val playPauseRoundness by shouldBePlayingTransition.animateDp( transitionSpec = { tween(durationMillis = 100, easing = LinearEasing) }, label = "playPauseRoundness", targetValueByState = { if (it) 24.dp else 12.dp } ) var isRotated by rememberSaveable { mutableStateOf(false) } val rotationAngle by animateFloatAsState( targetValue = if (isRotated) 360F else 0f, animationSpec = tween(durationMillis = 200), label = "" ) val visualizerEnabled by rememberPreference(visualizerEnabledKey, false) val playbackFadeDuration by rememberPreference( playbackFadeDurationKey, DurationInSeconds.Disabled ) val context = LocalContext.current binder.player.DisposableListener { object : Player.Listener { override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { nullableMediaItem = mediaItem //println("mediaItem onMediaItemTransition") if (playbackFadeDuration != DurationInSeconds.Disabled) { binder.player.volume = 0f //println("mediaItem volume startFadeIn initial volume ${binder.player.volume}") audioFadeIn(binder.player, playbackFadeDuration.seconds, context) } } override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) { shouldBePlaying = binder.player.shouldBePlaying //println("mediaItem onPlayWhenReadyChanged $playWhenReady") //if (playbackFadeDuration != DurationInSeconds.Disabled) { //} } override fun onPlaybackStateChanged(playbackState: Int) { shouldBePlaying = binder.player.shouldBePlaying //println("mediaItem onPlaybackStateChanged") } } } val mediaItem = nullableMediaItem ?: return val positionAndDuration by binder.player.positionAndDurationState() var timeRemaining by remember { mutableIntStateOf(0) } timeRemaining = positionAndDuration.second.toInt() - positionAndDuration.first.toInt() //println("mediaItem timeRemaining $timeRemaining") if (playbackFadeDuration != DurationInSeconds.Disabled) { val songProgressFloat = ((positionAndDuration.first.toFloat() * 100) / positionAndDuration.second.absoluteValue) .toBigDecimal().setScale(2, RoundingMode.UP).toDouble() //val songProgressInt = songProgressFloat.toInt() if (songProgressFloat in playbackFadeDuration.fadeOutRange && binder.player.shouldBePlaying) { //if (timeRemaining in playbackFadeDuration.fadeOutRange) { //println("mediaItem volume startFadeOut $fadeInOut") audioFadeOut(binder.player, playbackFadeDuration.seconds, context) //fadeInOut = true //startFadeOut(binder, playbackFadeDuration.seconds) //fade = !fade } /* if (songProgressFloat in playbackFadeDuration.fadeInRange && binder.player.shouldBePlaying) { //binder.player.volume = 0f println("mediaItem volume startFadeIn") audioFadeIn(binder.player, playbackFadeDuration.seconds, context) //fadeInOut = false //startFadeIn(binder, playbackFadeDuration.seconds) //fade = !fade } */ //println("mediaItem positionAndDuration $positionAndDuration % ${(positionAndDuration.first.toInt()*100) / positionAndDuration.second.toInt()}") //println("mediaItem progress float $songProgressFloat playbackFadeDuration ${playbackFadeDuration} $fadeInOut") } val windowInsets = WindowInsets.systemBars val horizontalBottomPaddingValues = windowInsets .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom).asPaddingValues() var albumInfo by remember { mutableStateOf(mediaItem.mediaMetadata.extras?.getString("albumId")?.let { albumId -> Info(albumId, null) }) } var artistsInfo by remember { mutableStateOf( mediaItem.mediaMetadata.extras?.getStringArrayList("artistNames")?.let { artistNames -> mediaItem.mediaMetadata.extras?.getStringArrayList("artistIds")?.let { artistIds -> artistNames.zip(artistIds).map { (authorName, authorId) -> Info(authorId, authorName) } } } ) } LaunchedEffect(mediaItem.mediaId) { withContext(Dispatchers.IO) { //if (albumInfo == null) albumInfo = Database.songAlbumInfo(mediaItem.mediaId) //if (artistsInfo == null) artistsInfo = Database.songArtistInfo(mediaItem.mediaId) } } val ExistIdsExtras = mediaItem.mediaMetadata.extras?.getStringArrayList("artistIds")?.size.toString() val ExistAlbumIdExtras = mediaItem.mediaMetadata.extras?.getString("albumId") var albumId = albumInfo?.id if (albumId == null) albumId = ExistAlbumIdExtras //var albumTitle = albumInfo?.name var artistIds = arrayListOf<String>() var artistNames = arrayListOf<String>() artistsInfo?.forEach { (id) -> artistIds = arrayListOf(id) } if (ExistIdsExtras.equals(0) .not() ) mediaItem.mediaMetadata.extras?.getStringArrayList("artistIds")?.toCollection(artistIds) artistsInfo?.forEach { (name) -> artistNames = arrayListOf(name) } if (ExistIdsExtras.equals(0) .not() ) mediaItem.mediaMetadata.extras?.getStringArrayList("artistNames")?.toCollection(artistNames) if (artistsInfo?.isEmpty() == true && ExistIdsExtras.equals(0).not()) { artistsInfo = artistNames.let { artistNames -> artistIds.let { artistIds -> artistNames.zip(artistIds).map { Info(it.second, it.first) } } } } /* //Log.d("mediaItem_pl_mediaId",mediaItem.mediaId) Log.d("mediaItem_player","--- START LOG ARTIST ---") Log.d("mediaItem_player","ExistIdsExtras: $ExistIdsExtras") Log.d("mediaItem_player","metadata artisIds "+mediaItem.mediaMetadata.extras?.getStringArrayList("artistIds").toString()) Log.d("mediaItem_player","variable artisIds "+artistIds.toString()) Log.d("mediaItem_player","variable artisNames pre"+artistNames.toString()) Log.d("mediaItem_player","variable artistsInfo pre "+artistsInfo.toString()) //Log.d("mediaItem_pl_artinfo",artistsInfo.toString()) //Log.d("mediaItem_pl_artId",artistIds.toString()) Log.d("mediaItem_player","--- START LOG ALBUM ---") Log.d("mediaItem_player",ExistAlbumIdExtras.toString()) Log.d("mediaItem_player","metadata albumId "+mediaItem.mediaMetadata.extras?.getString("albumId").toString()) Log.d("mediaItem_player","metadata extra "+mediaItem.mediaMetadata.extras?.toString()) Log.d("mediaItem_player","metadata full "+mediaItem.mediaMetadata.toString()) //Log.d("mediaItem_pl_extrasArt",mediaItem.mediaMetadata.extras?.getStringArrayList("artistNames").toString()) //Log.d("mediaItem_pl_extras",mediaItem.mediaMetadata.extras.toString()) Log.d("mediaItem_player","albumInfo "+albumInfo.toString()) Log.d("mediaItem_player","albumId "+albumId.toString()) Log.d("mediaItem_pl","--- END LOG ---") */ var trackLoopEnabled by rememberPreference(trackLoopEnabledKey, defaultValue = false) var expandedplayer by rememberPreference(expandedplayerKey, false) var likedAt by rememberSaveable { mutableStateOf<Long?>(null) } LaunchedEffect(mediaItem.mediaId) { Database.likedAt(mediaItem.mediaId).distinctUntilChanged().collect { likedAt = it } } var downloadState by remember { mutableStateOf(Download.STATE_STOPPED) } downloadState = getDownloadState(mediaItem.mediaId) // val isLocal by remember { derivedStateOf { mediaItem.isLocal } } var isDownloaded by rememberSaveable { mutableStateOf(false) } isDownloaded = downloadedStateMedia(mediaItem.mediaId) val showButtonPlayerAddToPlaylist by rememberPreference(showButtonPlayerAddToPlaylistKey, true) val showButtonPlayerArrow by rememberPreference(showButtonPlayerArrowKey, false) val showButtonPlayerDownload by rememberPreference(showButtonPlayerDownloadKey, true) val showButtonPlayerLoop by rememberPreference(showButtonPlayerLoopKey, true) val showButtonPlayerLyrics by rememberPreference(showButtonPlayerLyricsKey, true) val expandedplayertoggle by rememberPreference(expandedplayertoggleKey, true) val showButtonPlayerShuffle by rememberPreference(showButtonPlayerShuffleKey, true) val showButtonPlayerSleepTimer by rememberPreference(showButtonPlayerSleepTimerKey, false) val showButtonPlayerMenu by rememberPreference(showButtonPlayerMenuKey, false) val showButtonPlayerSystemEqualizer by rememberPreference( showButtonPlayerSystemEqualizerKey, false ) val disableClosingPlayerSwipingDown by rememberPreference( disableClosingPlayerSwipingDownKey, true ) val showTotalTimeQueue by rememberPreference(showTotalTimeQueueKey, true) val backgroundProgress by rememberPreference( backgroundProgressKey, BackgroundProgress.MiniPlayer ) /* val playlistPreviews by remember { Database.playlistPreviews(PlaylistSortBy.Name, SortOrder.Ascending) }.collectAsState(initial = emptyList(), context = Dispatchers.IO) var showPlaylistSelectDialog by remember { mutableStateOf(false) } */ var isShowingSleepTimerDialog by remember { mutableStateOf(false) } val sleepTimerMillisLeft by (binder?.sleepTimerMillisLeft ?: flowOf(null)) .collectAsState(initial = null) var showCircularSlider by remember { mutableStateOf(false) } var actionspacedevenly by rememberPreference(actionspacedevenlyKey, false) if (isShowingSleepTimerDialog) { if (sleepTimerMillisLeft != null) { ConfirmationDialog( text = stringResource(R.string.stop_sleep_timer), cancelText = stringResource(R.string.no), confirmText = stringResource(R.string.stop), onDismiss = { isShowingSleepTimerDialog = false }, onConfirm = { binder.cancelSleepTimer() //onDismiss() } ) } else { DefaultDialog( onDismiss = { isShowingSleepTimerDialog = false } ) { var amount by remember { mutableStateOf(1) } BasicText( text = stringResource(R.string.set_sleep_timer), style = typography.s.semiBold, modifier = Modifier .padding(vertical = 8.dp, horizontal = 24.dp) ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy( space = 16.dp, alignment = Alignment.CenterHorizontally ), modifier = Modifier .padding(vertical = 10.dp) ) { if (!showCircularSlider) { Box( contentAlignment = Alignment.Center, modifier = Modifier .alpha(if (amount <= 1) 0.5f else 1f) .clip(CircleShape) .clickable(enabled = amount > 1) { amount-- } .size(48.dp) .background(colorPalette.background0) ) { BasicText( text = "-", style = typography.xs.semiBold ) } Box(contentAlignment = Alignment.Center) { BasicText( text = stringResource( R.string.left, formatAsDuration(amount * 5 * 60 * 1000L) ), style = typography.s.semiBold, modifier = Modifier .clickable { showCircularSlider = !showCircularSlider } ) } Box( contentAlignment = Alignment.Center, modifier = Modifier .alpha(if (amount >= 60) 0.5f else 1f) .clip(CircleShape) .clickable(enabled = amount < 60) { amount++ } .size(48.dp) .background(colorPalette.background0) ) { BasicText( text = "+", style = typography.xs.semiBold ) } } else { CircularSlider( stroke = 40f, thumbColor = colorPalette.accent, text = formatAsDuration(amount * 5 * 60 * 1000L), modifier = Modifier .size(300.dp), onChange = { amount = (it * 120).toInt() } ) } } Row( horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier .padding(bottom = 20.dp) .fillMaxWidth() ) { SecondaryTextButton( text = stringResource(R.string.set_to) + " " + formatAsDuration(timeRemaining.toLong()) + " " + stringResource(R.string.end_of_song), onClick = { binder?.startSleepTimer(timeRemaining.toLong()) isShowingSleepTimerDialog = false } ) } Row( horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier .fillMaxWidth() ) { IconButton( onClick = { showCircularSlider = !showCircularSlider }, icon = R.drawable.time, color = colorPalette.text ) IconButton( onClick = { isShowingSleepTimerDialog = false }, icon = R.drawable.close, color = colorPalette.text ) IconButton( enabled = amount > 0, onClick = { binder?.startSleepTimer(amount * 5 * 60 * 1000L) isShowingSleepTimerDialog = false }, icon = R.drawable.checkmark, color = colorPalette.accent ) } } } } var position by remember { mutableIntStateOf(0) } var dynamicColorPalette by remember { mutableStateOf(colorPalette) } val colorPaletteMode by rememberPreference(colorPaletteModeKey, ColorPaletteMode.Dark) val playerBackgroundColors by rememberPreference( playerBackgroundColorsKey, PlayerBackgroundColors.BlurredCoverColor ) val isGradientBackgroundEnabled = playerBackgroundColors == PlayerBackgroundColors.ThemeColorGradient || playerBackgroundColors == PlayerBackgroundColors.CoverColorGradient || playerBackgroundColors == PlayerBackgroundColors.FluidThemeColorGradient || playerBackgroundColors == PlayerBackgroundColors.FluidCoverColorGradient if (playerBackgroundColors == PlayerBackgroundColors.CoverColorGradient || playerBackgroundColors == PlayerBackgroundColors.CoverColor || playerBackgroundColors == PlayerBackgroundColors.FluidCoverColorGradient ) { val isSystemDarkMode = isSystemInDarkTheme() LaunchedEffect(mediaItem.mediaId) { dynamicColorPalette = dynamicColorPaletteOf( getBitmapFromUrl( context, binder.player.currentWindow?.mediaItem?.mediaMetadata?.artworkUri.toString() ), isSystemDarkMode, colorPaletteMode == ColorPaletteMode.PitchBlack ) ?: colorPalette } } /* */ var sizeShader by remember { mutableStateOf(Size.Zero) } val shaderA = LinearGradientShader( Offset(sizeShader.width / 2f, 0f), Offset(sizeShader.width / 2f, sizeShader.height), listOf( dynamicColorPalette.background2, colorPalette.background2, ), listOf(0f, 1f) ) val shaderB = LinearGradientShader( Offset(sizeShader.width / 2f, 0f), Offset(sizeShader.width / 2f, sizeShader.height), listOf( colorPalette.background1, dynamicColorPalette.accent, ), listOf(0f, 1f) ) val shaderMask = LinearGradientShader( Offset(sizeShader.width / 2f, 0f), Offset(sizeShader.width / 2f, sizeShader.height), listOf( //Color.White, colorPalette.background2, Color.Transparent, ), listOf(0f, 1f) ) val brushA by animateBrushRotation(shaderA, sizeShader, 20_000, true) val brushB by animateBrushRotation(shaderB, sizeShader, 12_000, false) val brushMask by animateBrushRotation(shaderMask, sizeShader, 15_000, true) /* */ val (thumbnailSizeDp, thumbnailSizePx) = Dimensions.thumbnails.player.song.let { it to (it - 64.dp).px } val painter = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data( mediaItem.mediaMetadata.artworkUri.thumbnail( thumbnailSizePx ) ) .size(coil.size.Size.ORIGINAL) .transformations( listOf( BlurTransformation( scale = 0.5f, radius = 25 ) ) ) .build() ) //val imageState = painter.state /* OnGlobalRoute { layoutState.collapseSoft() } */ //val onGoToHome = homeRoute::global PlayerSheet( state = layoutState, modifier = modifier, onCollapse = onDismiss, disableDismiss = disableClosingPlayerSwipingDown, onDismiss = { //if (disableClosingPlayerSwipingDown) { //val playerBottomSheetMinHeight = 70.dp //layoutState.snapTo(playerBottomSheetMinHeight) //} else { binder.stopRadio() binder.player.clearMediaItems() //} }, collapsedContent = { /* var deltaX by remember { mutableStateOf(0f) } Row( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.Top, modifier = Modifier .background(colorPalette.background1) //.clip(shape) .fillMaxSize() //.padding(horizontalBottomPaddingValues) //change bottom navigation .drawBehind { if (backgroundProgress == BackgroundProgress.Both || backgroundProgress == BackgroundProgress.MiniPlayer) { drawRect( color = colorPalette.favoritesOverlay, topLeft = Offset.Zero, size = Size( width = positionAndDuration.first.toFloat() / positionAndDuration.second.absoluteValue * size.width, height = size.maxDimension ) ) } /* drawLine( color = colorPalette.textDisabled, start = Offset(x = 0f, y = 1.dp.toPx()), end = Offset(x = size.maxDimension, y = 1.dp.toPx()), strokeWidth = 2.dp.toPx() ) val progress = positionAndDuration.first.toFloat() / positionAndDuration.second.absoluteValue drawLine( color = colorPalette.collapsedPlayerProgressBar, start = Offset(x = 0f, y = 1.dp.toPx()), end = Offset(x = size.width * progress, y = 1.dp.toPx()), strokeWidth = 60.dp.toPx() ) drawLine( color = colorPalette.collapsedPlayerProgressBar, start = Offset(x = 0f, y = 1.dp.toPx()), end = Offset(x = size.width * progress, y = 1.dp.toPx()), strokeWidth = 2.dp.toPx() ) drawCircle( color = colorPalette.collapsedPlayerProgressBar, radius = 3.dp.toPx(), center = Offset(x = size.width * progress, y = 1.dp.toPx()) ) */ } .pointerInput(Unit) { detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> deltaX = dragAmount }, onDragStart = { //Log.d("mediaItemGesture","ondragStart offset ${it}") }, onDragEnd = { if (!disablePlayerHorizontalSwipe) { if (deltaX > 0) { binder.player.seekToPrevious() } else { binder.player.forceSeekToNext() } } } ) } ) { Spacer( modifier = Modifier .width(2.dp) ) Box( contentAlignment = Alignment.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) ) { AsyncImage( model = mediaItem.mediaMetadata.artworkUri.thumbnail(Dimensions.thumbnails.song.px), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .clip(thumbnailShape) .size(48.dp) ) } Column( verticalArrangement = Arrangement.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) .weight(1f) ) { /* minimized player */ BasicText( text = mediaItem.mediaMetadata.title?.toString() ?: "", style = typography.xxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) BasicText( text = mediaItem.mediaMetadata.artist?.toString() ?: "", style = typography.xxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } Spacer( modifier = Modifier .width(2.dp) ) Row( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier .height(Dimensions.collapsedPlayer) ) { IconButton( icon = R.drawable.play_skip_back, color = colorPalette.iconButtonPlayer, onClick = { binder.player.forceSeekToPrevious() if (effectRotationEnabled) isRotated = !isRotated }, modifier = Modifier .rotate(rotationAngle) .padding(horizontal = 2.dp, vertical = 8.dp) .size(24.dp) ) Box( modifier = Modifier .clip(RoundedCornerShape(playPauseRoundness)) .clickable { if (shouldBePlaying) { binder.player.pause() } else { if (binder.player.playbackState == Player.STATE_IDLE) { binder.player.prepare() } binder.player.play() } if (effectRotationEnabled) isRotated = !isRotated } .background(colorPalette.background2) .size(42.dp) ) { Image( painter = painterResource(if (shouldBePlaying) R.drawable.pause else R.drawable.play), contentDescription = null, colorFilter = ColorFilter.tint(colorPalette.iconButtonPlayer), modifier = Modifier .rotate(rotationAngle) .align(Alignment.Center) .size(24.dp) ) } IconButton( icon = R.drawable.play_skip_forward, color = colorPalette.iconButtonPlayer, onClick = { binder.player.forceSeekToNext() if (effectRotationEnabled) isRotated = !isRotated }, modifier = Modifier .rotate(rotationAngle) .padding(horizontal = 2.dp, vertical = 8.dp) .size(24.dp) ) } Spacer( modifier = Modifier .width(2.dp) ) } */ } ) { val windows by remember { mutableStateOf(binder.player.currentTimeline.windows) } var queuedSongs by remember { mutableStateOf<List<Song>>(emptyList()) } LaunchedEffect(Unit, mediaItem.mediaId, windows) { Database.getSongsList( windows.map { it.mediaItem.mediaId } ).collect { queuedSongs = it } } var totalPlayTimes = 0L queuedSongs.forEach { totalPlayTimes += it.durationText?.let { it1 -> durationTextToMillis(it1) }?.toLong() ?: 0 } var isShowingLyrics by rememberSaveable { mutableStateOf(false) } var isShowingStatsForNerds by rememberSaveable { mutableStateOf(false) } var isShowingEqualizer by remember { mutableStateOf(false) } val thumbnailTapEnabled by rememberPreference(thumbnailTapEnabledKey, false) val showNextSongsInPlayer by rememberPreference(showNextSongsInPlayerKey, false) val playerBottomHeight = if (showNextSongsInPlayer) 80.dp else 50.dp //val playerBottomHeight = 0.dp /* val playerBottomSheetState = rememberBottomSheetState( playerBottomHeight + horizontalBottomPaddingValues.calculateBottomPadding(), layoutState.expandedBound ) */ val playerSheetState = rememberPlayerSheetState( playerBottomHeight + horizontalBottomPaddingValues.calculateBottomPadding(), layoutState.expandedBound ) val queueSheetState = rememberBottomSheetState( playerBottomHeight + horizontalBottomPaddingValues.calculateBottomPadding(), layoutState.expandedBound ) val lyricsBottomSheetState = rememberBottomSheetState( 0.dp + horizontalBottomPaddingValues.calculateBottomPadding(), layoutState.expandedBound ) var containerModifier = Modifier /* .padding( windowInsets .only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal) .asPaddingValues() ) */ .padding(bottom = playerSheetState.collapsedBound) if (!isGradientBackgroundEnabled) { if (playerBackgroundColors == PlayerBackgroundColors.BlurredCoverColor) { containerModifier = containerModifier .background(dynamicColorPalette.background1) .paint( painter = painter, contentScale = ContentScale.Crop, sizeToIntrinsics = false ) } else { containerModifier = containerModifier .background( dynamicColorPalette.background1 //colorPalette.background1 ) } } else { when (playerBackgroundColors) { PlayerBackgroundColors.FluidThemeColorGradient, PlayerBackgroundColors.FluidCoverColorGradient -> { containerModifier = containerModifier .onSizeChanged { sizeShader = Size(it.width.toFloat(), it.height.toFloat()) } .drawBehind { drawRect(brush = brushA) drawRect(brush = brushMask, blendMode = BlendMode.DstOut) drawRect(brush = brushB, blendMode = BlendMode.DstAtop) } } else -> { containerModifier = containerModifier .background( Brush.verticalGradient( 0.5f to dynamicColorPalette.background2, 1.0f to colorPalette.background2, //0.0f to colorPalette.background0, //1.0f to colorPalette.background2, startY = 0.0f, endY = 1500.0f ) ) } } } var showthumbnail by rememberPreference(showthumbnailKey, false) val thumbnailContent: @Composable ( //modifier: Modifier ) -> Unit = { //modifier -> KOTLIN 2 var deltaX by remember { mutableStateOf(0f) } //var direction by remember { mutableIntStateOf(-1)} Thumbnail( thumbnailTapEnabledKey = thumbnailTapEnabled, isShowingLyrics = isShowingLyrics, onShowLyrics = { isShowingLyrics = it }, isShowingStatsForNerds = isShowingStatsForNerds, onShowStatsForNerds = { isShowingStatsForNerds = it }, isShowingVisualizer = isShowingEqualizer, onShowEqualizer = { isShowingEqualizer = it }, showthumbnail = showthumbnail, onMaximize = { lyricsBottomSheetState.expandSoft() }, onDoubleTap = { val currentMediaItem = binder.player.currentMediaItem query { if (Database.like( mediaItem.mediaId, if (likedAt == null) System.currentTimeMillis() else null ) == 0 ) { currentMediaItem ?.takeIf { it.mediaId == mediaItem.mediaId } ?.let { Database.insert(currentMediaItem, Song::toggleLike) } } } if (effectRotationEnabled) isRotated = !isRotated }, modifier = modifier .nestedScroll(layoutState.preUpPostDownNestedScrollConnection) .pointerInput(Unit) { detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> deltaX = dragAmount }, onDragStart = { //Log.d("mediaItemGesture","ondragStart offset ${it}") }, onDragEnd = { if (!disablePlayerHorizontalSwipe) { if (deltaX > 0) { binder.player.seekToPreviousMediaItem() //binder.player.forceSeekToPrevious() //Log.d("mediaItem","Swipe to LEFT") } else { binder.player.forceSeekToNext() //Log.d("mediaItem","Swipe to RIGHT") } } } ) } /* **** */ /* .pointerInput(Unit) { detectDragGestures( onDrag = { change, dragAmount -> change.consume() val (x, y) = dragAmount if(abs(x) > abs(y)){ when { x > 0 -> { //right direction = 0 } x < 0 -> { // left direction = 1 } } } else { when { y > 0 -> { // down direction = 2 } y < 0 -> { // up direction = 3 } } } }, onDragEnd = { when (direction) { 0 -> { //right swipe code here if (!disablePlayerHorizontalSwipe) binder.player.seekToPreviousMediaItem() //Log.d("mediaItem","Swipe to RIGHT") } 1 -> { // left swipe code here if (!disablePlayerHorizontalSwipe) binder.player.forceSeekToNext() //Log.d("mediaItem","Swipe to LEFT") } 2 -> { // down swipe code here layoutState.collapseSoft() //Log.d("mediaItem","Swipe to DOWN") } 3 -> { // up swipe code here playerBottomSheetState.expandSoft() //Log.d("mediaItem","Swipe to UP") } } } ) } */ /* **** */ ) } val controlsContent: @Composable ( //modifier: Modifier KOTLIN 2 ) -> Unit = { //modifier -> Controls( navController = navController, onCollapse = onDismiss, expandedplayer = expandedplayer, layoutState = layoutState, media = mediaItem.toUiMedia(positionAndDuration.second), mediaId = mediaItem.mediaId, title = mediaItem.mediaMetadata.title?.toString(), artist = mediaItem.mediaMetadata.artist?.toString(), artistIds = artistsInfo, albumId = albumId, shouldBePlaying = shouldBePlaying, position = positionAndDuration.first, duration = positionAndDuration.second, modifier = modifier, onBlurScaleChange = {} ) } if (isLandscape) { Row( verticalAlignment = Alignment.CenterVertically, modifier = containerModifier .padding(top = 20.dp) ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .weight(0.66f) .padding(bottom = 10.dp) ) { thumbnailContent( /* modifier = Modifier .padding(horizontal = 10.dp) */ ) } controlsContent( /* modifier = Modifier .padding(vertical = 8.dp) .fillMaxHeight() .weight(1f) */ ) } } else { /* var offsetX by remember { mutableStateOf(0f) } var deltaX by remember { mutableStateOf(0f) } var direction by remember { mutableStateOf(-1)} */ Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = containerModifier //.padding(top = 10.dp) .drawBehind { if (backgroundProgress == BackgroundProgress.Both || backgroundProgress == BackgroundProgress.Player) { drawRect( color = colorPalette.favoritesOverlay, topLeft = Offset.Zero, size = Size( width = positionAndDuration.first.toFloat() / positionAndDuration.second.absoluteValue * size.width, height = size.maxDimension ) ) } } /* .pointerInput(Unit) { detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> deltaX = dragAmount }, onDragStart = { //Log.d("mediaItemGesture","ondragStart offset ${it}") }, onDragEnd = { if (!disablePlayerHorizontalSwipe) { if (deltaX > 0) { binder.player.seekToPreviousMediaItem() //binder.player.forceSeekToPrevious() Log.d("mediaItem","Swipe to LEFT") } else { binder.player.forceSeekToNext() Log.d("mediaItem","Swipe to RIGHT") } } } ) } */ ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding( windowInsets .only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal) .asPaddingValues() ) .fillMaxWidth(0.9f) .height(30.dp) ) { if (uiType != UiType.ViMusic) { Image( painter = painterResource(R.drawable.chevron_down), contentDescription = null, colorFilter = ColorFilter.tint(colorPalette.collapsedPlayerProgressBar), modifier = Modifier .clickable { onDismiss() layoutState.collapseSoft() } .rotate(rotationAngle) //.padding(10.dp) .size(24.dp) ) /* IconButton( icon = R.drawable.chevron_down, color = colorPalette.text, enabled = true, onClick = { layoutState.collapseSoft() }, modifier = Modifier //.padding(horizontal = 15.dp) .size(24.dp) ) */ Image( painter = painterResource(R.drawable.app_icon), contentDescription = null, colorFilter = ColorFilter.tint(colorPalette.collapsedPlayerProgressBar), modifier = Modifier .clickable { //onGoToHome() navController.navigate(NavRoutes.home.name) onDismiss() layoutState.collapseSoft() } .rotate(rotationAngle) //.padding(10.dp) .size(24.dp) ) if (!showButtonPlayerMenu) Image( painter = painterResource(R.drawable.ellipsis_vertical), contentDescription = null, colorFilter = ColorFilter.tint(colorPalette.collapsedPlayerProgressBar), modifier = Modifier .clickable { menuState.display { PlayerMenu( navController = navController, onDismiss = menuState::hide, mediaItem = mediaItem, binder = binder, onClosePlayer = { onDismiss() layoutState.collapseSoft() } ) } } .rotate(rotationAngle) //.padding(10.dp) .size(24.dp) ) } } Spacer( modifier = Modifier .height(5.dp) ) Box( contentAlignment = Alignment.Center, modifier = Modifier //.weight(0.5f) .fillMaxHeight(0.55f) ) { thumbnailContent( /* modifier = Modifier .clip(thumbnailShape) .padding( horizontal = playerThumbnailSize.size.dp, vertical = 4.dp, ) */ ) } if (showTotalTimeQueue) Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier ) { Image( painter = painterResource(R.drawable.time), colorFilter = ColorFilter.tint(colorPalette.accent), modifier = Modifier .size(20.dp) .padding(horizontal = 5.dp), contentDescription = "Background Image", contentScale = ContentScale.Fit ) BasicText( text = " ${formatAsTime(totalPlayTimes)}", style = typography.xxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } Spacer( modifier = Modifier .height(10.dp) ) controlsContent( /* modifier = Modifier .padding(vertical = 4.dp) .fillMaxWidth() */ ) } } Queue( navController = navController, layoutState = queueSheetState, content = { val context = LocalContext.current Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxHeight() ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = if (actionspacedevenly) Arrangement.SpaceEvenly else Arrangement.SpaceBetween, //Arrangement.SpaceEvenly, modifier = Modifier //.align(Alignment.Center) //.padding(horizontal = 12.dp) //.fillMaxWidth() .fillMaxSize() //.fillMaxHeight(0.5f) .drawBehind { if (backgroundProgress == BackgroundProgress.Both || backgroundProgress == BackgroundProgress.Player) { drawRect( color = colorPalette.favoritesOverlay, topLeft = Offset.Zero, size = Size( width = positionAndDuration.first.toFloat() / positionAndDuration.second.absoluteValue * size.width, height = size.maxDimension ) ) } } ) { //if (uiType != UiType.ViMusic) { if (showButtonPlayerDownload) DownloadStateIconButton( icon = if (isDownloaded) R.drawable.downloaded else R.drawable.download, color = if (isDownloaded) colorPalette.text else colorPalette.textDisabled, downloadState = downloadState, onClick = { //if (!isLocal) manageDownload( context = context, songId = mediaItem.mediaId, songTitle = mediaItem.mediaMetadata.title.toString(), downloadState = isDownloaded ) }, modifier = Modifier .padding(start = 12.dp) .size(24.dp) ) /* if (showPlaylistSelectDialog) { SelectorDialog( title = stringResource(R.string.playlists), onDismiss = { showPlaylistSelectDialog = false }, showItemsIcon = true, values = playlistPreviews.map { Info( it.playlist.id.toString(), "${it.playlist.name} \n ${it.songCount} ${stringResource(R.string.songs)}" ) }, onValueSelected = { //Log.d("mediaItem", it) var position = 0 query { position = Database.getSongMaxPositionToPlaylist(it.toLong()) } if (position > 0) position++ //Log.d("mediaItemMaxPos", position.toString()) transaction { Database.insert(mediaItem) Database.insert( SongPlaylistMap( songId = mediaItem.mediaId, playlistId = it.toLong(), position = position ) ) } //Log.d("mediaItemPos", "add position $position") showPlaylistSelectDialog = false } ) } */ if (showButtonPlayerAddToPlaylist) IconButton( icon = R.drawable.add_in_playlist, color = colorPalette.text, onClick = { menuState.display { MiniPlayerMenu( navController = navController, onDismiss = menuState::hide, mediaItem = mediaItem, binder = binder, onClosePlayer = { onDismiss() layoutState.collapseSoft() } ) /* PlaylistsItemMenu( navController = navController, modifier = Modifier.fillMaxHeight(0.6f), onDismiss = menuState::hide, onAddToPlaylist = { playlistPreview -> position = playlistPreview.songCount.minus(1) ?: 0 if (position > 0) position++ else position = 0 transaction { Database.insert(mediaItem) Database.insert( SongPlaylistMap( songId = mediaItem.mediaId, playlistId = playlistPreview.playlist.id, position = position + 1 ) ) } }, onGoToPlaylist = { navController.navigate("${NavRoutes.localPlaylist.name}/$it") layoutState.collapseSoft() } ) */ } }, modifier = Modifier //.padding(horizontal = 4.dp) .size(24.dp) ) if (showButtonPlayerLoop) IconButton( icon = R.drawable.repeat, color = if (trackLoopEnabled) colorPalette.text else colorPalette.textDisabled, onClick = { trackLoopEnabled = !trackLoopEnabled if (effectRotationEnabled) isRotated = !isRotated }, modifier = Modifier //.padding(horizontal = 4.dp) .size(24.dp) ) if (showButtonPlayerShuffle) IconButton( icon = R.drawable.shuffle, color = colorPalette.text, enabled = true, onClick = { binder?.player?.shuffleQueue() binder.player.forceSeekToNext() }, modifier = Modifier .size(24.dp), ) if (showButtonPlayerLyrics) IconButton( icon = R.drawable.song_lyrics, color = if (isShowingLyrics) colorPalette.text else colorPalette.textDisabled, enabled = true, onClick = { if (isShowingEqualizer) isShowingEqualizer = !isShowingEqualizer isShowingLyrics = !isShowingLyrics }, modifier = Modifier .size(24.dp), ) if (expandedplayertoggle) IconButton( icon = R.drawable.minmax, color = if (expandedplayer) colorPalette.text else colorPalette.textDisabled, enabled = true, onClick = { expandedplayer = !expandedplayer }, modifier = Modifier .size(20.dp), ) if (visualizerEnabled) IconButton( icon = R.drawable.sound_effect, color = if (isShowingEqualizer) colorPalette.text else colorPalette.textDisabled, enabled = true, onClick = { if (isShowingLyrics) isShowingLyrics = !isShowingLyrics isShowingEqualizer = !isShowingEqualizer }, modifier = Modifier .size(24.dp) ) if (showButtonPlayerSleepTimer) IconButton( icon = R.drawable.sleep, color = if (sleepTimerMillisLeft != null) colorPalette.text else colorPalette.textDisabled, enabled = true, onClick = { isShowingSleepTimerDialog = true }, modifier = Modifier .size(24.dp), ) if (showButtonPlayerSystemEqualizer) { val activityResultLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { } IconButton( icon = R.drawable.equalizer, color = colorPalette.text, enabled = true, onClick = { try { activityResultLauncher.launch( Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL).apply { putExtra( AudioEffect.EXTRA_AUDIO_SESSION, binder.player.audioSessionId ) putExtra( AudioEffect.EXTRA_PACKAGE_NAME, context.packageName ) putExtra( AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC ) } ) } catch (e: ActivityNotFoundException) { SmartMessage( context.resources.getString(R.string.info_not_find_application_audio), type = PopupType.Warning, context = context ) } }, modifier = Modifier .size(20.dp), ) } if (showButtonPlayerArrow) IconButton( icon = R.drawable.chevron_up, color = colorPalette.text, enabled = true, onClick = { queueSheetState.expandSoft() }, modifier = Modifier .padding(end = 12.dp) .size(24.dp), ) if (showButtonPlayerMenu && !isLandscape) IconButton( icon = R.drawable.ellipsis_vertical, color = colorPalette.text, onClick = { menuState.display { PlayerMenu( navController = navController, onDismiss = menuState::hide, mediaItem = mediaItem, binder = binder, onClosePlayer = { onDismiss() layoutState.collapseSoft() } ) } }, modifier = Modifier .padding(end = 12.dp) .size(24.dp) ) if (isLandscape) { IconButton( icon = R.drawable.ellipsis_horizontal, color = colorPalette.text, onClick = { menuState.display { PlayerMenu( navController = navController, onDismiss = menuState::hide, mediaItem = mediaItem, binder = binder, onClosePlayer = { onDismiss() layoutState.collapseSoft() } ) } }, modifier = Modifier .padding(end = 12.dp) .size(24.dp) ) } } if (showNextSongsInPlayer) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(horizontal = 12.dp) .fillMaxWidth() ) { val nextMediaItemIndex = binder.player.nextMediaItemIndex val nextMediaItem = if (binder.player.hasNextMediaItem()) binder.player.getMediaItemAt(binder.player.nextMediaItemIndex) else MediaItem.EMPTY val nextNextMediaItem = try { binder.player.getMediaItemAt(nextMediaItemIndex + 1) } catch (e: Exception) { MediaItem.EMPTY } Box( contentAlignment = Alignment.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) ) { AsyncImage( model = nextMediaItem.mediaMetadata.artworkUri.thumbnail( Dimensions.thumbnails.song.px / 2 ), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .padding(end = 5.dp) .clip(thumbnailShape) .size(30.dp) ) } Column( verticalArrangement = Arrangement.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) .weight(1f) ) { BasicText( text = nextMediaItem.mediaMetadata.title?.toString() ?: "", style = typography.xxxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) BasicText( text = nextMediaItem.mediaMetadata.artist?.toString() ?: "", style = typography.xxxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } Box( contentAlignment = Alignment.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) ) { AsyncImage( model = nextNextMediaItem.mediaMetadata.artworkUri.thumbnail( Dimensions.thumbnails.song.px / 2 ), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .padding(end = 5.dp) .clip(thumbnailShape) .size(30.dp) ) } Column( verticalArrangement = Arrangement.Center, modifier = Modifier .height(Dimensions.collapsedPlayer) .weight(1f) ) { BasicText( text = nextNextMediaItem.mediaMetadata.title?.toString() ?: "", style = typography.xxxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) BasicText( text = nextNextMediaItem.mediaMetadata.artist?.toString() ?: "", style = typography.xxxs.semiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } } } } }, backgroundColorProvider = { colorPalette.background2 }, modifier = Modifier .align(Alignment.BottomCenter), shape = shape ) FullLyricsSheet( layoutState = lyricsBottomSheetState, content = {}, backgroundColorProvider = { colorPalette.background2 }, onMaximize = { lyricsBottomSheetState.collapseSoft() }, onRefresh = { lyricsBottomSheetState.collapse(tween(50)) lyricsBottomSheetState.expand(tween(50)) } ) } } @UnstableApi @Composable fun PlayerSheet( state: PlayerSheetState, disableVerticalDrag: Boolean? = false, disableDismiss: Boolean? = false, modifier: Modifier = Modifier, onDismiss: (() -> Unit)? = null, onCollapse: (() -> Unit)? = null, collapsedContent: @Composable BoxScope.() -> Unit, content: @Composable BoxScope.() -> Unit, ) { val density = LocalDensity.current val windowsInsets = WindowInsets.systemBars val bottomDp = with(density) { windowsInsets.getBottom(density).toDp() } Box( modifier = modifier //change bottom navigation .offset { val y = (state.expandedBound - state.value) //(state.expandedBound - state.value - (Dimensions.collapsedPlayer + bottomDp)) //bottom navigation .roundToPx() .coerceAtLeast(0) IntOffset(x = 0, y = y) } .pointerInput(state) { val velocityTracker = VelocityTracker() detectVerticalDragGestures( onVerticalDrag = { change, dragAmount -> if (disableVerticalDrag == false) { velocityTracker.addPointerInputChange(change) //if (disableDismiss == false) state.dispatchRawDelta(dragAmount) } }, onDragCancel = { velocityTracker.resetTracking() state.snapTo(state.collapsedBound) }, onDragEnd = { if (disableVerticalDrag == false) { val velocity = -velocityTracker.calculateVelocity().y velocityTracker.resetTracking() state.performFling( velocity, if (disableDismiss == false) onDismiss else null ) onCollapse?.invoke() } } ) } .fillMaxSize() ) { if (!state.isCollapsed) { BackHandler(onBack = state::collapseSoft) content() } if (!state.isExpanded && (onDismiss == null || !state.isDismissed)) { Box( modifier = Modifier .graphicsLayer { alpha = 1f - (state.progress * 16).coerceAtMost(1f) } .clickable(onClick = { if (disableVerticalDrag == false) state.expandSoft() }) .fillMaxWidth() .height(state.collapsedBound), content = collapsedContent ) } } } @Stable class PlayerSheetState( draggableState: DraggableState, private val coroutineScope: CoroutineScope, private val animatable: Animatable<Dp, AnimationVector1D>, private val onAnchorChanged: (Int) -> Unit, val collapsedBound: Dp, ) : DraggableState by draggableState { val dismissedBound: Dp get() = animatable.lowerBound!! val expandedBound: Dp get() = animatable.upperBound!! val value by animatable.asState() val isDismissed by derivedStateOf { value == animatable.lowerBound!! } val isCollapsed by derivedStateOf { value == collapsedBound } val isExpanded by derivedStateOf { value == animatable.upperBound } val progress by derivedStateOf { 1f - (animatable.upperBound!! - animatable.value) / (animatable.upperBound!! - collapsedBound) } fun collapse(animationSpec: AnimationSpec<Dp>) { onAnchorChanged(collapsedAnchor) coroutineScope.launch { animatable.animateTo(collapsedBound, animationSpec) } } fun expand(animationSpec: AnimationSpec<Dp>) { onAnchorChanged(expandedAnchor) coroutineScope.launch { animatable.animateTo(animatable.upperBound!!, animationSpec) } } private fun collapse() { collapse(SpringSpec()) } private fun expand() { expand(SpringSpec()) } fun collapseSoft() { collapse(tween(300)) } fun expandSoft() { expand(tween(300)) } fun dismiss() { onAnchorChanged(dismissedAnchor) coroutineScope.launch { animatable.animateTo(animatable.lowerBound!!) } } fun snapTo(value: Dp) { coroutineScope.launch { animatable.snapTo(value) } } fun performFling(velocity: Float, onDismiss: (() -> Unit)?) { if (velocity > 250) { expand() } else if (velocity < -250) { if (value < collapsedBound && onDismiss != null) { dismiss() onDismiss.invoke() } else { collapse() } } else { val l0 = dismissedBound val l1 = (collapsedBound - dismissedBound) / 2 val l2 = (expandedBound - collapsedBound) / 2 val l3 = expandedBound when (value) { in l0..l1 -> { if (onDismiss != null) { dismiss() onDismiss.invoke() } else { collapse() } } in l1..l2 -> collapse() in l2..l3 -> expand() else -> Unit } } } val preUpPostDownNestedScrollConnection get() = object : NestedScrollConnection { var isTopReached = false override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { if (isExpanded && available.y < 0) { isTopReached = false } return if (isTopReached && available.y < 0 && source == NestedScrollSource.Drag) { dispatchRawDelta(available.y) available } else { Offset.Zero } } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { if (!isTopReached) { isTopReached = consumed.y == 0f && available.y > 0 } return if (isTopReached && source == NestedScrollSource.Drag) { dispatchRawDelta(available.y) available } else { Offset.Zero } } override suspend fun onPreFling(available: Velocity): Velocity { return if (isTopReached) { val velocity = -available.y performFling(velocity, null) available } else { Velocity.Zero } } override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity { isTopReached = false return Velocity.Zero } } } const val expandedAnchor = 2 const val collapsedAnchor = 1 const val dismissedAnchor = 0 @Composable fun rememberPlayerSheetState( dismissedBound: Dp, expandedBound: Dp, collapsedBound: Dp = dismissedBound, initialAnchor: Int = dismissedAnchor ): PlayerSheetState { val density = LocalDensity.current val coroutineScope = rememberCoroutineScope() var previousAnchor by rememberSaveable { mutableStateOf(initialAnchor) } return remember(dismissedBound, expandedBound, collapsedBound, coroutineScope) { val initialValue = when (previousAnchor) { expandedAnchor -> expandedBound collapsedAnchor -> collapsedBound dismissedAnchor -> dismissedBound else -> error("Unknown PlayerSheet anchor") } val animatable = Animatable(initialValue, Dp.VectorConverter).also { it.updateBounds(dismissedBound.coerceAtMost(expandedBound), expandedBound) } PlayerSheetState( draggableState = DraggableState { delta -> coroutineScope.launch { animatable.snapTo(animatable.value - with(density) { delta.toDp() }) } }, onAnchorChanged = { previousAnchor = it }, coroutineScope = coroutineScope, animatable = animatable, collapsedBound = collapsedBound ) } }
0
Kotlin
0
0
bcc8e691579ea2c6f04e9287e45056e9fb85c532
92,045
YMusic
Apache License 2.0
src/main/kotlin/com/vvv/engine/service/TriePrefixService.kt
vicol13
530,589,547
false
null
package com.vvv.engine.service import com.vvv.engine.advice.TrackExecutionTime import com.vvv.engine.utils.Trie import com.vvv.engine.utils.WeightedTrie open class TriePrefixService(set: Set<String>) : PrefixService { private val trie: Trie init { this.trie = Trie(set) } @TrackExecutionTime override fun search(prefix: String): List<String> { return this.trie.search(prefix.lowercase()) } } open class WeightedTriePrefixService(map: Map<String, Int>) : PrefixService { private val trie: Trie init { this.trie = WeightedTrie(map) } @TrackExecutionTime override fun search(prefix: String): List<String> { return trie.search(prefix) } }
0
Kotlin
0
1
534a40c5a4c0b02f1935ba4ea976d47cd8c43485
724
search-engine
MIT License
KotlinExample/src/main/kotlin/programmers/basic/Day22/평행/Solution.kt
sangki930
467,437,850
false
{"Kotlin": 110206}
package programmers.basic.Day22.평행 class Solution { fun solution(dots: Array<IntArray>): Int { val x1 = dots[0][0] val y1 = dots[0][1] val x2 = dots[1][0] val y2 = dots[1][1] val x3 = dots[2][0] val y3 = dots[2][1] val x4 = dots[3][0] val y4 = dots[3][1] var answer = 0 var slope1 = (y2 - y1).toDouble() / (x2 - x1) var slope2 = (y4 - y3).toDouble() / (x4 - x3) if (slope1 == slope2) answer = 1 slope1 = (y3 - y1).toDouble() / (x3 - x1) slope2 = (y2 - y4).toDouble() / (x2 - x4) if (slope1 == slope2) answer = 1 slope1 = (y4 - y1).toDouble() / (x4 - x1) slope2 = (y2 - y3).toDouble() / (x2 - x3) if (slope1 == slope2) answer = 1 return answer } }
0
Kotlin
0
0
d8c8599bfe99acd160dadc2f6727a5ae87a1bad0
811
Kotlin
Apache License 2.0
myddd-vertx-media/myddd-vertx-media-domain/src/main/kotlin/org/myddd/vertx/media/domain/MediaRepository.kt
mydddOrg
394,671,816
false
null
package org.myddd.vertx.media.domain import io.vertx.core.Future interface MediaRepository { fun nextId():String? suspend fun queryByMediaId(mediaId:String):Future<Media?> suspend fun queryByDigest(digest:String):Future<Media?> suspend fun saveMedia(media: Media):Future<Media> }
0
Kotlin
0
6
2f03041f4a8984f6acba1f6ec31a22185f0fcb0e
301
myddd-vertx
MIT License
app/src/main/java/ke/co/tulivuapps/hobbyhorsetours/data/di/HotelModule.kt
brendenozie
685,892,586
false
{"Kotlin": 880667}
package ke.co.tulivuapps.hobbyhorsetours.data.di import androidx.compose.runtime.Stable import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import ke.co.tulivuapps.hobbyhorsetours.data.local.dao.HotelDao import ke.co.tulivuapps.hobbyhorsetours.data.remote.api.HotelService import ke.co.tulivuapps.hobbyhorsetours.data.remote.source.HotelRemoteDataSource import ke.co.tulivuapps.hobbyhorsetours.data.remote.source.impl.HotelRemoteDataSourceImpl import ke.co.tulivuapps.hobbyhorsetours.data.repository.HotelRepositoryImpl import ke.co.tulivuapps.hobbyhorsetours.domain.repository.HotelRepository import retrofit2.Retrofit /** * Created by brendenozie on 12.03.2023 */ @Stable @Module @InstallIn(ViewModelComponent::class) class HotelModule { @Provides fun provideHotelService(retrofit: Retrofit): HotelService = retrofit.create(HotelService::class.java) @Provides fun provideHotelRemoteDataSource( hotelService: HotelService, dao: HotelDao ): HotelRemoteDataSource = HotelRemoteDataSourceImpl(hotelService, dao) @Provides fun provideHotelRepository( accountRemoteDataSource: HotelRemoteDataSource, dao: HotelDao ): HotelRepository = HotelRepositoryImpl(accountRemoteDataSource, dao) }
0
Kotlin
0
0
38200eb57d06c4bfb5bbcc607bd2977ecbf2d859
1,352
HobbyHorseToursAndroidApp
The Unlicense
actions/src/main/kotlin/com/alfresco/content/actions/ActionCreateFolder.kt
Alfresco
201,430,708
false
null
package com.alfresco.content.actions import android.content.Context import android.view.View import com.alfresco.content.data.BrowseRepository import com.alfresco.content.data.Entry import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext data class ActionCreateFolder( override var entry: Entry, override val icon: Int = R.drawable.ic_action_create_folder, override val title: Int = R.string.action_create_folder ) : Action { override suspend fun execute(context: Context): Entry { val result = showCreateFolderDialog(context) ?: throw CancellationException("User Cancellation") return BrowseRepository().createFolder(result.name, result.description, entry.id) } private suspend fun showCreateFolderDialog(context: Context) = withContext(Dispatchers.Main) { suspendCoroutine<CreateFolderMetadata?> { CreateFolderDialog.Builder(context) .onSuccess { title, description -> it.resume(CreateFolderMetadata(title, description)) } .onCancel { it.resume(null) } .show() } } override fun copy(_entry: Entry): Action = copy(entry = _entry) override fun showToast(view: View, anchorView: View?) = Action.showToast(view, anchorView, R.string.action_create_folder_toast, entry.name) private data class CreateFolderMetadata( val name: String, val description: String ) }
2
Kotlin
2
3
04da85b580cae72b6c117672f12b2beff0a0de97
1,603
alfresco-mobile-workspace-android
Apache License 2.0
app/src/main/java/com/santansarah/oauthxml/utils/Constants.kt
santansarah
661,455,248
false
null
package com.santansarah.oauthxml.utils import com.santansarah.oauthxml.BuildConfig const val BASE_URL = "https://github.com" const val API_URL = " https://api.github.com" const val AUTH_PATH = "$BASE_URL/login/oauth/authorize" const val TOKEN_PATH = "$BASE_URL/login/oauth/access_token" const val CLIENT_ID = BuildConfig.CLIENT_ID const val CLIENT_SECRET = BuildConfig.CLIENT_SECRET const val REDIRECT_URI = "mycode://signin" const val USER_PATH = "$API_URL/user" const val REPOS_PATH = "$API_URL/user/repos"
0
Kotlin
0
0
d1d05375d283b203baf93ae3d6f5bc3aa29b526a
510
oauth-xml
MIT License
libraries/core/src/main/kotlin/com/bumble/appyx/core/navigation/transition/TransitionDescriptor.kt
bumble-tech
493,334,393
false
null
package com.bumble.appyx.core.navigation.transition import androidx.compose.runtime.Immutable import com.bumble.appyx.core.navigation.Operation @Immutable data class TransitionDescriptor<NavTarget, out State>( val params: TransitionParams, val operation: Operation<NavTarget, out State>, val element: NavTarget, val fromState: State, val toState: State )
68
Kotlin
45
754
1c13ab49fb3e2eb0bcd192332d597f8c05d3f6a9
377
appyx
Apache License 2.0
src/jvmTest/kotlin/org/angproj/crypt/sec/ConversionTest.kt
angelos-project
677,062,617
false
{"Kotlin": 18069186, "Java": 273216}
package org.angproj.crypt.sec import org.angproj.aux.util.BinHex import kotlin.test.Test import kotlin.test.assertContentEquals class ConversionTest { val testPrimeCurve = Secp256Koblitz1 @Test fun octetExport() { val q = testPrimeCurve.domainParameters assertContentEquals(Conversion.integer2octetSting(Integer(q.p), Convention.mlen(q)).value, testPrimeCurve.p.value) assertContentEquals(Conversion.integer2octetSting(Integer(q.a.value), Convention.mlen(q)).value, testPrimeCurve.a.value) assertContentEquals(Conversion.integer2octetSting(Integer(q.b.value), Convention.mlen(q)).value, testPrimeCurve.b.value) assertContentEquals(Conversion.ellipticCurvePoint2octetString(q.G, q, false).value, testPrimeCurve.G.value) assertContentEquals(Conversion.integer2octetSting(Integer(q.n), Convention.mlen(q)).value, testPrimeCurve.n.value) assertContentEquals(Conversion.integer2octetSting(Integer(q.h), 1).value, testPrimeCurve.h.value) } @Test fun octetString2ellipticCurvePoint() { val q = testPrimeCurve.domainParameters val base = Conversion.octetString2ellipticCurvePoint(testPrimeCurve.Gc, q) println(BinHex.encodeToHex(base.x.value.toByteArray())) println(BinHex.encodeToHex(base.y.value.toByteArray())) println() println(BinHex.encodeToHex(q.G.x.value.toByteArray())) println(BinHex.encodeToHex(q.G.y.value.toByteArray())) } }
0
Kotlin
0
0
cf5c860cfa05d6dc0d0d4c0affeec808bf1f0b6a
1,475
angelos-project-crypt
MIT License
app/src/main/java/com/amitghasoliya/notesapp/models/UserRequest.kt
amitghasoliya
767,163,070
false
{"Kotlin": 87342}
package com.amitghasoliya.notesapp.models data class UserRequest( val email: String, val password: String, val username: String ) data class UserDelete( val id: String )
0
Kotlin
0
1
2648ca44c56da974425f9df32374cfd0fef72f72
186
notes_app_kotlin_android
MIT License
BasicAndroidAccessibility-Kotlin/app/src/main/java/com/example/android/server/HelloController.kt
javawww
449,597,516
true
{"Kotlin": 103707, "Java": 20702}
package com.example.android.server import com.yanzhenjie.andserver.annotation.GetMapping import com.yanzhenjie.andserver.annotation.RequestMapping import com.yanzhenjie.andserver.annotation.RestController /** * 测试接口 */ @RestController @RequestMapping(path = ["/hello"]) class HelloController { @GetMapping(path = ["/test"]) fun test():String{ return "Hello World" } }
0
Kotlin
0
0
5275a1e5b415d115ae07d99028280b176e508830
392
android-accessibility
Apache License 2.0
src/test/kotlin/com/jay/monitoring/MonitoringApplicationTests.kt
jay-choe
732,410,644
false
{"Kotlin": 498}
package com.jay.monitoring import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class MonitoringApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
8481b71e5ada87e6798e69322909d0409954f9c3
219
goodmorning
Apache License 2.0
src/main/kotlin/ws/WebSocketServer.kt
paroquet
230,206,935
false
null
package ws class WebSocketServer : SimpleEndPoint() { override fun onOpen(session: Session) { println("Server onOpen") } override fun onMessage(session: Session, message: String) { println("server 收到消息 $message") session.sendText("server 发送消息 hello") } override fun onMessage(session: Session, message: ByteArray, messageLen: Int) { } override fun onClose(session: Session, closeReasonCode: Int, closeReasonPhrase: String) { println("Server onClose") } override fun onError(session: Session, t: Throwable) { println("Server onError") } }
0
Kotlin
1
0
aa438fc6691c3b74e1feafa26e2b117d69b35582
584
websocket-server
MIT License
common/src/commonMain/kotlin/com/aitorgf/threekt/types/Map.kt
tokkenno
276,641,018
false
null
package com.aitorgf.threekt.types import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport @ExperimentalJsExport @JsExport class Map { private var entries: Array<MapEntry> = emptyArray() val size: Int get() = this.entries.size val keys: Array<String> get() = this.entries.map { it.key }.toTypedArray() val values: Array<Any?> get() = this.entries.map { it.value }.toTypedArray() fun containsKey(key: String): Boolean { return this.entries.indexOfFirst { it.key == key } != -1 } fun get(key: String): Any? { val index = this.entries.indexOfFirst { it.key == key } if (index == -1) { return null } else { return this.entries[index].value } } fun getOrDefault(key: String, default: Any): Any { return this.get(key) ?: default } fun set(key: String, value: String) { val index = this.entries.indexOfFirst { it.key == key } if (index == -1) { val tmpSet = entries.toMutableSet() tmpSet.add(MapEntry(key, value)) this.entries = tmpSet.toTypedArray() } else { this.entries[index].value = value } } }
0
Kotlin
0
0
ae7731892ca6784f382c858bf623d68f73819fe9
1,233
threekt
MIT License
src/main/kotlin/protocol/ForConditionKt.kt
i3biscotti
736,031,193
false
{"Kotlin": 627343, "Java": 23218, "ANTLR": 9453, "Dockerfile": 272}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: statements.proto // Generated files should ignore deprecation warnings @file:Suppress("DEPRECATION") package protocol; @kotlin.jvm.JvmName("-initializeforCondition") public inline fun forCondition(block: protocol.ForConditionKt.Dsl.() -> kotlin.Unit): protocol.Statements.ForCondition = protocol.ForConditionKt.Dsl._create(protocol.Statements.ForCondition.newBuilder()).apply { block() }._build() /** * Protobuf type `protocol.ForCondition` */ public object ForConditionKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: protocol.Statements.ForCondition.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: protocol.Statements.ForCondition.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): protocol.Statements.ForCondition = _builder.build() /** * `.protocol.StandardForCondition standardForCondition = 1;` */ public var standardForCondition: protocol.Statements.StandardForCondition @JvmName("getStandardForCondition") get() = _builder.getStandardForCondition() @JvmName("setStandardForCondition") set(value) { _builder.setStandardForCondition(value) } /** * `.protocol.StandardForCondition standardForCondition = 1;` */ public fun clearStandardForCondition() { _builder.clearStandardForCondition() } /** * `.protocol.StandardForCondition standardForCondition = 1;` * @return Whether the standardForCondition field is set. */ public fun hasStandardForCondition(): kotlin.Boolean { return _builder.hasStandardForCondition() } /** * `.protocol.ForEachCondition forEachCondition = 2;` */ public var forEachCondition: protocol.Statements.ForEachCondition @JvmName("getForEachCondition") get() = _builder.getForEachCondition() @JvmName("setForEachCondition") set(value) { _builder.setForEachCondition(value) } /** * `.protocol.ForEachCondition forEachCondition = 2;` */ public fun clearForEachCondition() { _builder.clearForEachCondition() } /** * `.protocol.ForEachCondition forEachCondition = 2;` * @return Whether the forEachCondition field is set. */ public fun hasForEachCondition(): kotlin.Boolean { return _builder.hasForEachCondition() } public val conditionCase: protocol.Statements.ForCondition.ConditionCase @JvmName("getConditionCase") get() = _builder.getConditionCase() public fun clearCondition() { _builder.clearCondition() } } } @kotlin.jvm.JvmSynthetic public inline fun protocol.Statements.ForCondition.copy(block: `protocol`.ForConditionKt.Dsl.() -> kotlin.Unit): protocol.Statements.ForCondition = `protocol`.ForConditionKt.Dsl._create(this.toBuilder()).apply { block() }._build() public val protocol.Statements.ForConditionOrBuilder.standardForConditionOrNull: protocol.Statements.StandardForCondition? get() = if (hasStandardForCondition()) getStandardForCondition() else null public val protocol.Statements.ForConditionOrBuilder.forEachConditionOrNull: protocol.Statements.ForEachCondition? get() = if (hasForEachCondition()) getForEachCondition() else null
0
Kotlin
0
0
bb87f5eff6f424bca654a0f5313ee9d9ce267281
3,531
kotlin2ast-engine
Apache License 2.0
library/generator/src/main/java/io/mehow/laboratory/generator/FeatureFlagModel.kt
boguszpawlowski
387,763,435
true
{"Kotlin": 324311, "Shell": 2768, "HTML": 261, "CSS": 188}
package io.mehow.laboratory.generator import arrow.core.Either import arrow.core.Nel import arrow.core.extensions.either.applicative.applicative import arrow.core.extensions.either.applicative.map import arrow.core.extensions.fx import arrow.core.extensions.list.traverse.traverse import arrow.core.fix import arrow.core.flatMap import arrow.core.getOrElse import arrow.core.left import arrow.core.right import com.squareup.kotlinpoet.ClassName import java.io.File @Suppress("LongParameterList") // All properties are required for code generation. public class FeatureFlagModel internal constructor( internal val visibility: Visibility, internal val className: ClassName, internal val options: Nel<FeatureFlagOption>, internal val source: FeatureFlagModel?, internal val description: String, internal val deprecation: Deprecation?, internal val supervisor: Supervisor?, ) { internal val packageName = className.packageName internal val name = className.simpleName internal val reflectionName = className.reflectionName() public fun generate(file: File): File { FeatureFlagGenerator(this).generate(file) val outputDir = file.toPath().resolve(packageName.replace(".", "/")).toFile() return File(outputDir, "$name.kt") } override fun equals(other: Any?): Boolean = other is FeatureFlagModel && reflectionName == other.reflectionName override fun hashCode(): Int = reflectionName.hashCode() override fun toString(): String = reflectionName public data class Builder( internal val visibility: Visibility, internal val packageName: String, internal val names: List<String>, internal val options: List<FeatureFlagOption>, internal val sourceOptions: List<FeatureFlagOption> = emptyList(), internal val description: String = "", internal val deprecation: Deprecation? = null, internal val supervisor: Supervisor.Builder? = null, ) { internal val fqcn = ClassName(packageName, names).canonicalName public fun build(): Either<GenerationFailure, FeatureFlagModel> { return Either.fx { val packageName = !validatePackageName() val names = !validateName() val options = !validateOptions() val nestedSource = createNestedSource()?.bind() val supervisor = !validateSupervisor() FeatureFlagModel( visibility = visibility, className = ClassName(packageName, names), options = options, source = nestedSource, description = description, deprecation = deprecation, supervisor = supervisor, ) } } private fun validatePackageName(): Either<GenerationFailure, String> { return Either.cond( test = packageName.isEmpty() || packageName.matches(packageNameRegex), ifTrue = { packageName }, ifFalse = { InvalidPackageName(fqcn) } ) } private fun validateName(): Either<GenerationFailure, List<String>> { return names.traverse(Either.applicative()) { name -> Either.cond( test = name.matches(nameRegex), ifTrue = { name }, ifFalse = { InvalidFeatureName(name, fqcn) } ) }.map { listKind -> listKind.fix() } } private fun validateOptions(): Either<GenerationFailure, Nel<FeatureFlagOption>> { return Nel.fromList(options) .toEither { NoFeatureValues(fqcn) } .flatMap(::validateOptionNames) .flatMap(::validateDuplicates) .flatMap(::validateSingleDefault) } private fun validateOptionNames( options: Nel<FeatureFlagOption>, ): Either<GenerationFailure, Nel<FeatureFlagOption>> { val invalidOptions = options.toList().map(FeatureFlagOption::name).filterNot(optionRegex::matches) return Nel.fromList(invalidOptions) .toEither { options } .swap() .mapLeft { InvalidFeatureValues(it, fqcn) } } private fun validateDuplicates( options: Nel<FeatureFlagOption>, ): Either<GenerationFailure, Nel<FeatureFlagOption>> { val duplicates = options.toList().map(FeatureFlagOption::name).findDuplicates() return Nel.fromList(duplicates.toList()) .toEither { options } .swap() .mapLeft { FeatureValuesCollision(it, fqcn) } } private fun validateSingleDefault( options: Nel<FeatureFlagOption>, ): Either<GenerationFailure, Nel<FeatureFlagOption>> { val defaultProblems = options.toList() .filter(FeatureFlagOption::isDefault) .takeIf { it.size != 1 } ?.map(FeatureFlagOption::name) return if (defaultProblems == null) options.right() else Nel.fromList(defaultProblems) .map { MultipleFeatureDefaultValues(it, fqcn) } .getOrElse { NoFeatureDefaultValue(fqcn) } .left() } private fun createNestedSource(): Either<GenerationFailure, FeatureFlagModel>? { return sourceOptions .filterNot { it.name.equals("local", ignoreCase = true) } .takeIf { it.isNotEmpty() } ?.let { options -> val isDefaultValue = options.none(FeatureFlagOption::isDefault) return@let Builder( visibility = visibility, packageName = packageName, names = names + "Source", options = Nel(FeatureFlagOption("Local", isDefaultValue), options).toList(), ) }?.build() } private fun validateSupervisor(): Either<GenerationFailure, Supervisor?> = supervisor?.build() ?.flatMap(::validateSelfSupervision) ?: Either.right(null) private fun validateSelfSupervision( supervisor: Supervisor, ): Either<GenerationFailure, Supervisor> = Either.cond( test = supervisor.featureFlag.className.canonicalName != fqcn, ifTrue = { supervisor }, ifFalse = { SelfSupervision(supervisor.featureFlag.toString()) } ) private companion object { val packageNameRegex = """^(?:[a-zA-Z]+(?:\d*[a-zA-Z_]*)*)(?:\.[a-zA-Z]+(?:\d*[a-zA-Z_]*)*)*${'$'}""".toRegex() val nameRegex = """^[a-zA-Z][a-zA-Z_\d]*""".toRegex() val optionRegex = """^[a-zA-Z][a-zA-Z_\d]*""".toRegex() } } } public fun List<FeatureFlagModel.Builder>.buildAll(): Either<GenerationFailure, List<FeatureFlagModel>> { return traverse(Either.applicative(), FeatureFlagModel.Builder::build) .map { listKind -> listKind.fix() } .flatMap { models -> models.checkForDuplicates(FeaturesCollision::fromFeatures) } } public fun List<FeatureFlagModel>.sourceNames(): List<String> = mapNotNull(FeatureFlagModel::source) .map(FeatureFlagModel::options) .flatMap { it.toList() } .map(FeatureFlagOption::name) public fun List<FeatureFlagModel>.sourceModels(): List<FeatureFlagModel> = mapNotNull(FeatureFlagModel::source)
0
null
0
0
08e0d941c8bb4bc6d137eba4151c49376e3f9578
6,887
laboratory
Apache License 2.0
core/src/commonMain/kotlin/tech/skot/core/SKLogPrinter.kt
skot-framework
235,318,194
false
null
package tech.skot.core expect object SKLogPrinter { fun d(tag:String, message: String) fun i(tag:String, message:String) fun v(tag:String, message:String) fun w(tag:String, message:String) fun e(e:Throwable, tag:String, message:String? = null) }
1
null
4
6
8fcff82c719c9775e63da9c3808817704068cbba
266
skot
Apache License 2.0
app/src/main/java/red/padraig/syncsong/data/SSTrack.kt
Red350
159,534,341
false
null
package red.padraig.syncsong.data import android.graphics.Bitmap import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName import com.spotify.protocol.types.ImageUri // Sync Song Track. An object representing a single track within this app. data class SSTrack( @SerializedName("uri") val uri: String, @SerializedName("name") val name: String, @SerializedName("artist") val artist: String, // Duration of the song in millis. @SerializedName("duration") val duration: Long, // Current position of the track in millis. -1 indicates this field should be ignored. @SerializedName("position") val position: Long = -1L, // User who chose this track. @SerializedName("username") var username: String = "", @Transient val imageUri: ImageUri? = null, @Transient val artwork: Bitmap? = null ) : Parcelable { @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") constructor(parcel: Parcel) : this( uri = parcel.readString(), name = parcel.readString(), artist = parcel.readString(), duration = parcel.readLong(), username = parcel.readString()) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(uri) parcel.writeString(name) parcel.writeString(artist) parcel.writeLong(duration) parcel.writeString(username) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SSTrack> { override fun createFromParcel(parcel: Parcel): SSTrack { return SSTrack(parcel) } override fun newArray(size: Int): Array<SSTrack?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
e7641138612802a3ea66e1632397bedc6edae386
1,840
sync-song-app
MIT License
app/src/main/java/io/add/calendar/domain/DatetimeInference.kt
XinyueZ
200,510,186
false
null
package io.add.calendar.domain import android.content.Context import android.icu.util.Calendar import android.telephony.TelephonyManager import android.util.Log import androidx.core.content.getSystemService import androidx.core.os.LocaleListCompat import androidx.textclassifier.TextClassification import androidx.textclassifier.TextClassificationManager import androidx.textclassifier.TextClassifier import com.google.android.gms.tasks.Task import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage import com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentification import com.google.firebase.ml.naturallanguage.languageid.IdentifiedLanguage import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage.EN import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions import java.util.Date import java.util.Locale const val UND = -1 /** * Factory gives fallback to identify the language to inference. */ typealias FallbackLanguageProvider = () -> String /** * [DatetimeInference] gives English based data&time format inference on [_source]. * [fallbackLanguage] is a factory which gives chance to fallback language-id on [_source]. * Default of [fallbackLanguage] is the language of the user's sim provider. */ class DatetimeInference( context: Context, _source: String, private val fallbackLanguage: FallbackLanguageProvider = { val telephonyManager: TelephonyManager? = context.getSystemService() telephonyManager?.simCountryIso ?: Locale.getDefault().language } ) : IDatetimeInference { private val _adjustedSource: String = _source .trim(',', '#', ';', ' ', '\t', '\n') .replace("\n", "") .replace("\t", "") override val source: String = _adjustedSource private var _sourceLanguageId: Int = UND override var sourceLanguageId: Int get() = _sourceLanguageId set(value) { _sourceLanguageId = value } private lateinit var _translated: String override var translated: String get() = _translated set(value) { _translated = value.replace("at", "") // TODO looking for nice solution, see #10 } override val isAlreadyEnglish: Boolean get() = sourceLanguageId == EN private val textClassificationManager: TextClassificationManager = TextClassificationManager.of(context) private val languageIdentifier: FirebaseLanguageIdentification by lazy { FirebaseNaturalLanguage.getInstance().languageIdentification } private val translator: FirebaseTranslator by lazy { val options = FirebaseTranslatorOptions.Builder() .setSourceLanguage(sourceLanguageId) .setTargetLanguage(EN) .build() FirebaseNaturalLanguage.getInstance().getTranslator(options) } override fun release() { languageIdentifier.close() translator.close() } override suspend fun getResult(): Calendar? = doClassificationBeforeTranslation(source) ?: doTranslationBeforeClassification(source) override suspend fun doTranslationBeforeClassification(text: String): Calendar? { findLanguageId(text) translate(text) /** * Pass translated [text], no more translation more in the [buildResult]. */ return buildResult(translated, false) } override suspend fun doClassificationBeforeTranslation(text: String): Calendar? { /** * The text will be passed, let [buildResult] do translation before creating [Calendar]. */ return buildResult(text, true) } override suspend fun findLanguageId(text: String, supportFallback: Boolean) { Log.d("+Calendar", "classification finding lang-id on: $text") val searchingLanguageId: Task<MutableList<IdentifiedLanguage>> = languageIdentifier.identifyPossibleLanguages(text) while (!searchingLanguageId.isComplete) continue searchingLanguageId.result?.let { langCodeList -> val langCode: IdentifiedLanguage? = langCodeList.maxBy { it.confidence } sourceLanguageId = langCode?.let { FirebaseTranslateLanguage.languageForLanguageCode(it.languageCode) } ?: UND } ?: run { sourceLanguageId = UND } if (supportFallback) { supportFallbackLanguageIdIfNeeded() } } override suspend fun supportFallbackLanguageIdIfNeeded() { if (sourceLanguageId == UND) { sourceLanguageId = FirebaseTranslateLanguage.languageForLanguageCode(fallbackLanguage()) ?: UND Log.d("+Calendar", "classification fallback lang: $fallbackLanguage") Log.d("+Calendar", "classification fallback lang-id: $sourceLanguageId") } else Log.d("+Calendar", "classification lang-id: $sourceLanguageId") } override suspend fun translate(text: String) { if (sourceLanguageId == UND) { Log.d( "+Calendar", "classification avoid translating: $text, cannot detect language" ) translated = text return } if (isAlreadyEnglish) { Log.d( "+Calendar", "classification avoid translating: $text, detect English: $isAlreadyEnglish" ) translated = text return } Log.d("+Calendar", "classification translating: $text") val download = translator.downloadModelIfNeeded() while (!download.isComplete) continue val translating = translator.translate(text) while (!translating.isComplete) continue translated = translating.result ?: text Log.d("+Calendar", "classification translated: $translated") } override fun createTextClassification(text: String): TextClassification { val classifier: TextClassifier = textClassificationManager.textClassifier val builder: TextClassification.Request.Builder = TextClassification.Request .Builder(text, 0, text.length) .setDefaultLocales( LocaleListCompat.getAdjustedDefault() ) return classifier.classifyText(builder.build()) } override suspend fun buildResult(text: String, needTranslation: Boolean): Calendar? { try { val calendar = Calendar.getInstance() val classification: TextClassification = createTextClassification(text) if (classification.entityTypeCount < 1) return null val entity: String = classification.getEntityType(0) val score: Float = classification.getConfidenceScore(entity) Log.d("+Calendar", "classification Entity: $entity") Log.d("+Calendar", "classification Score: $score") return if (entity == TextClassifier.TYPE_DATE || entity == TextClassifier.TYPE_DATE_TIME) { calendar.apply { if (needTranslation) { Log.d("+Calendar", "classification need translating: $needTranslation") findLanguageId(text) translate(text) } @Suppress("DEPRECATION") timeInMillis = Date.parse(translated) // timeInMillis = valueOf(LocalDateTime.parse(translated, DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(Locale.ENGLISH)).toString()).toString().toLong() } } else null } catch (ex: Exception) { return null } } }
1
Kotlin
0
0
a037ddedd8886193e62698eb38f56ef00679e321
7,906
AddCalendar
Apache License 2.0
src/main/kotlin/com/navelplace/jsemver/Exceptions.kt
BrianDeacon
126,040,923
false
{"Kotlin": 98222, "ANTLR": 3616}
package com.navelplace.jsemver /** * @suppress */ open class SemverException(message: String): RuntimeException(message) /** * @suppress */ class InvalidVersionFormatException(val format: String): SemverException("Invalid version format: $format") /** * @suppress */ open class InvalidRequirementFormatException(message: String): SemverException(message)
1
Kotlin
1
0
cc2d54102b1fa4c95529b30df6fd71f3111f2c48
366
jsemver
Apache License 2.0
app/src/main/java/com/notesync/notes/framework/dataSource/cache/implementation/AuthDaoServiceImpl.kt
AgarwalsRahul
410,538,003
false
{"Kotlin": 427137, "JavaScript": 1559, "Shell": 739}
package com.notesync.notes.framework.dataSource.cache.implementation import com.notesync.notes.business.domain.model.User import com.notesync.notes.framework.dataSource.cache.abstraction.AuthDaoService import com.notesync.notes.framework.dataSource.cache.database.AuthDao import com.notesync.notes.framework.dataSource.cache.mappers.UserMapper import javax.inject.Inject class AuthDaoServiceImpl @Inject constructor( private val authDao: AuthDao, private val userMapper: UserMapper ) : AuthDaoService { override suspend fun setUser(user: User): Long { return authDao.setUser(userMapper.mapToEntity(user,null)) } override suspend fun retrieveUser(email: String): User? { return authDao.retrieveUser(email)?.let { userMapper.mapFromEntity(it,null) } } override suspend fun deleteUser(id: String): Int { return authDao.deleteUser(id) } }
0
Kotlin
2
5
9b4c16efffcb3dfe314a2f45c4ffae318717e05f
914
Sync-Note
Apache License 2.0
compose/src/main/kotlin/startup/KtlCncInitializer.kt
85vmh
543,628,296
false
null
package startup import app.Files import com.mindovercnc.linuxcnc.CncInitializer import mu.KotlinLogging import okio.FileSystem object KtlCncInitializer { fun initialise() { val appDir = Files.appDir FileSystem.SYSTEM.createDirectories(appDir) println(appDir) logger.info { "Created appDir $appDir" } CncInitializer(appDir.toFile()) } private val logger = KotlinLogging.logger("ktlcnc") }
0
Kotlin
1
2
ed1002352f1a9b437869b560510365e1467d6b8c
444
mindovercnclathe
Apache License 2.0
infrastructure/src/main/kotlin/com/lukinhasssss/catalogo/infrastructure/graphql/GenreGraphQLController.kt
Lukinhasssss
643,341,523
false
{"Kotlin": 451959, "Dockerfile": 1593, "Shell": 492}
package com.lukinhasssss.catalogo.infrastructure.graphql import com.lukinhasssss.catalogo.application.genre.list.ListGenreUseCase import com.lukinhasssss.catalogo.application.genre.save.SaveGenreUseCase import com.lukinhasssss.catalogo.infrastructure.configuration.security.Roles import com.lukinhasssss.catalogo.infrastructure.genre.GqlGenrePresenter import com.lukinhasssss.catalogo.infrastructure.genre.models.GqlGenre import com.lukinhasssss.catalogo.infrastructure.genre.models.GqlGenreInput import org.springframework.graphql.data.method.annotation.Argument import org.springframework.graphql.data.method.annotation.MutationMapping import org.springframework.graphql.data.method.annotation.QueryMapping import org.springframework.security.access.annotation.Secured import org.springframework.stereotype.Controller @Controller class GenreGraphQLController( private val listGenreUseCase: ListGenreUseCase, private val saveGenreUseCase: SaveGenreUseCase ) { @QueryMapping @Secured(Roles.ADMIN, Roles.GENRES, Roles.SUBSCRIBER) fun genres( @Argument search: String, @Argument page: Int, @Argument perPage: Int, @Argument sort: String, @Argument direction: String, @Argument categories: Set<String> = setOf() ): List<GqlGenre> { val input = ListGenreUseCase.Input( page = page, perPage = perPage, terms = search, sort = sort, direction = direction, categories = categories ) return listGenreUseCase.execute(input).map(GqlGenrePresenter::present).data } @MutationMapping @Secured(Roles.ADMIN, Roles.GENRES, Roles.SUBSCRIBER) fun saveGenre(@Argument(name = "input") input: GqlGenreInput): SaveGenreUseCase.Output = saveGenreUseCase.execute(input.toSaveGenreInput()) }
1
Kotlin
0
0
61d76ebbef228a97363bffdab78180014a836696
1,863
catalogo-de-videos
MIT License
features/core/thread/lib/src/main/java/com/ruslan/hlushan/core/thread/ThreadChecker.kt
game-x50
361,364,864
false
null
package com.ruslan.hlushan.core.thread interface ThreadChecker { val isNeededThread: Boolean } fun ThreadChecker.checkThread() = check(this.isNeededThread)
22
Kotlin
0
0
159a035109fab5cf777dd7a60f142a89f441df63
162
android_client_app
Apache License 2.0
src/main/java/com/dystopia/api/provider/DiffProvider.kt
tseylerd
120,107,315
false
null
package com.dystopia.api.provider interface DiffProvider<E> { fun different(first: E, second: E): E fun same(element: E): E }
0
Kotlin
0
0
b85deba8b0517f1a32a6770225384d48651fc534
134
dystopia-model
Apache License 2.0
app/src/main/java/com/rafay/notes/domain/models/LocalProfile.kt
rafayali
200,348,454
false
null
package com.rafay.notes.domain.models /** * Data class for storing loggedIn user profile information */ data class LocalProfile( val firstName: String, val lastName: String?, val email: String, val dob: String )
10
Kotlin
2
7
42a177ca833567ec403f59b553e2de2813a88def
231
notes
Apache License 2.0
adapters/adapter-coroutines/src/commonMain/kotlin/com/divpundir/mavlink/adapters/coroutines/IoDispatcher.kt
divyanshupundir
484,943,163
false
{"Kotlin": 2961421}
package com.divpundir.mavlink.adapters.coroutines import kotlinx.coroutines.CoroutineDispatcher internal expect val IoDispatcher: CoroutineDispatcher
1
Kotlin
7
48
647efb2f1a1d00ae410a0a5ad08e2111fe17214e
152
mavlink-kotlin
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmodes/NewDriveToTag.kt
GearUp12499-org
630,593,823
true
{"Java Properties": 1, "PowerShell": 1, "Shell": 1, "Markdown": 11, "Batchfile": 1, "Gradle Kotlin DSL": 1, "Kotlin": 40, "Java": 87, "Python": 1, "INI": 1}
package org.firstinspires.ftc.teamcode.opmodes import android.util.Log import android.util.Size import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import dev.aether.collaborative_multitasking.MultitaskScheduler import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName import org.firstinspires.ftc.teamcode.Var import org.firstinspires.ftc.teamcode.configurations.RobotConfiguration import org.firstinspires.ftc.teamcode.odo.AprilTagUpdateTool import org.firstinspires.ftc.teamcode.odo.ControlRamps import org.firstinspires.ftc.teamcode.odo.OdoTracker import org.firstinspires.ftc.teamcode.tagPositions import org.firstinspires.ftc.teamcode.utilities.Move import org.firstinspires.ftc.teamcode.utilities.Pose import org.firstinspires.ftc.teamcode.utilities.Vector2 import org.firstinspires.ftc.teamcode.utilities.degrees import org.firstinspires.ftc.teamcode.utilities.inches import org.firstinspires.ftc.teamcode.utilities.typedGet import org.firstinspires.ftc.vision.VisionPortal import org.firstinspires.ftc.vision.apriltag.AprilTagGameDatabase import org.firstinspires.ftc.vision.apriltag.AprilTagProcessor import kotlin.math.sqrt @TeleOp class NewDriveToTag : LinearOpMode() { private var portal: VisionPortal? = null private var aprilTag: AprilTagProcessor? = null companion object { private val tagOffset = Vector2(0.0, -20.0) val tagTargets = mapOf( 1 to tagPositions[1]!! + tagOffset, 2 to tagPositions[2]!! + tagOffset, 3 to tagPositions[3]!! + tagOffset, ) val xOkWithin = 1.inches val yOkWithin = 6.inches val yOkPreciseWithin = 1.inches const val ROBOT_SIZE = 20.794 // in val ramp = ControlRamps( 0.2, 0.4, 0.0, 24.0 ) } override fun runOpMode() { val scheduler = MultitaskScheduler() val robot = RobotConfiguration.currentConfiguration()(hardwareMap) initVisionPortal(hardwareMap.typedGet("Webcam 1")) val tagMotion = AprilTagUpdateTool(aprilTag!!, 2) val odo = OdoTracker(robot, Var.AutoPositions.BlueLeft) val motors = robot.driveMotors() scheduler.task(odo.taskFactory) val toolTask = scheduler.task(tagMotion.updateTool(odo)) scheduler.task { +robot.driveMotorLock val target = Pose(tagTargets[2]!! + tagOffset, (-90.0).degrees) onTick { -> // if (!tagMotion.acquired) return@onTick val pose = odo.currentPose telemetry.addData("current est", pose) telemetry.addData("target", target) // This turns the From pose and the To pose into a Move. // THIS IS THE PROBLEM PART. // vvvvvv val fromTo = pose.toPose(target) telemetry.addData("from/to", fromTo) // Pythagorean theorem. val distance = sqrt( fromTo.forward.value * fromTo.forward.value + fromTo.right.value * fromTo.right.value ) // THIS IS THE PROBLEM PART. (2) // vvvvvvvvv val motion = fromTo.getSpeeds(ROBOT_SIZE) * ramp.ramp(0.0, distance) telemetry.addData("speeds", motion) val correctedMotion = motion.map(Move::rampSpeedToPower) telemetry.addData("powers", correctedMotion) correctedMotion.apply(motors) telemetry.update() Log.i( "NewDriveToTag", String.format( "Current est: %s\nTarget : %s\nFrom/To : %s\nSpeeds : %s\nPowers : %s", pose, target, fromTo, motion, correctedMotion ) ) } isCompleted { -> (odo.currentPose.x - target.x).abs < xOkWithin && (odo.currentPose.y - target.y).abs < yOkPreciseWithin } onFinish { -> motors.setAll(0.0) } } waitForStart() if (!opModeIsActive()) return scheduler.runToCompletion(::opModeIsActive) while (opModeIsActive()) { sleep(20) } } private fun initVisionPortal(webcam: WebcamName) { aprilTag = AprilTagProcessor.Builder() .setDrawAxes(true) .setDrawCubeProjection(true) .setDrawTagOutline(true) .setTagFamily(AprilTagProcessor.TagFamily.TAG_36h11) .setTagLibrary(AprilTagGameDatabase.getCenterStageTagLibrary()) //.setOutputUnits(DistanceUnit.INCH, AngleUnit.DEGREES) .build() val visionPortalBuilder = VisionPortal.Builder() visionPortalBuilder.setCamera(webcam) // Medium-sized 16:9ish. See-also builtinwebcamcalibrations.xml // Logitech HD Pro Webcam C920 // use Search Anything in "include non-project" mode to find visionPortalBuilder.setCameraResolution(Size(864, 480)) visionPortalBuilder.addProcessor(aprilTag) portal = visionPortalBuilder.build() } }
0
Java
0
0
f85006b20d52b775478100c6752466a6cbcf0dec
5,352
GearUp2023-4
BSD 3-Clause Clear License
giokit/src/main/java/com/growingio/giokit/utils/SdkV3InfoUtils.kt
gflkdns
605,931,859
true
{"Java Properties": 2, "Gradle": 13, "Shell": 3, "Markdown": 1, "Batchfile": 1, "Ignore List": 7, "INI": 6, "Proguard": 5, "Java": 105, "XML": 127, "YAML": 2, "Kotlin": 106, "JavaScript": 1}
package com.growingio.giokit.utils import android.app.Activity import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.content.res.Resources import android.os.Build import com.growingio.android.sdk.TrackerContext import com.growingio.android.sdk.autotrack.AutotrackConfig import com.growingio.android.sdk.autotrack.IgnorePolicy import com.growingio.android.sdk.autotrack.page.PageProvider import com.growingio.android.sdk.track.events.AutotrackEventType import com.growingio.android.sdk.track.events.TrackEventType import com.growingio.android.sdk.track.events.helper.EventExcludeFilter import com.growingio.android.sdk.track.events.helper.FieldIgnoreFilter import com.growingio.android.sdk.track.middleware.http.EventEncoder import com.growingio.android.sdk.track.providers.ConfigurationProvider import com.growingio.android.sdk.track.providers.DeviceInfoProvider import com.growingio.android.sdk.track.providers.SessionProvider import com.growingio.android.sdk.track.providers.UserInfoProvider import com.growingio.giokit.hook.GioPluginConfig import com.growingio.giokit.launch.sdkinfo.SdkInfo import org.json.JSONException import org.json.JSONObject /** * <p> * * @author cpacm 2021/8/26 */ object SdkV3InfoUtils { //获取 sdk 信息 fun getSdkInfo(): List<SdkInfo> { val list = arrayListOf<SdkInfo>() list.add(SdkInfo("GrowingIO SDK信息", isHeader = true)) val hasDepend = hasClass("com.growingio.android.sdk.track.providers.ConfigurationProvider") if (hasDepend) { val (_, sdkVersion, _) = GioPluginConfig.analyseDepend() list.tryAdd { SdkInfo("SDK版本", sdkVersion) } list.tryAdd { SdkInfo("项目ID", ConfigurationProvider.core().projectId) } list.tryAdd { SdkInfo("URLScheme", ConfigurationProvider.core().urlScheme) } val checkItem = CheckSdkStatusManager.getInstance().getDataSourceID(0) list.tryAdd { SdkInfo("DataSource ID", checkItem.content) } list.tryAdd { SdkInfo( "DataServerHost", ConfigurationProvider.core().dataCollectionServerHost ) } list.tryAdd { SdkInfo( "数据收集", if (ConfigurationProvider.core().isDataCollectionEnabled) "打开" else "关闭" ) } list.tryAdd { SdkInfo( "Debug测试", if (ConfigurationProvider.core().isDebugEnabled) "是" else "否" ) } list.tryAdd { SdkInfo( "集成模块", CheckSdkStatusManager.getInstance().getSdkModules(0).content ) } list.tryAdd { SdkInfo("分发渠道", ConfigurationProvider.core().channel) } list.tryAdd { SdkInfo( "每日流量限制", ConfigurationProvider.core().cellularDataLimit.toString() + "M" ) } list.tryAdd { SdkInfo( "数据发送间隔", ConfigurationProvider.core().dataUploadInterval.toString() + "S" ) } list.tryAdd { SdkInfo( "访问会话时长", ConfigurationProvider.core().sessionInterval.toString() + "S" ) } list.tryAdd { SdkInfo("事件过滤", getExcludeEvent()) } list.tryAdd { SdkInfo("事件属性过滤", getIgnoreFiled()) } val scale = getImpressionScale() if (scale >= 0F) list.tryAdd { SdkInfo("曝光比例", scale.toString()) } list.tryAdd { SdkInfo("数据加密", getEncryptEnabled()) } list.tryAdd { SdkInfo("登录账户", getLoginUser()) } list.tryAdd { SdkInfo("位置信息", getLocation()) } list.tryAdd { SdkInfo("设备ID", DeviceInfoProvider.get().deviceId) } } else { list.add(SdkInfo("SDK", "SDK未集成")) } return list } private fun getEncryptEnabled(): String { if (TrackerContext.get().registry.getModelLoader(EventEncoder::class.java) != null) { return "启用" } return "未启用" } private fun getExcludeEvent(): String { val excludeEventMask = ConfigurationProvider.core().excludeEvent val events = EventExcludeFilter.getEventFilterLog(excludeEventMask) if (events.isNullOrEmpty()) return "未设置" return events.substringAfter("[").substringBefore("]") } private fun getIgnoreFiled(): String { val ignoreMask = ConfigurationProvider.core().ignoreField val fields = FieldIgnoreFilter.getFieldFilterLog(ignoreMask) if (fields.isNullOrEmpty()) return "未设置" return fields.substringAfter("[").substringBefore("]") } private fun getImpressionScale(): Float { if (hasClass("com.growingio.android.sdk.autotrack.AutotrackConfig")) { val config = ConfigurationProvider.get() .getConfiguration<AutotrackConfig>(AutotrackConfig::class.java) return config.impressionScale } return -1F } private fun getLoginUser(): String { if (hasClass("com.growingio.android.sdk.track.providers.UserInfoProvider")) { val userId = UserInfoProvider.get().loginUserId return if (userId.isNullOrEmpty()) "未配置" else userId } return "未配置" } private fun getLocation(): String { if (hasClass("com.growingio.android.sdk.track.providers.SessionProvider")) { val la = SessionProvider.get().latitude val lo = SessionProvider.get().longitude if (la == 0.0 && lo == 0.0) return "未配置" return "$la,$lo" } return "未配置" } private fun hasClass(className: String): Boolean { try { Class.forName(className) return true } catch (e: ClassNotFoundException) { return false } } fun getAppInfo(context: Context): List<SdkInfo> { val list = arrayListOf<SdkInfo>() val pi = getPackageInfo(context) if (pi != null) { list.add(SdkInfo("App信息", isHeader = true)) list.add(SdkInfo("包名", pi.packageName)) list.add(SdkInfo("应用版本名", pi.versionName)) list.add(SdkInfo("应用版本号", pi.versionCode.toString())) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { list.add(SdkInfo("最低系统版本号", context.applicationInfo.minSdkVersion.toString())) } list.add(SdkInfo("目标系统版本号", context.applicationInfo.targetSdkVersion.toString())) } return list } private fun getPackageInfo(context: Context): PackageInfo? { var pi: PackageInfo? = null try { val pm = context.packageManager pi = pm.getPackageInfo( context.packageName, PackageManager.GET_CONFIGURATIONS ) } catch (e: Exception) { e.printStackTrace() } return pi } fun getMobileInfo(context: Context): List<SdkInfo> { val list = arrayListOf<SdkInfo>() list.add(SdkInfo("设备信息", isHeader = true)) list.add(SdkInfo("手机型号", Build.MANUFACTURER + " " + Build.MODEL)) list.add(SdkInfo("系统版本", Build.VERSION.RELEASE + " (" + Build.VERSION.SDK_INT + ")")) list.tryAdd { SdkInfo("SD卡剩余空间", DeviceUtils.getSDCardSpace(context)) } list.tryAdd { SdkInfo("系统剩余空间", DeviceUtils.getRomSpace(context)) } list.tryAdd { SdkInfo( "分辨率", "${DeviceUtils.getWidthPixels(context)}x${ DeviceUtils.getRealHeightPixels( context ) }" ) } if (context is Activity) { list.tryAdd { SdkInfo("屏幕尺寸", DeviceUtils.getScreenInch(context).toString()) } } list.tryAdd { SdkInfo("ROOT", DeviceUtils.isRoot(context).toString()) } list.tryAdd { SdkInfo("DENSITY", Resources.getSystem().displayMetrics.density.toString()) } list.tryAdd { SdkInfo("IP", DeviceUtils.getIPAddress(true)) } if (hasClass("com.growingio.android.sdk.track.providers.DeviceInfoProvider")) { list.tryAdd { SdkInfo("IMEI", DeviceInfoProvider.get().deviceId) } } if (hasClass("com.growingio.android.sdk.track.providers.DeviceInfoProvider")) { list.tryAdd { SdkInfo("AndroidId", DeviceInfoProvider.get().androidId) } } if (hasClass("com.growingio.android.sdk.track.providers.DeviceInfoProvider")) { DeviceInfoProvider.get().googleAdId?.let { list.tryAdd { SdkInfo("GoogleId", it) } } } return list } fun ignoreActivity(activity: Activity) { if (hasClass("com.growingio.android.sdk.autotrack.page.PageProvider")) { PageProvider.get().addIgnoreActivity(activity, IgnorePolicy.IGNORE_ALL) } } fun getEventAlphaBet(eventType: String): String { return when (eventType) { TrackEventType.VISITOR_ATTRIBUTES -> "VA" TrackEventType.LOGIN_USER_ATTRIBUTES -> "UA" TrackEventType.CONVERSION_VARIABLES -> "CV" TrackEventType.APP_CLOSED -> "A" AutotrackEventType.PAGE_ATTRIBUTES -> "PA" AutotrackEventType.VIEW_CLICK -> "CK" AutotrackEventType.VIEW_CHANGE -> "CG" TrackEventType.FORM_SUBMIT -> "FS" TrackEventType.REENGAGE -> "RG" TrackEventType.ACTIVATE -> "AV" else -> eventType.first().uppercase() } } fun getEventDesc(eventType: String, data: String): String { try { val jsonObj = JSONObject(data) // custom name val name = jsonObj.optString("eventName") if (name.isNotEmpty()) return name // page val p = jsonObj.optString("path") if (p.isNotEmpty()) return p // visit if (eventType == TrackEventType.VISIT) { val userId = jsonObj.optString("userId") if (userId.isNotEmpty()) return userId val oaid = jsonObj.optString("oaid") if (oaid.isNotEmpty()) return oaid val adrid = jsonObj.optString("androidId") if (adrid.isNotEmpty()) return adrid return jsonObj.optString("domain") } if (eventType == TrackEventType.APP_CLOSED) { return jsonObj.optString("timestamp") } return jsonObj.optString("appName") } catch (e: JSONException) { } return data } }
0
null
0
0
008f5be5c4884e0348d73783dbc5fdfb23c82581
10,911
giokit-android
Apache License 2.0
app/src/main/java/com/hazz/aipick/ui/activity/PayActivity.kt
q513718201
232,772,377
false
{"Java": 997236, "Kotlin": 609033}
package com.hazz.aipick.ui.activity import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.graphics.Color import android.os.Handler import android.os.Message import android.support.v7.widget.Toolbar import android.text.TextUtils import android.util.Log import android.view.View import com.google.gson.Gson import com.hazz.aipick.R import com.hazz.aipick.base.BaseActivity import com.hazz.aipick.mvp.contract.HomeContract import com.hazz.aipick.mvp.model.bean.* import com.hazz.aipick.mvp.presenter.PayPresenter import com.hazz.aipick.utils.PayUtil import com.hazz.aipick.utils.SToast import com.hazz.aipick.utils.ToastUtils import com.hazz.aipick.utils.ToolBarCustom import com.xgr.easypay.callback.IPayCallback import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.activity_pay.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit class PayActivity : BaseActivity(), HomeContract.payView, IPayCallback { companion object { fun start(context: Activity, id: String, role: String, price: String, createId: String, timer: String) { context.startActivity(Intent(context, PayActivity::class.java) .putExtra("id", id) .putExtra("role", role) .putExtra("price", price) .putExtra("createId", createId) .putExtra("timer", timer) ) } } override fun paySucceed(msg: PaySucceed) { tv_succeed.visibility = View.VISIBLE ll_succeed.visibility = View.VISIBLE ll_choose.visibility = View.GONE isPay = true tv1.text = msg.user_name tv2.text = msg.subee_name tv3.text = msg.price + "/" + msg.time_range_type tv4.text = msg.create_at when (msg.pay_method) { "alipay" -> tv5.text = getString(R.string.alipay) else -> tv5.text = getString(R.string.wechat_pay) } tv6.text = msg.expire_at tv_suscribe.text = "已完成" } override fun payCancle(msg: String) { ToastUtils.showToast(this, msg) } override fun createId(msg: CreateId) { subId = msg.sub_id start(msg.timer.toLong()) } @SuppressLint("HandlerLeak") private val mHandler = object : Handler() { override fun handleMessage(msg: Message) { when (msg.what) { SDK_PAY_FLAG -> { val payResult = PayResult(msg.obj as Map<String, String>) /** * 对于支付结果,请商户依赖服务端的异步通知结果。同步通知结果,仅作为支付结束的通知。 */ val resultInfo = payResult.getResult()// 同步返回需要验证的信息 Log.d("junjun", resultInfo) val resultStatus = payResult.getResultStatus() // 判断resultStatus 为9000则代表支付成功 if (TextUtils.equals(resultStatus, "9000")) { val gson = Gson() val fromJson = gson.fromJson(resultInfo, ResultInfo::class.java) // 该笔订单是否真实支付成功,需要依赖服务端的异步通知。 mPayPresenter.payCheck(subId, resultInfo, fromJson.sign, fromJson.sign_type, "9000" ) // SToast.showText("支付成功") } else { // 该笔订单真实的支付结果,需要依赖服务端的异步通知。 SToast.showText("支付失败") } } SDK_AUTH_FLAG -> { } else -> { } } } } override fun payResult(msg: PayResultMine) { if (msg.alipay != null) PayUtil.aliPay(this, msg.alipay.order_string, this) else { PayUtil.wxPay(this, msg.wxpay, this) } } override fun layoutId(): Int = R.layout.activity_pay override fun initData() { } private var price = "" private var mPayPresenter: PayPresenter = PayPresenter(this) private var role = "" private var subId = "" private var timer = "" private var subscribe: Disposable? = null//保存订阅者 private val SDK_PAY_FLAG = 1 private val SDK_AUTH_FLAG = 2 private var isPay = false @SuppressLint("SetTextI18n") override fun initView() { ToolBarCustom.newBuilder(toolbar as Toolbar) .setLeftIcon(R.mipmap.back_white) .setTitle(getString(R.string.pay)) .setTitleColor(resources.getColor(R.color.color_white)) .setToolBarBg(Color.parseColor("#1E2742")) .setOnLeftIconClickListener { finish() } } @SuppressLint("SetTextI18n") override fun start() { price = intent.getStringExtra("price") role = intent.getStringExtra("role") subId = intent.getStringExtra("createId") timer = intent.getStringExtra("timer") tv_price.text = "$price" start(timer.toLong()) tv_suscribe.setOnClickListener { mPayPresenter.pay(subId, if (payType == 0) "alipay" else "wechat") } tv_alipay.setOnClickListener { tv_alipay.isSelected = true tv_wechat.isSelected = false payType = 0 } tv_wechat.setOnClickListener { tv_alipay.isSelected = false tv_wechat.isSelected = true payType = 1 } tv_alipay.isSelected = true } private var payType: Int = 0;//默认是支付宝支付 private fun secondToDate(second: Long, patten: String): String { var calendar = Calendar.getInstance(); calendar.timeInMillis = second * 1000//转换为毫秒 var date = calendar.time var format = SimpleDateFormat(patten) return format.format(date) } fun start(count: Long) { subscribe = Flowable.interval(1, TimeUnit.SECONDS)//按时间间隔发送整数的Observable .observeOn(AndroidSchedulers.mainThread())//切换到主线程修改UI .subscribe { val show = count - it Log.d("junjun", show.toString()) tv_time.text = getString(R.string.pay_time, secondToDate(show, "mm:ss")) if (show <= 0.toLong()) {//当倒计时小于0,计时结束 subscribe!!.dispose() tv_time.text = "支付已超时" return@subscribe//使用标记跳出方法 } } } override fun onDestroy() { super.onDestroy() if (subscribe != null) { subscribe!!.dispose() } if (!isPay) { mPayPresenter.orderCancle(subId) } } override fun failed(code: Int, message: String?) { com.blankj.utilcode.util.ToastUtils.showShort(message) } override fun cancel() { com.blankj.utilcode.util.ToastUtils.showShort("支付取消了") } override fun success(msg: String) { if (payType == 0) { val gson = Gson() val fromJson = gson.fromJson(msg, ResultInfo::class.java) mPayPresenter.payCheck(subId, msg, fromJson.sign, fromJson.sign_type, "9000") } com.blankj.utilcode.util.ToastUtils.showShort("支付成功了") } }
1
null
1
1
a9ca66fb384edc7cc53dd239f216ecdde07c09f6
7,411
Aipick
Apache License 2.0
MPChartExample/src/main/java/com/xxmassdeveloper/mpchartexample/RealtimeLineChartActivity.kt
Amir-yazdanmanesh
646,947,873
true
{"Batchfile": 1, "Shell": 1, "Markdown": 7, "INI": 1, "Java": 165, "Java Properties": 1, "Proguard": 1, "Kotlin": 58}
package com.xxmassdeveloper.mpchartexample import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.net.Uri import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.WindowManager import android.widget.Toast import androidx.core.content.ContextCompat import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.Legend.LegendForm import com.github.mikephil.charting.components.YAxis.AxisDependency import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.highlight.Highlight import com.github.mikephil.charting.listener.OnChartValueSelectedListener import com.github.mikephil.charting.utils.ColorTemplate import com.xxmassdeveloper.mpchartexample.databinding.ActivityLinechartBinding import com.xxmassdeveloper.mpchartexample.databinding.ActivityRealtimeLinechartBinding import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase class RealtimeLineChartActivity : DemoBase(), OnChartValueSelectedListener { private lateinit var chart: LineChart private lateinit var binding: ActivityRealtimeLinechartBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) binding = ActivityRealtimeLinechartBinding.inflate(layoutInflater) val view = binding.root setContentView(view) title = "RealtimeLineChartActivity" chart = binding.barChart chart.setOnChartValueSelectedListener(this) // enable description text chart.getDescription().isEnabled = true // enable touch gestures chart.setTouchEnabled(true) // enable scaling and dragging chart.setDragEnabled(true) chart.setScaleEnabled(true) chart.setDrawGridBackground(false) // if disabled, scaling can be done on x- and y-axis separately chart.setPinchZoom(true) // set an alternative background color chart.setBackgroundColor(Color.LTGRAY) val data = LineData() data.setValueTextColor(Color.WHITE) // add empty data chart.setData(data) // get the legend (only possible after setting data) val l = chart.getLegend() // modify the legend ... l.form = LegendForm.LINE l.typeface = tfLight l.textColor = Color.WHITE val xl = chart.getXAxis() xl.typeface = tfLight xl.textColor = Color.WHITE xl.setDrawGridLines(false) xl.setAvoidFirstLastClipping(true) xl.isEnabled = true val leftAxis = chart.getAxisLeft() leftAxis.typeface = tfLight leftAxis.textColor = Color.WHITE leftAxis.axisMaximum = 100f leftAxis.axisMinimum = 0f leftAxis.setDrawGridLines(true) val rightAxis = chart.getAxisRight() rightAxis.isEnabled = false } private fun addEntry() { val data = chart!!.data if (data != null) { var set = data.getDataSetByIndex(0) // set.addEntry(...); // can be called as well if (set == null) { set = createSet() data.addDataSet(set) } data.addEntry(Entry(set.entryCount.toFloat(), (Math.random() * 40).toFloat() + 30f), 0) data.notifyDataChanged() // let the chart know it's data has changed chart!!.notifyDataSetChanged() // limit the number of visible entries chart!!.setVisibleXRangeMaximum(120f) // chart.setVisibleYRange(30, AxisDependency.LEFT); // move to the latest entry chart!!.moveViewToX(data.entryCount.toFloat()) // this automatically refreshes the chart (calls invalidate()) // chart.moveViewTo(data.getXValCount()-7, 55f, // AxisDependency.LEFT); } } private fun createSet(): LineDataSet { val set = LineDataSet(null, "Dynamic Data") set.axisDependency = AxisDependency.LEFT set.color = ColorTemplate.getHoloBlue() set.setCircleColor(Color.WHITE) set.lineWidth = 2f set.circleRadius = 4f set.fillAlpha = 65 set.fillColor = ColorTemplate.getHoloBlue() set.highLightColor = Color.rgb(244, 117, 117) set.valueTextColor = Color.WHITE set.valueTextSize = 9f set.setDrawValues(false) return set } private var thread: Thread? = null private fun feedMultiple() { if (thread != null) thread!!.interrupt() val runnable = Runnable { addEntry() } thread = Thread { for (i in 0..999) { // Don't generate garbage runnables inside the loop. runOnUiThread(runnable) try { Thread.sleep(25) } catch (e: InterruptedException) { e.printStackTrace() } } } thread!!.start() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.realtime, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.viewGithub -> { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse("https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/RealtimeLineChartActivity.java") startActivity(i) } R.id.actionAdd -> { addEntry() } R.id.actionClear -> { chart!!.clearValues() Toast.makeText(this, "Chart cleared!", Toast.LENGTH_SHORT).show() } R.id.actionFeedMultiple -> { feedMultiple() } R.id.actionSave -> { if (ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED ) { saveToGallery() } else { requestStoragePermission(chart) } } } return true } override fun saveToGallery() { saveToGallery(chart, "RealtimeLineChartActivity") } override fun onValueSelected(e: Entry, h: Highlight) { Log.i("Entry selected", e.toString()) } override fun onNothingSelected() { Log.i("Nothing selected", "Nothing selected.") } override fun onPause() { super.onPause() if (thread != null) { thread!!.interrupt() } } }
0
Java
0
2
339d56e4f1b4182672719e175c2550a527a341b6
7,139
AndroidChart
Apache License 2.0
src/main/kotlin/com/cluster/data/SimpleS3.kt
hexlabsio
131,974,377
false
{"Kotlin": 28426}
package com.cluster.data import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.model.ObjectListing import com.amazonaws.services.s3.model.ObjectMetadata import com.amazonaws.services.s3.model.PutObjectResult import java.io.InputStream interface SimpleS3{ fun doesObjectExist(bucket: String, key: String): Boolean fun getObjectAsString(bucket: String, key: String): String fun listObjects(bucket: String, key: String): ObjectListing fun putObject(bucket: String, key: String, body: InputStream, objectMetadata: ObjectMetadata): PutObjectResult fun putObject(bucket: String, key: String, body: String): PutObjectResult } class ActualS3(private val s3Client: AmazonS3): SimpleS3{ override fun doesObjectExist(bucket: String, key: String) = s3Client.doesObjectExist(bucket, key) override fun getObjectAsString(bucket: String, key: String) = s3Client.getObjectAsString(bucket, key) override fun listObjects(bucket: String, key: String) = s3Client.listObjects(bucket, key) override fun putObject(bucket: String, key: String, body: InputStream, objectMetadata: ObjectMetadata) = s3Client.putObject(bucket, key, body, objectMetadata) override fun putObject(bucket: String, key: String, body: String) = s3Client.putObject(bucket, key, body) }
4
Kotlin
0
0
1f8aaab978e16695b781c1676121c5b0ea4893fc
1,298
cloud-resource-finder
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/plugins/ProjectPluginTrackerManager.kt
hai-ping
335,897,390
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.intellij.ide.AppLifecycleListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.project.stateStore import com.intellij.util.xmlb.annotations.XCollection import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @Service @State( name = "ProjectPluginTrackerManager", storages = [Storage(value = StoragePathMacros.NON_ROAMABLE_FILE, roamingType = RoamingType.DISABLED)], reloadable = false, ) @ApiStatus.Internal class ProjectPluginTrackerManager : SimplePersistentStateComponent<ProjectPluginTrackerManagerState>(ProjectPluginTrackerManagerState()) { companion object { @JvmStatic fun getInstance() = service<ProjectPluginTrackerManager>() @JvmStatic internal fun loadPlugins(candidatesToLoad: Collection<PluginId>) { loadPlugins( candidatesToLoad.findPluginById() ) } @JvmStatic private fun loadPlugins(descriptors: Collection<IdeaPluginDescriptor>): Boolean { /* model: enabled (descriptor, disabledList, load), enabled per project (descriptor, load) project opening: enabled per project (descriptor, load) project closing: disabled per project (descriptor, load iff not is disabled globally) */ return descriptors.isEmpty() || DynamicPlugins.loadPlugins(descriptors).requireRestartIfNecessary() } private fun Boolean.requireRestartIfNecessary(): Boolean { if (!this) { InstalledPluginsState.getInstance().isRestartRequired = true } return this } private fun Collection<PluginId>.findPluginById() = mapNotNull { PluginManagerCore.getPlugin(it) } } private var applicationShuttingDown = false init { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe( ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { if (applicationShuttingDown) return val tracker = createPluginTracker(project) val trackers = openProjectsPluginTrackers(project) loadPlugins( tracker.disabledPluginIds(trackers) ) unloadPlugins( tracker.enabledPluginIds(trackers), project, ) } } ) connection.subscribe( AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { applicationShuttingDown = true } } ) } fun createPluginTracker(project: Project) = ProjectPluginTracker( project.name, state.findStateByProject(project), ) @JvmOverloads fun updatePluginsState( descriptors: Collection<IdeaPluginDescriptor>, action: PluginEnableDisableAction, project: Project? = null, parentComponent: JComponent? = null, ): Boolean { assert(!action.isPerProject || project != null) val pluginIds = descriptors.map { it.pluginId } fun enablePlugins(enabled: Boolean) = DisabledPluginsState.enablePlugins(descriptors, enabled) fun startTrackingPerProject(enable: Boolean) = state.startTracking(project!!, pluginIds, enable) fun stopTrackingPerProject() = state.stopTracking(pluginIds) fun loadPlugins() = loadPlugins(descriptors) fun unloadPlugins() = unloadPlugins(descriptors, project, parentComponent) return when (action) { PluginEnableDisableAction.ENABLE_GLOBALLY -> { enablePlugins(true) stopTrackingPerProject() loadPlugins() } PluginEnableDisableAction.ENABLE_FOR_PROJECT -> { startTrackingPerProject(true) loadPlugins() } PluginEnableDisableAction.ENABLE_FOR_PROJECT_DISABLE_GLOBALLY -> { enablePlugins(false) descriptors.forEach { it.isEnabled = true } startTrackingPerProject(true) true } PluginEnableDisableAction.DISABLE_GLOBALLY -> { enablePlugins(false) stopTrackingPerProject() unloadPlugins() } PluginEnableDisableAction.DISABLE_FOR_PROJECT -> { startTrackingPerProject(false) unloadPlugins() } PluginEnableDisableAction.DISABLE_FOR_PROJECT_ENABLE_GLOBALLY -> false } } internal fun unloadPlugins( candidatesToUnload: Collection<PluginId>, project: Project, ) { unloadPlugins( candidatesToUnload.findPluginById(), project, ) } private fun unloadPlugins( descriptors: Collection<IdeaPluginDescriptor>, project: Project? = null, parentComponent: JComponent? = null, ): Boolean { /* model: disabled (descriptor, disabledList, unload iff not is used), enabled per project (descriptor, unload if not is used) project opening: disabled per project (descriptor, unload if not is used) project closing: enabled per project (descriptor, unload ???) */ return descriptors.isEmpty() || DynamicPlugins.unloadPlugins( descriptors.filter(shouldUnload(project)), project, parentComponent, ).requireRestartIfNecessary() } internal fun openProjectsPluginTrackers(project: Project?): List<ProjectPluginTracker> { return ProjectManager .getInstance() .openProjects .filterNot { it == project } .map { createPluginTracker(it) } } private fun shouldUnload(project: Project?): (IdeaPluginDescriptor) -> Boolean { val trackers = openProjectsPluginTrackers(project) return { descriptor -> val pluginId = descriptor.pluginId trackers.all { !it.isEnabled(pluginId) } && (DisabledPluginsState.isDisabled(pluginId) || trackers.all { it.isDisabled(pluginId) }) } } } class ProjectPluginTrackerManagerState : BaseState() { @get:XCollection var trackers by map<String, ProjectPluginTrackerState>() fun startTracking( project: Project, pluginIds: Collection<PluginId>, enable: Boolean, ) { val updated = findStateByProject(project) .startTracking(pluginIds, enable) if (updated) incrementModificationCount() } fun stopTracking(pluginIds: Collection<PluginId>) { var updated = false trackers.forEach { (_, state) -> updated = state.stopTracking(pluginIds) || updated } if (updated) incrementModificationCount() } internal fun findStateByProject(project: Project): ProjectPluginTrackerState { val workspaceId = if (project.isDefault) null else project.stateStore.projectWorkspaceId return trackers.getOrPut(workspaceId ?: project.name) { ProjectPluginTrackerState().also { incrementModificationCount() } } } }
0
null
0
0
3e1b9a7b8e02803c717f4462924a2cbcfff5cc68
7,107
intellij-community
Apache License 2.0
MLKitLanguageDetection/app/src/main/java/com/example/mlkitlanguagedetection/ui/home/HomeFragment.kt
cewaphi
334,760,962
false
null
package com.example.mlkitlanguagedetection.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.mlkitlanguagedetection.R import com.example.mlkitlanguagedetection.databinding.FragmentHomeBinding import com.google.mlkit.nl.languageid.LanguageIdentification import java.util.* class HomeFragment : Fragment() { private lateinit var homeViewModel: HomeViewModel private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private val languageIdentifier get() = LanguageIdentification.getClient() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textHome homeViewModel.text.observe(viewLifecycleOwner, Observer { textView.text = it }) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnDetect.setOnClickListener { try { languageIdentifier.identifyLanguage(binding.inputText.text.toString()) .addOnSuccessListener { if (it.contains("und", ignoreCase = true)) { Toast.makeText(requireContext(), "What language is this?!", Toast.LENGTH_SHORT).show() binding.detectedLanguage.text = "UNKNOWN" } else { Toast.makeText(requireContext(), "Success!", Toast.LENGTH_SHORT).show() binding.detectedLanguage.text = Locale(it).displayName } } .addOnFailureListener { Toast.makeText(requireContext(), "Failure! :(", Toast.LENGTH_SHORT).show() } languageIdentifier.identifyPossibleLanguages(binding.inputText.text.toString()) .addOnSuccessListener { identifiedLanguages -> binding.detectedLanguages.text = identifiedLanguages.map { "${it.languageTag} (${"%.3f".format(it.confidence)})" }.joinToString("\n") } } catch (e: Exception) { Toast.makeText(requireContext(), "Error: $e", Toast.LENGTH_LONG).show() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
80605722c599c3d0b718c1155be6ab26b2aa4cbd
3,100
common-android-tasks
MIT License
src/main/kotlin/com/pineypiney/game_engine/objects/components/TextureMapsComponent.kt
PineyPiney
491,900,499
false
{"Kotlin": 579098, "GLSL": 32418}
package com.pineypiney.game_engine.objects.components import com.pineypiney.game_engine.objects.GameObject import com.pineypiney.game_engine.resources.textures.Texture class TextureMapsComponent(parent: GameObject, val textures: Map<String, Texture> = emptyMap()): Component(parent, "TMC"), PreRenderComponent { constructor(parent: GameObject): this(parent, emptyMap()) override val fields: Array<Field<*>> = arrayOf() val renderer by lazy{ parent.getComponent<RenderedComponentI>() } override val whenVisible: Boolean = true override fun init() { super.init() renderer?.let { for ((name, texture) in textures) it.uniforms.setIntUniform(name, texture::binding) } } override fun preRender(tickDelta: Double) { renderer?.let { for ((_, texture) in textures) { texture.bind() } } } }
0
Kotlin
0
0
bd05a4b88d530c397a3e9fc36b7f75363dfec1b8
911
GameEngine
MIT License
src/main/kotlin/datastructure/linkedlist/LinkedList.kt
janbarari
385,123,974
false
null
package datastructure.linkedlist class LinkedList<T>: Iterable<T>, Collection<T>, MutableIterable<T>, MutableCollection<T> { private var head: Node<T>? = null private var tail: Node<T>? = null override var size = 0 private set override fun isEmpty(): Boolean { return size == 0 } override fun toString(): String { return if (isEmpty()) { "Empty list" } else { head.toString() } } /** * Adds a value at the front of the list * Time complexity equals O(1) */ fun push(value: T): LinkedList<T> { head = Node(value, head) if (tail == null) { tail = head } size++ return this } /** * Adds a value at the end of the list * Time complexity equals O(1) */ fun append(value: T) { // if the list is empty, It's need to update both head and tail to the new node, // Since we can use push because when the list is empty it's identical to push. if (isEmpty()) { push(value) return } // Tail will never be null here because you were already handled the case where // the list is empty in the if statement. tail?.next = Node(value) // Since this is tail-end insertion, your new node is also the tail of the list. tail = tail?.next size++ } /** * Adds a value after a particular node of the list * Time complexity equals O(1) */ fun insert(value: T, afterNode: Node<T>): Node<T> { // In the case where this method is called with the tail node, call the functionality equivalent append method. // This takes care of updating tail. if (tail == afterNode) { append(value) return tail!! } // Otherwise, create a new node and link its next property to the next node of the list val newNode = Node(value, afterNode.next) // Reassign the next value of the specific node to link it to the new node that you just created. afterNode.next = newNode size++ return newNode } /** * Find and get a particular node of the list * Time complexity equals O(i) which i is the given index as input parameter */ fun nodeAt(index: Int): Node<T>? { // Create a new reference to head and keep track if the current number if traversals. var currentNode = head var currentIndex = 0 // Move down the list until reach the desired index. Empty or out-of-bounds indexed will result in a null return value while (currentNode != null && currentIndex < index) { currentNode = currentNode.next currentIndex++ } return currentNode } /** * Removes the value at the front of the list * note: Once the method finished the garbage collector will remove the first value from the memory * Time complexity equals O(1) */ fun pop(): T? { if(isEmpty().not()) size-- val result = head?.value head = head?.next if (isEmpty()) { tail = null } return result } /** * Removes the value at the end of the list * Time complexity equals O(n) */ fun removeLast(): T? { // if head is null, there is nothing to remove, return null val head = head ?: return null // if the list only consists of one node, removeLast is functionally equivalent to pop. Since pop will handle // updating the head and tail references, so delegate this work to pop method if (head.next == null) return pop() // update the size of the list cause it's going to remove a node size-- // looking for the next node until current.next is null. it means that the current is the last node of the list var prev = head var current = head var next = current.next while(next != null) { prev = current current = next next = current.next } // since current is the last node, disconnect it using the prev.next reference, and update the tail prev.next = null tail = prev return current.value } /** * Removes a value anywhere in the list * Time complexity equals O(1) */ fun removeAfter(node: Node<T>): T? { val result = node.next?.value if (node.next == tail) { tail = node } if (node.next != null) { size-- } node.next = node.next?.next return result } /** * Kotlin Iterable interface */ override fun iterator(): MutableIterator<T> { return LinkedListIterator(this) } /** * Kotlin collection interface * This method iterates through all elements of the list if needed * Time complexity equals O(n) */ override fun contains(element: T): Boolean { for (item in this) { if (item == element) return true } return false } /** * It's just works with a collection of elements * Time complexity equals O(n^2) */ override fun containsAll(elements: Collection<T>): Boolean { for (searched in elements) { if (!contains(searched)) return false } return true } override fun add(element: T): Boolean { append(element) return true } override fun addAll(elements: Collection<T>): Boolean { for (element in elements) { append(element) } return true } override fun clear() { head = null tail = null size = 0 } override fun remove(element: T): Boolean { val iterator = iterator() while(iterator.hasNext()) { val item = iterator.next() if (item == element) { iterator.remove() return true } } return false } override fun removeAll(elements: Collection<T>): Boolean { var result = false for(item in elements) { result = remove(item) || result } return result } override fun retainAll(elements: Collection<T>): Boolean { var result = false val iterator = this.iterator() while (iterator.hasNext()) { val item = iterator.next() if (!elements.contains(item)) { iterator.remove() result = true } } return result } }
0
Kotlin
1
7
2e8ba69f220840881cc11e107ab6b3657c30f87c
6,677
datastructures_and_algorithms
Apache License 2.0
app/src/main/java/com/prmto/mova_movieapp/core/data/data_source/remote/TMDBApi.kt
tolgaprm
541,709,201
false
{"Kotlin": 531468}
package com.prmto.mova_movieapp.core.data.data_source.remote import com.prmto.mova_movieapp.core.data.dto.GenreList import retrofit2.http.GET import retrofit2.http.Query interface TMDBApi { @GET("genre/movie/list") suspend fun getMovieGenreList( @Query("language") language: String ): GenreList @GET("genre/tv/list") suspend fun getTvGenreList( @Query("language") language: String ): GenreList }
1
Kotlin
3
55
816f5eceec10a5aae39e8594f7f02744050c16f9
441
Mova-MovieApp
Apache License 2.0
data/RF00087/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00087" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 1 to 4 75 to 78 } value = "#be1f66" } color { location { 5 to 74 } value = "#6529d1" } color { location { 79 to 79 } value = "#01b5d3" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
661
Rfam-for-RNArtist
MIT License
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/logos/YuqueFill.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.logos 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 com.woowla.compose.icon.collections.remix.remix.LogosGroup public val LogosGroup.YuqueFill: ImageVector get() { if (_yuqueFill != null) { return _yuqueFill!! } _yuqueFill = Builder(name = "YuqueFill", 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) { moveTo(17.281f, 2.955f) curveTo(20.25f, 3.158f, 21.036f, 5.297f, 21.12f, 5.552f) lineTo(22.417f, 5.648f) curveTo(22.547f, 5.648f, 22.586f, 5.828f, 22.471f, 5.884f) curveTo(21.148f, 6.6f, 20.744f, 8.055f, 20.981f, 9.002f) curveTo(21.071f, 9.36f, 21.235f, 9.692f, 21.393f, 10.022f) curveTo(21.7f, 10.664f, 22.044f, 11.44f, 22.1f, 13.003f) curveTo(22.217f, 16.242f, 19.59f, 19.178f, 16.312f, 19.596f) curveTo(17.481f, 18.409f, 18.126f, 17.152f, 18.431f, 16.221f) curveTo(19.037f, 14.375f, 18.939f, 12.905f, 18.486f, 11.781f) curveTo(18.038f, 10.673f, 17.281f, 9.99f, 16.704f, 9.64f) curveTo(15.021f, 8.62f, 13.485f, 8.549f, 12.26f, 8.878f) curveTo(12.725f, 8.284f, 13.136f, 7.677f, 13.46f, 7.014f) curveTo(14.044f, 5.364f, 13.358f, 4.166f, 12.756f, 3.495f) curveTo(12.564f, 3.249f, 12.695f, 2.84f, 13.061f, 2.84f) curveTo(14.47f, 2.84f, 15.874f, 2.86f, 17.281f, 2.955f) close() moveTo(3.319f, 19.107f) curveTo(5.243f, 16.905f, 8.031f, 13.713f, 10.481f, 10.956f) curveTo(11.04f, 10.328f, 13.25f, 8.619f, 16.229f, 10.424f) curveTo(17.107f, 10.956f, 18.659f, 12.589f, 17.56f, 15.935f) curveTo(16.758f, 18.38f, 13.153f, 23.73f, 1.801f, 21.778f) curveTo(1.574f, 21.739f, 1.29f, 21.424f, 1.583f, 21.09f) curveTo(1.998f, 20.618f, 2.598f, 19.932f, 3.319f, 19.107f) close() } } .build() return _yuqueFill!! } private var _yuqueFill: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,925
compose-icon-collections
MIT License
src/test/java/guru/springframework/sfgpetclinic/services/springdatajpa/PetSDJpaServiceIT.kt
adrianbadarau
179,070,960
true
{"Kotlin": 47191, "Java": 2201}
package guru.springframework.sfgpetclinic.services.springdatajpa import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* internal class PetSDJpaServiceIT { @BeforeEach fun setUp() { } @Test fun findAll() { } @Test fun findById() { } @Test fun save() { } @Test fun delete() { } @Test fun deleteById() { } }
0
Kotlin
0
0
cbd206ac8f44483ae573ab7f009dc239c9cea9b0
447
testing-java-junit5
Apache License 2.0
app/src/main/java/io/bibuti/opennews/core/BaseFragment.kt
bibutikoley
325,942,445
false
null
package io.bibuti.opennews.core import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment /** * try to initialize all the fragments from this class. */ abstract class BaseFragment<T : ViewDataBinding> constructor(@LayoutRes private val layoutResId: Int) : Fragment() { lateinit var binding: T override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, layoutResId, container, false) return binding.root } }
0
Kotlin
0
1
c59e27f8bc771d8339728657f7ee96d0e5d26520
793
OpenNews
MIT License
data/RF00754/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00754" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 5 to 6 98 to 99 } value = "#66be02" } color { location { 7 to 27 74 to 94 } value = "#2deac6" } color { location { 29 to 34 67 to 72 } value = "#33cc7d" } color { location { 39 to 43 62 to 66 } value = "#0aa2b7" } color { location { 7 to 6 95 to 97 } value = "#dd7b36" } color { location { 28 to 28 73 to 73 } value = "#6a7fde" } color { location { 35 to 38 67 to 66 } value = "#ec3cc3" } color { location { 44 to 61 } value = "#ae80d9" } color { location { 1 to 4 } value = "#501ab0" } color { location { 100 to 101 } value = "#c901fc" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
1,649
Rfam-for-RNArtist
MIT License
effect_player_arcloud_example/src/main/java/com/banuba/sdk/example/effect_player_arcloud_example/Application.kt
MaksimABanuba
434,158,454
false
{"GLSL": 124045, "Kotlin": 37519, "JavaScript": 11358}
package com.banuba.sdk.example.effect_player_arcloud_example import com.banuba.sdk.arcloud.di.ArCloudKoinModule import com.banuba.sdk.example.common.BANUBA_CLIENT_TOKEN import com.banuba.sdk.example.effect_player_arcloud_example.arcloud.MainKoinModule import com.banuba.sdk.manager.BanubaSdkManager import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class Application : android.app.Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@Application) modules( ArCloudKoinModule().module, MainKoinModule().module ) } // It crashes if token is empty string with // // RuntimeException: // Unable to create application com.banuba.sdk.samples.SamplesApp: // java.lang.RuntimeException: Can't parse client token. // // Please, contact Banuba for obtain a correct client token. BanubaSdkManager.initialize(this, BANUBA_CLIENT_TOKEN) } }
0
GLSL
0
0
dedfcf647940d48edf76927af777b76b48039565
1,075
arcloud-android-kotlin
MIT License
src/main/kotlin/com/dc2f/loader/ContentDefReflection.kt
dc2f
169,700,633
false
{"Kotlin": 154139, "Shell": 419, "Sass": 44}
package com.dc2f.loader import com.dc2f.* import com.dc2f.util.* import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.databind.* import mu.KotlinLogging import org.reflections.Reflections import java.lang.reflect.Modifier import kotlin.reflect.* import kotlin.reflect.full.* import kotlin.reflect.jvm.* private val logger = KotlinLogging.logger {} @ApiDto class ContentDefReflection<T : ContentDef>(@JsonIgnore val klass: KClass<T>) { @Suppress("unused") val type get() = klass.qualifiedName @Suppress("unused") val typeIdentifier: String? by lazy { klass.findAnnotation<Nestable>()?.identifier } @JsonIgnore val contentLoader = ContentLoader(klass) @Suppress("unused") val defaultValues by lazy { if (!klass.isSubclassOf(ContentDef::class)) { logger.debug("Discovered a class which is not a subclass of ContentDef. not reflecting default values. $klass") return@lazy emptyMap<String, Any?>() } if (klass.isSealed) { // sealed classes must not be used directly, but only their children. logger.debug { "Discovered a sealed class. $klass" } return@lazy emptyMap<String, Any?>() } val reader = ContentLoader.objectMapper.reader(object : InjectableValues() { override fun findInjectableValue( valueId: Any?, ctxt: DeserializationContext?, forProperty: BeanProperty?, beanInstance: Any? ): Any? = null }).forType(klass.java) val emptyInstance = reader.readValue<ContentDef>("{}") properties.map { prop -> prop.name to prop.getValue(emptyInstance) }.filter { it.second != null }.toMap() } val property by lazy { properties.map { it.name to it }.toMap() } val properties by lazy { klass.memberProperties.filter { !it.returnType.isJavaType } .filter { prop -> if (!prop.isOpen && !prop.isAbstract) { logger.error { "property must be open: $prop ${prop.isAbstract}" } } // ignore lateinit properties. if (prop.isLateinit) { if (!prop.isTransient) { throw IllegalArgumentException("a lateinit field must be marked as transient.") } return@filter false } if (prop.getter.findAnnotation<JsonIgnore>()?.value == true) { return@filter false } return@filter true } .map { prop -> val elementJavaClass = prop.elementJavaClass if (ParsableObjectDef::class.java.isAssignableFrom(prop.elementJavaClass)) { require(!prop.isMultiValue) { "MultiValue parsable values are not (yet) supported. $klass::${prop.name}" } val propertyTypes = findPropertyTypesFor(elementJavaClass) ContentDefPropertyReflectionParsable( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, propertyTypes.keys.joinToString(","), propertyTypes ) } else if (ContentDef::class.java.isAssignableFrom(prop.elementJavaClass)) { // if (elementJavaClass.kotlin.companionObjectInstance is Parsable<*>) { elementJavaClass.kotlin.isAbstract ContentDefPropertyReflectionNested( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, (findChildTypesForProperty(prop.name)?.map { type -> type.key to type.value }?.toMap() ?: emptyMap()) + // TODO i don't think this is necessary actually? findPropertyTypesFor( elementJavaClass ).mapValues { it.value.java }, elementJavaClass.name ) } else if (Map::class.java.isAssignableFrom(elementJavaClass)) { ContentDefPropertyReflectionMap( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, requireNotNull(prop.returnType.arguments[1].type?.javaType?.typeName) ) } else if (BaseFileAsset::class.java.isAssignableFrom(elementJavaClass)) { ContentDefPropertyReflectionFileAsset( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, ImageAsset::class.java.isAssignableFrom(elementJavaClass) .then { ContentDefPropertyReflectionFileAsset.Type.Image } ?: ContentDefPropertyReflectionFileAsset.Type.File ) } else if (ContentReference::class.java.isAssignableFrom(elementJavaClass)) { ContentDefPropertyReflectionContentReference( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue ) } else if (elementJavaClass.isEnum) { logger.debug("$elementJavaClass is an enum. ${elementJavaClass is Enum<*>} vs. ${elementJavaClass.kotlin is Enum<*>}") // logger.debug("$elementJavaClass is an enum. ${elementJavaClass is Enum<*>} vs. ${elementJavaClass.kotlin is Enum<*>}") ContentDefPropertyReflectionEnum( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, elementJavaClass.enumConstants.map { (it as Enum<*>).name } ) } else { ContentDefPropertyReflectionPrimitive( prop.name, prop.returnType.isMarkedNullable, prop.isMultiValue, PrimitiveType.fromJavaClass( elementJavaClass, "${klass}::${prop.name}" ) ) } } .sortedWith(compareBy({ it.optional }, { it.name })) // .sortedBy { it.name } } private fun findPropertyTypesFor(clazz: Class<*>) = contentLoader.findPropertyTypes().filter { clazz.isAssignableFrom(it.value.java) } private fun findChildTypesForProperty(propertyName: String) = childTypesForProperty(propertyName) private fun childTypesForProperty(propertyName: String): Map<String, Class<out Any>>? { logger.trace { "Loading childTypes for $propertyName of $klass." } val typeArgument = klass.members.find { it.name == propertyName }?.let { member -> if ((member.returnType.classifier as? KClass<*>)?.isSubclassOf(Collection::class) == true) { member.returnType.arguments[0].type } else { member.returnType } } ?: return null logger.trace { "childTypes for $propertyName: typeArgument: {$typeArgument}" } val childrenClass = (typeArgument.classifier as KClass<*>).java return (setOf(childrenClass) + Reflections("app.anlage", "com.dc2f").getSubTypesOf( childrenClass )).mapNotNull { clazz -> val nestable = clazz.kotlin.findAnnotation<Nestable>() ?: clazz.kotlin.allSuperclasses.mapNotNull { it.findAnnotation<Nestable>() } .firstOrNull() // val nestable = it.kotlin.findAnnotation<Nestable>() logger.trace { "available class: $clazz --- $nestable" } nestable?.identifier?.to(clazz) }.toMap() } } @ApiDto sealed class ContentDefPropertyReflection( val name: String, val optional: Boolean, val multiValue: Boolean ) { fun getValue(content: ContentDef): Any? { val property = requireNotNull(content::class.memberProperties.find { it.name == name && !it.returnType.isJavaType }) { "Unable to find member property $name on $content (${content::class})" } return property.getter.run { isAccessible = true call(content) } } @Suppress("unused") val kind get() = when (this) { is ContentDefPropertyReflectionParsable -> "Parsable" is ContentDefPropertyReflectionPrimitive -> "Primitive" is ContentDefPropertyReflectionMap -> "Map" is ContentDefPropertyReflectionNested -> "Nested" is ContentDefPropertyReflectionFileAsset -> "File" is ContentDefPropertyReflectionContentReference -> "ContentReference" is ContentDefPropertyReflectionEnum -> "Enum" } } class ContentDefPropertyReflectionEnum( name: String, optional: Boolean, multiValue: Boolean, @Suppress("unused") val enumValues: List<String> ) : ContentDefPropertyReflection(name, optional, multiValue) class ContentDefPropertyReflectionPrimitive( name: String, optional: Boolean, multiValue: Boolean, @Suppress("unused") val type: PrimitiveType ) : ContentDefPropertyReflection(name, optional, multiValue) enum class PrimitiveType(vararg val clazz: KClass<*>) { Boolean(kotlin.Boolean::class), String(kotlin.String::class, Slug::class), // Integer(Integer::class), ZonedDateTime(java.time.ZonedDateTime::class), Unknown(Any::class) ; companion object { fun fromJavaClass(elementJavaClass: Class<*>, debugMessage: kotlin.String): PrimitiveType { val kotlinClazz = elementJavaClass.kotlin val type = values().find { it.clazz.contains(kotlinClazz) } if (type == null) { logger.error { "UNKNOWN PrimitiveType: $kotlinClazz ($debugMessage)" } return Unknown } return type } } } class ContentDefPropertyReflectionParsable( name: String, optional: Boolean, multiValue: Boolean, @Suppress("unused") val parsableHint: String, @JsonIgnore val parsableTypes: Map<String, KClass<out Any>> ) : ContentDefPropertyReflection(name, optional, multiValue) class ContentDefPropertyReflectionMap( name: String, optional: Boolean, multiValue: Boolean, @Suppress("unused") val mapValueType: String ) : ContentDefPropertyReflection(name, optional, multiValue) class ContentDefPropertyReflectionNested( name: String, optional: Boolean, multiValue: Boolean, @JsonIgnore val allowedTypesClasses: Map<String, Class<*>>, val baseType: String ) : ContentDefPropertyReflection(name, optional, multiValue) { val allowedTypes = allowedTypesClasses.mapValues { it.value.name } } class ContentDefPropertyReflectionFileAsset( name: String, optional: Boolean, multiValue: Boolean, @Suppress("unused") val fileType: Type ) : ContentDefPropertyReflection(name, optional, multiValue) { enum class Type { File, Image } } class ContentDefPropertyReflectionContentReference( name: String, optional: Boolean, multiValue: Boolean ) : ContentDefPropertyReflection(name, optional, multiValue) private val <R> KProperty<R>.isTransient: Boolean get() = javaField?.modifiers?.let { Modifier.isTransient(it) } == true /// either the class of the return value, or the class of elements in the collection, if multivalue (ie. a collection) private val <R> KProperty<R>.elementJavaClass: Class<*> get() = requireNotNull( if ((returnType.classifier as? KClass<*>)?.isSubclassOf(Map::class) == true) { Map::class } else { if (isMultiValue) { returnType.arguments[0].type } else { returnType }?.classifier as? KClass<*> }?.java ) { "Return Type is not a class: $returnType / ${returnType.javaType} (of property $this)" } private val <R> KProperty<R>.isMultiValue: Boolean get() = (returnType.classifier as? KClass<*>)?.isSubclassOf(Collection::class) == true
0
Kotlin
0
1
3eebc777ef432c5c1e16245cf8a66b5e4b80685d
12,772
dc2f.kt
Apache License 2.0
cli/src/main/kotlin/ls/kafka/backup/cli/commands/Restore.kt
lovelysystems
685,887,345
false
{"Kotlin": 69423, "Shell": 4118, "Dockerfile": 704}
package ls.kafka.backup.cli.commands import kotlinx.coroutines.runBlocking import ls.kafka.backup.s3.BackupBucket import ls.kafka.backup.s3.S3Config import org.apache.kafka.clients.admin.AdminClientConfig import picocli.CommandLine.Command import picocli.CommandLine.Option import java.util.* @Command(name = "restore", description = [" - restore Kafka records from S3 to Kafka"]) class Restore : Runnable { @Option(names = ["-b", "--bucket"], required = true, description = ["Bucket to restore from"]) lateinit var bucket: String @Option(names = ["--s3Endpoint"], description = ["Url to S3. If not given defaults to AWS-S3"]) var s3Endpoint: String? = null @Option(names = ["--bootstrapServers"], description = ["Url or list of Urls of kafka servers to restore to."]) var bootstrapServers: String? = null @Option( names = ["-p", "--prefix"], defaultValue = "", description = ["Path prefix of the source topics to restore."] ) lateinit var prefix: String @Option( names = ["-k", "--key"], defaultValue = ".*", description = ["Regex pattern to match the keys to restore."] ) lateinit var keyPattern: String @Option(names = ["--partition"], description = ["Partition of the source topics to restore."]) var partition: Int? = null @Option(names = ["--from"], defaultValue = "0", description = ["First offset to restore from."]) var fromOffset: Long = 0 @Option(names = ["--to"], description = ["Last offset to restore to."]) var toOffset: Long? = null @Option( names = ["-t", "--topic"], description = ["Restored records are produced to the same topic. Set to override the target topic name. Assumes the topic exists or is created."] ) var targetTopic: String? = null @Option(names = ["--profile"], description = ["The profile to use for s3 access."]) var profile: String? = null override fun run() = runBlocking { val s3Config = S3Config(s3Endpoint, profile) val kafkaConfig = createPropertiesFromEnv( overrides = mapOf(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG to bootstrapServers) .mapNotNull { (k, v) -> v?.let { k to v } } .toMap() ) val backupBucket = BackupBucket(bucket, s3Config, kafkaConfig) backupBucket.restore(prefix, Regex(keyPattern), partition, targetTopic, fromOffset, toOffset) } } fun createPropertiesFromEnv( prefix: String = "KAFKA_", overrides: Map<String, String> = emptyMap(), getter: () -> Map<String, String> = System::getenv ): Properties { val props = Properties() getter().forEach { (k, v) -> if (k.startsWith(prefix)) { props[k.substring(prefix.length).replace("_", ".").lowercase()] = v } } overrides.forEach { (k, v) -> props[k] = v } return props }
0
Kotlin
0
0
a1749cb025e21ecadf560a1b14b965a91dbf700d
2,915
lovely-kafka-backup
Apache License 2.0
data/hibernate/src/main/kotlin/io/bluetape4k/hibernate/converters/CompressedStringConverter.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.hibernate.converters import io.bluetape4k.io.compressor.Compressor import io.bluetape4k.io.compressor.Compressors import jakarta.persistence.AttributeConverter import jakarta.persistence.Converter /** * 문자열을 압축해서 문자열로 저장하는 JPA Converter 입니다. */ abstract class AbstractCompressedStringConverter( private val compressor: Compressor, ): AttributeConverter<String?, String?> { override fun convertToDatabaseColumn(attribute: String?): String? { return attribute?.run { compressor.compress(this) } } override fun convertToEntityAttribute(dbData: String?): String? { return dbData?.run { compressor.decompress(this) } } } @Converter class BZip2StringConverter: AbstractCompressedStringConverter(Compressors.BZip2) @Converter class DeflateStringConverter: AbstractCompressedStringConverter(Compressors.Deflate) @Converter class GZipStringConverter: AbstractCompressedStringConverter(Compressors.GZip) @Converter class LZ4StringConverter: AbstractCompressedStringConverter(Compressors.LZ4) @Converter class SnappyStringConverter: AbstractCompressedStringConverter(Compressors.Snappy) @Converter class ZstdStringConverter: AbstractCompressedStringConverter(Compressors.Zstd)
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
1,237
bluetape4k
MIT License
buildSrc/src/main/kotlin/BuildConfig.kt
2BAB
92,044,857
false
null
object BuildConfig { object Versions { const val sealVersion = "3.3.0" } }
0
Kotlin
23
222
5a2c6efbcc04ea065d8efbae9e129523dd571ada
92
Seal
Apache License 2.0
app/src/main/java/com/example/myquizapp/QuizQuestionsActivity.kt
creativelyContent
452,977,009
false
{"Kotlin": 12498}
package com.example.myquizapp import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat class QuizQuestionsActivity : AppCompatActivity(), View.OnClickListener { private var mCurrentPosition: Int = 1 private var mQuestionsList: ArrayList<Question>? = null private var mSelectedOptionPosition: Int = 0 private var progBar: ProgressBar? = null private var tvProgress: TextView? = null private var tvQuestion: TextView? = null private var ivImage: ImageView? = null private var mUserName: String? = null private var mCorrectAnswers: Int = 0 private var optionOne: TextView? = null private var optionTwo: TextView? = null private var optionThree: TextView? = null private var optionFour: TextView? = null private var btnSubmit: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_quiz_questions) mUserName = intent.getStringExtra(Constants.USER_NAME) progBar = findViewById(R.id.prog_bar) tvProgress = findViewById(R.id.tv_progress) tvQuestion = findViewById(R.id.tv_question) ivImage = findViewById(R.id.iv_image) optionOne = findViewById(R.id.optionOne) optionTwo = findViewById(R.id.optionTwo) optionThree = findViewById(R.id.optionThree) optionFour = findViewById(R.id.optionFour) btnSubmit = findViewById(R.id.btnSubmit) mQuestionsList = Constants.getQuestions() optionOne?.setOnClickListener(this) optionTwo?.setOnClickListener(this) optionThree?.setOnClickListener(this) optionFour?.setOnClickListener(this) btnSubmit?.setOnClickListener(this) setQuestion() } private fun setQuestion() { val question: Question = mQuestionsList!![mCurrentPosition - 1] defaultOptionsView() progBar?.progress = mCurrentPosition tvProgress?.text = "$mCurrentPosition / ${progBar?.max}" tvQuestion?.text = question.question optionOne?.text = question.optionOne optionTwo?.text = question.optionTwo optionThree?.text = question.optionThree optionFour?.text = question.optionFour ivImage?.setImageResource(question.Image) if (mCurrentPosition == mQuestionsList!!.size) { btnSubmit?.text = "FINISH" } else { btnSubmit?.text = "SUBMIT" } } private fun defaultOptionsView() { val options = ArrayList<TextView>() optionOne?.let { options.add(0, it) } optionTwo?.let { options.add(1, it) } optionThree?.let { options.add(2, it) } optionFour?.let { options.add(3, it) } for (o in options) { o.setTextColor(Color.parseColor("#7A8089")) o.typeface = Typeface.DEFAULT o.background = ContextCompat.getDrawable(this, R.drawable.default_option_border_bg) } } private fun selectedOptionsView(tv: TextView, selectedOptionNum: Int) { defaultOptionsView() mSelectedOptionPosition = selectedOptionNum tv.setTextColor(Color.parseColor("#363A43")) tv.typeface = Typeface.DEFAULT_BOLD tv.background = ContextCompat.getDrawable(this, R.drawable.selected_option_border) } override fun onClick(view: View?) { when (view?.id) { R.id.optionOne -> { optionOne?.let { selectedOptionsView(it, 1) } } R.id.optionTwo -> { optionTwo?.let { selectedOptionsView(it, 2) } } R.id.optionThree -> { optionThree?.let { selectedOptionsView(it, 3) } } R.id.optionFour -> { optionFour?.let { selectedOptionsView(it, 4) } } R.id.btnSubmit -> { if(mSelectedOptionPosition == 0) { mCurrentPosition++ when{ mCurrentPosition <= mQuestionsList!!.size -> { setQuestion() } else -> { val intent = Intent(this,ResultActivity::class.java) intent.putExtra(Constants.USER_NAME, mUserName) intent.putExtra(Constants.CORRECT_ANSWERS, mCorrectAnswers) intent.putExtra(Constants.TOTAL_QUESTIONS, mQuestionsList?.size) startActivity(intent) finish() Toast.makeText(this, "Congratulations for finishing the quiz!!", Toast.LENGTH_LONG).show() } } } else { val question = mQuestionsList?.get(mCurrentPosition-1) if (question!!.correctAnswer != mSelectedOptionPosition) { answerView(mSelectedOptionPosition, R.drawable.wrong_option_border_bg) }else{ mCorrectAnswers++ } answerView(question.correctAnswer, R.drawable.correct_option_border_bg) if (mCurrentPosition == mQuestionsList!!.size) { btnSubmit?.text = "FINISH" } else { btnSubmit?.text = "GO TO NEXT QUESTION" } mSelectedOptionPosition = 0 } } } } private fun answerView(answer: Int, drawableView: Int){ when(answer){ 1 -> { optionOne?.background = ContextCompat.getDrawable(this,drawableView) } 2 -> { optionTwo?.background = ContextCompat.getDrawable(this,drawableView) } 3 ->{ optionThree?.background = ContextCompat.getDrawable(this,drawableView) } 4 -> { optionFour?.background = ContextCompat.getDrawable(this,drawableView) } } } }
0
Kotlin
0
0
1e8bda2fe6e47c4ef067dc460211875e55b7a1e8
6,540
QuizApp
Creative Commons Zero v1.0 Universal
src/commonMain/kotlin/data/socketbonus/SocB76.kt
marisa-ashkandi
332,658,265
false
null
package data.socketbonus import data.Constants data class SocB76 ( override var id: Int = 76, override var stat: Constants.StatType = Constants.StatType.AGILITY, override var amount: Int = 3 ) : SocketBonusRaw ()
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
221
tbcsim
MIT License
aws/ses/src/test/kotlin/io/bluetape4k/aws/ses/model/DestinationSupportTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.aws.ses.model import io.bluetape4k.logging.KLogging import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class DestinationSupportTest { companion object: KLogging() @Test fun `build destination`() { val destination = destinationOf( toAddresses = listOf("<EMAIL>", "<EMAIL>"), ccAddresses = listOf("<EMAIL>"), bccAddresses = listOf("<EMAIL>") ) destination.toAddresses() shouldBeEqualTo listOf("<EMAIL>", "<EMAIL>") destination.ccAddresses() shouldBeEqualTo listOf("<EMAIL>") destination.bccAddresses() shouldBeEqualTo listOf("<EMAIL>") } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
681
bluetape4k
MIT License
shuttle/design/src/main/kotlin/shuttle/design/model/WidgetPreviewUiModel.kt
fardavide
462,194,990
false
{"Kotlin": 465845, "Shell": 11573}
package shuttle.design.model import android.graphics.drawable.Drawable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import arrow.optics.optics @optics data class WidgetPreviewUiModel( val apps: List<WidgetPreviewAppUiModel>, val layout: WidgetLayoutUiModel ) { companion object } @optics data class WidgetPreviewAppUiModel( val name: String, val icon: Drawable ) { companion object } @optics data class WidgetLayoutUiModel( val allowTwoLines: Boolean, val columnsCount: Int, val horizontalSpacing: Dp, val iconSize: Dp, val rowsCount: Int, val textSize: TextUnit, val transparency: Int, val useMaterialColors: Boolean, val verticalSpacing: Dp ) { companion object }
12
Kotlin
1
14
375798a9ea6433839d5d34965afd0b216f82391a
765
Shuttle
Apache License 2.0
services/hanke-service/src/test/kotlin/fi/hel/haitaton/hanke/test/JacksonTestExtension.kt
City-of-Helsinki
300,534,352
false
{"Kotlin": 1912011, "Mustache": 92562, "Shell": 23444, "Batchfile": 5169, "PLpgSQL": 1115, "Dockerfile": 371}
package fi.hel.haitaton.hanke.test import com.fasterxml.jackson.databind.module.SimpleModule import fi.hel.haitaton.hanke.OBJECT_MAPPER import fi.hel.haitaton.hanke.hakemus.Hakemus import fi.hel.haitaton.hanke.hakemus.HakemusDeserializer import fi.hel.haitaton.hanke.hakemus.HakemusResponse import fi.hel.haitaton.hanke.hakemus.HakemusResponseDeserializer import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.ExtensionContext /** * Extension for customizing Jackson for test use. E.g. deserializing abstract classes we don't want * to deserialize in production code. * * Tests that extend [fi.hel.haitaton.hanke.IntegrationTest] or * [fi.hel.haitaton.hanke.ControllerTest] have this extension enabled by default. Others can use it * by annotating the test class with: * ``` * @ExtendWith(JacksonTestExtension::class) * ``` */ class JacksonTestExtension : BeforeAllCallback { override fun beforeAll(context: ExtensionContext) { if (started) return val module = SimpleModule() module.addDeserializer(Hakemus::class.java, HakemusDeserializer()) module.addDeserializer(HakemusResponse::class.java, HakemusResponseDeserializer()) OBJECT_MAPPER.registerModule(module) } companion object { private var started = false } }
2
Kotlin
5
4
72c671b6105f8706dae713e680ae0c2c0be6a63f
1,337
haitaton-backend
MIT License
src/test/resources/test-compile-data/jvm/kotlin-web-site/whatsnew14/ad8e7706416536cc082340d4c8bd1621.16.kt
AlexanderPrendota
219,478,945
false
null
data class OrderItem(val name: String, val price: Double, val count: Int) fun main() { //sampleStart val order = listOf<OrderItem>( OrderItem("Cake", price = 10.0, count = 1), OrderItem("Coffee", price = 2.5, count = 3), OrderItem("Tea", price = 1.5, count = 2)) val total = order.sumOf { it.price * it.count } // Double val count = order.sumOf { it.count } // Int //sampleEnd println("You've ordered $count items that cost $total in total") }
14
Kotlin
47
89
95326951087813b6dea8b5ef4234fc06f252bd80
485
kotlin-compiler-server
Apache License 2.0
src/main/java/com/example/kotlin/training/section_01_syntax/Task01.kt
macbre
113,159,186
true
{"Kotlin": 15714, "Java": 2577}
package com.example.kotlin.training.section_01_syntax class Task01 { fun generateGreetings(name: String): String { return "Hello ${name.toUpperCase()}!" } }
0
Kotlin
0
0
53d4adad6a7a09ee81da4251cf1f4fb5f580b1af
175
kotlin-training
Apache License 2.0
app/src/main/java/garypan/com/imagebrowserforreddit/ui/views/ImagePopUpView.kt
garypan51
154,085,664
false
null
package garypan.com.imagebrowserforreddit.ui.views import android.content.Context import android.graphics.drawable.Drawable import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.WindowManager import android.widget.* import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import garypan.com.imagebrowserforreddit.R import garypan.com.imagebrowserforreddit.networking.models.RedditPostResponse import android.text.method.ScrollingMovementMethod object ImagePopUpView{ private lateinit var window : PopupWindow fun createPopUpWindow(context : Context, viewOfParentLayout : View, postUrl : String, post : RedditPostResponse.Post){ if(::window.isInitialized){ window.dismiss() } val imagePopUpView = LayoutInflater.from(context).inflate(R.layout.popup_image, null) window = PopupWindow(imagePopUpView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) window.contentView = imagePopUpView // Uncomment to add animation to pop up window // window.animationStyle = R.style.Animation window.isFocusable = true window.showAtLocation(viewOfParentLayout, Gravity.NO_GRAVITY, 0, 0) setUpViews(context, imagePopUpView, postUrl, post) } private fun setUpViews(context: Context, imagePopUpView : View, postUrl: String, post: RedditPostResponse.Post){ val closeButton = imagePopUpView.findViewById<Button>(R.id.closeButton) closeButton.setOnClickListener{window.dismiss()} val imageView = imagePopUpView.findViewById<ImageView>(R.id.imageView) loadImage(context, imageView, postUrl) val titleTextView = imagePopUpView.findViewById<TextView>(R.id.titleTextView) titleTextView.movementMethod = ScrollingMovementMethod() titleTextView.text = post.title val posterTextView = imagePopUpView.findViewById<TextView>(R.id.posterTextView) posterTextView.text = context.getString(R.string.poster_name, post.author) val scoreTextView = imagePopUpView.findViewById<TextView>(R.id.scoreTextView) scoreTextView.text = context.getString(R.string.score, post.score) val silverTextView = imagePopUpView.findViewById<TextView>(R.id.silverAwardTextView) val goldTextView = imagePopUpView.findViewById<TextView>(R.id.goldAwardTextView) val platTextView = imagePopUpView.findViewById<TextView>(R.id.platAwardTextView) val gilds = post.gildings if(gilds.anyGilds()) { if(gilds.awardedSilver()) { silverTextView.visibility = View.VISIBLE silverTextView.text = gilds.gid_1.toString() } if(gilds.awardedGold()) { goldTextView.visibility = View.VISIBLE goldTextView.text = gilds.gid_2.toString() } if(gilds.awardedPlat()) { platTextView.visibility = View.VISIBLE platTextView.text = gilds.gid_3.toString() } } } private fun loadImage(context : Context, imageView : ImageView, postUrl : String){ val progressBar = window.contentView.findViewById<ProgressBar>(R.id.progressBar) progressBar.visibility = View.VISIBLE val options = RequestOptions() .fitCenter() .diskCacheStrategy(DiskCacheStrategy.ALL) Glide.with(context) .load(postUrl) .apply(options) .listener(object : RequestListener<Drawable>{ override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean) : Boolean { return false } override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean) : Boolean { progressBar.visibility = View.INVISIBLE return false } }) .into(imageView) } }
0
Kotlin
0
0
2a28c841e4618ab85b0d119ebd3f837fff18506d
4,509
Image-Browser-For-Reddit
MIT License
HMCardview/src/main/java/com/yuan/hmcardview/ShadowDrawable.kt
zchao-ysu
639,289,704
false
null
package com.yuan.hmcardview import android.graphics.BlurMaskFilter import android.graphics.Rect import android.graphics.drawable.PaintDrawable class ShadowDrawable() : PaintDrawable() { var mShadowEffect: Float = 0f set(value) { if (field != value) { field = value paint.maskFilter = BlurMaskFilter(field, BlurMaskFilter.Blur.NORMAL) } } var mShadowColor: Int = 0x28000000 set(value) { if (field != value) { field = value paint.setColor(field) } } /** * shadow offset with card background on x */ var mOffsetX = 0 /** * shadow offset with card background on y */ var mOffsetY = 0 /** * shadow inset with card background, unit is px */ var mShadowInset = 0 override fun onBoundsChange(bounds: Rect) { bounds.inset(mShadowInset, mShadowInset) bounds.offset(mOffsetX, mOffsetY) super.onBoundsChange(bounds) } }
0
Kotlin
0
1
f611b8b87c1a2f65cbcf2e51e01ccdc2322755a0
1,054
HMShadowCardView
MIT License
bones/src/main/java/pro/horovodovodo4ka/bones/ui/ContainerFragmentSibling.kt
horovodovodo4ka
123,154,278
false
null
package pro.horovodovodo4ka.bones.ui import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import pro.horovodovodo4ka.bones.Bone import pro.horovodovodo4ka.bones.Finger import pro.horovodovodo4ka.bones.Spine import pro.horovodovodo4ka.bones.Wrist import pro.horovodovodo4ka.bones.ui.delegates.FingerNavigator import pro.horovodovodo4ka.bones.ui.delegates.SpineNavigator import pro.horovodovodo4ka.bones.ui.delegates.WristNavigator /** * Base interface for fragments which are siblings of bone with navigation capabilities eg [Finger], [Spine], [Wrist]. * Describes place where nested siblings will be inserted. * Uses support library component by default [FragmentManager] */ interface ContainerFragmentSibling<T : Bone> : FragmentSibling<T> { /** * ID of view in which content of nested siblings will be inserted */ val containerId: Int /** * Lambda that provides FragmentManager for use with transitions. * Primarily used by navigation delegates eg [SpineNavigator], [WristNavigator], [FingerNavigator] */ var managerProvider: (() -> FragmentManager)? /** * Lambda called for additional transaction setup */ var transactionSetup: (FragmentTransaction.(targetFragment: Fragment) -> Unit)? }
0
Kotlin
2
12
dcf5e6349ecb11871e3706c3087113c85b49d402
1,337
bones
The Unlicense
common/src/main/java/io/novafoundation/nova/common/data/GoogleApiAvailabilityProvider.kt
novasamatech
415,834,480
false
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.common.data import android.content.Context import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability interface GoogleApiAvailabilityProvider { fun isAvailable(): Boolean } internal class RealGoogleApiAvailabilityProvider( val context: Context ) : GoogleApiAvailabilityProvider { override fun isAvailable(): Boolean { val googleApiAvailability = GoogleApiAvailability.getInstance() val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context) return resultCode == ConnectionResult.SUCCESS } }
12
Kotlin
30
50
127f8739ca86dc74d006f018237daed0de5095a1
640
nova-wallet-android
Apache License 2.0
common/src/main/java/io/novafoundation/nova/common/data/GoogleApiAvailabilityProvider.kt
novasamatech
415,834,480
false
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.common.data import android.content.Context import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability interface GoogleApiAvailabilityProvider { fun isAvailable(): Boolean } internal class RealGoogleApiAvailabilityProvider( val context: Context ) : GoogleApiAvailabilityProvider { override fun isAvailable(): Boolean { val googleApiAvailability = GoogleApiAvailability.getInstance() val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(context) return resultCode == ConnectionResult.SUCCESS } }
12
Kotlin
30
50
127f8739ca86dc74d006f018237daed0de5095a1
640
nova-wallet-android
Apache License 2.0
app/src/main/java/com/dss886/dotaautochess/feature/filter/list/FilterListAdapter.kt
dss886
168,908,148
false
null
package com.dss886.dotaautochess.feature.filter.list import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.dss886.dotaautochess.R import com.dss886.dotaautochess.data.Hero import com.dss886.dotaautochess.feature.hero.holder.BaseHeroViewHolder import com.dss886.dotaautochess.feature.hero.holder.HeroCountHolder import java.io.Serializable /** * Created by dss886 on 2019/1/30. */ class FilterListAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { private const val TYPE_HEADER = 1000 private const val TYPE_FOOTER = 1001 const val TYPE_HERO = 1002 } private var mHeroList: List<Hero> = emptyList() private var mFilterValue: Serializable? = null fun updateData(heroList: List<Hero>, filterValue: Serializable?) { mHeroList = heroList mFilterValue = filterValue notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { TYPE_HEADER -> FilterHeaderHolder(inflater.inflate(R.layout.hero_item_header, parent, false)) TYPE_FOOTER -> HeroCountHolder(inflater.inflate(R.layout.hero_item_footer, parent, false)) else -> FilterHeroViewHolder(inflater.inflate(R.layout.hero_item_filter_list, parent, false)) } } override fun getItemViewType(position: Int): Int { return when (position) { 0 -> TYPE_HEADER mHeroList.size + 1 -> TYPE_FOOTER else -> TYPE_HERO } } override fun getItemCount(): Int { return mHeroList.size + 2 } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is FilterHeaderHolder -> holder.bind(mFilterValue) is HeroCountHolder -> holder.bind(mHeroList.size) is BaseHeroViewHolder -> holder.bind(mHeroList[position - 1], position) } } }
0
Kotlin
3
14
a2aebbe0746040ec1943ef0173fdf6b428f3e36e
2,163
AutoChessHelper
Apache License 2.0
src/main/kotlin/ru/justagod/mincer/filter/AnnotationClassFilter.kt
JustAGod1
179,755,842
false
{"Kotlin": 232280, "Java": 12281}
package ru.justagod.mincer.filter import org.objectweb.asm.ClassReader import ru.justagod.mincer.Mincer import ru.justagod.model.ClassTypeReference class AnnotationClassFilter(private val target: ClassTypeReference) : ClassFilter { override fun isValid(name: ClassTypeReference, mincer: Mincer): Boolean { val classNode = mincer.makeNode(name, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES) return classNode.invisibleAnnotations != null && classNode.invisibleAnnotations.any { ClassTypeReference.fromDesc(it.desc) == target } } }
0
Kotlin
0
0
5f635e045a6e1323571e492723110de280232c5a
604
cutter
MIT License
ioka/src/main/java/kz/ioka/android/ioka/presentation/webView/WebViewFragment.kt
iokadev
452,776,665
false
null
package kz.ioka.android.ioka.presentation.webView import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.webkit.CookieManager import android.webkit.WebStorage import android.webkit.WebView import android.webkit.WebViewClient import android.widget.FrameLayout import androidx.appcompat.widget.AppCompatTextView import androidx.appcompat.widget.Toolbar import androidx.core.view.isVisible import androidx.fragment.app.setFragmentResult import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import kz.ioka.android.ioka.R import kz.ioka.android.ioka.presentation.result.ErrorResultLauncher import kz.ioka.android.ioka.presentation.result.ResultFragment import kz.ioka.android.ioka.presentation.result.ResultLauncher import kz.ioka.android.ioka.presentation.result.SuccessResultLauncher import kz.ioka.android.ioka.util.replaceFragment import kz.ioka.android.ioka.viewBase.BaseFragment internal class WebViewFragment : BaseFragment(R.layout.ioka_fragment_web_view) { companion object { const val WEB_VIEW_REQUEST_KEY = "WEB_VIEW_REQUEST_KEY" const val WEB_VIEW_RESULT_BUNDLE_KEY = "WEB_VIEW_RESULT_BUNDLE_KEY" const val REDIRECT_URL = "https://ioka.kz/" const val RESULT_SUCCESS = 1_000 const val RESULT_FAIL = 1_001 fun getInstance( behavior: WebViewBehavior ): WebViewFragment { val bundle = Bundle() bundle.putParcelable(FRAGMENT_LAUNCHER, behavior) val fragment = WebViewFragment() fragment.arguments = bundle return fragment } } private val viewModel: WebViewViewModel by viewModels { WebViewViewModelFactory( launcher()!! ) } private var launcher: WebViewBehavior? = null private lateinit var vToolbar: Toolbar private lateinit var vToolbarTitle: AppCompatTextView private lateinit var webView: WebView private lateinit var vProgress: FrameLayout override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) launcher = launcher() bindViews(view) setupViews() observeData() initResultListener() } private fun bindViews(view: View) { vToolbar = view.findViewById(R.id.vToolbar) vToolbarTitle = view.findViewById(R.id.tvToolbarTitle) webView = view.findViewById(R.id.webView) vProgress = view.findViewById(R.id.vProgress) } private fun initResultListener() { setFragmentResultListener(WEB_VIEW_REQUEST_KEY) { _, result -> val state = result.getParcelable<ResultState>(WEB_VIEW_RESULT_BUNDLE_KEY) ?: return@setFragmentResultListener (launcher as? PaymentConfirmationBehavior)?.let { showResultScreen(state, it) } } } private fun showResultScreen(state: ResultState, launcher: PaymentConfirmationBehavior) { val resultLauncher: ResultLauncher? = when (state) { is ResultState.Success -> { SuccessResultLauncher( subtitle = if (launcher.order.externalId.isBlank()) "" else getString( R.string.ioka_result_success_payment_subtitle, launcher.order.externalId ), amount = launcher.order.amount, ) } is ResultState.Fail -> { ErrorResultLauncher( subtitle = state.cause ?: getString(R.string.ioka_result_failed_payment_common_cause) ) } is ResultState.Canceled -> { requireActivity().finish() null } } resultLauncher?.let { parentFragmentManager.replaceFragment( ResultFragment.getInstance( it ) ) } } @SuppressLint("SetJavaScriptEnabled") private fun setupViews() { vToolbar.setNavigationOnClickListener { val data = Bundle() data.putParcelable(WEB_VIEW_RESULT_BUNDLE_KEY, ResultState.Canceled) setFragmentResult(WEB_VIEW_REQUEST_KEY, data) parentFragmentManager.popBackStack() } webView.settings.javaScriptEnabled = true webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (url == REDIRECT_URL) { viewModel.onRedirected() } return false } } } private fun observeData() { viewModel.apply { vToolbarTitle.text = getString(toolbarTitleRes) webView.loadUrl(actionUrl) progress.observe(viewLifecycleOwner) { vProgress.isVisible = it } result.observe(viewLifecycleOwner) { val data = Bundle() data.putParcelable(WEB_VIEW_RESULT_BUNDLE_KEY, it) parentFragmentManager.popBackStack() setFragmentResult(WEB_VIEW_REQUEST_KEY, data) } } } override fun onDestroy() { webView.clearCache(true) webView.clearFormData() webView.clearHistory() webView.clearSslPreferences() CookieManager.getInstance().removeAllCookies(null) CookieManager.getInstance().flush() WebStorage.getInstance().deleteAllData() super.onDestroy() } }
0
Kotlin
0
0
e095b7c443dad4d9954f0dcac19d2a23edd4d9eb
5,849
ioka-android
MIT License
app/src/test/java/com/girlify/dolarapp/dolar/domain/GetDollarsUseCaseTest.kt
honeybadger2788
636,435,895
false
null
package com.girlify.dolarapp.dolar.domain import com.girlify.dolarapp.dolar.data.DollarRepository import com.girlify.dolarapp.dolar.ui.dollar.model.DollarModel import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerify import io.mockk.impl.annotations.RelaxedMockK import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test internal class GetDollarsUseCaseTest { @RelaxedMockK private lateinit var repository: DollarRepository lateinit var getDollarsUseCase: GetDollarsUseCase @Before fun onBefore(){ MockKAnnotations.init(this) getDollarsUseCase = GetDollarsUseCase(repository) } @Test fun whenApiDoesNotReturnAnything_thenGetEmptyList() = runBlocking { coEvery { repository.getDollars() } returns flow { emit(emptyList()) } val response = getDollarsUseCase() coVerify( exactly = 1) { repository.getDollars() } response.collect{ assert(emptyList<DollarModel>() == it) } } @Test fun whenApiReturnData_thenGetDollarsList() = runBlocking { coEvery { repository.getDollars() } returns flow{emit(getDollars())} val response = getDollarsUseCase() coVerify( exactly = 1) { repository.getDollars() } response.collect{ assert(getDollars().size == it.size) assert(getDollars()[0].name == it[0].name) } } private fun getDollars(): List<DollarModel> = listOf( DollarModel("Bco Nacion", "450", "452", "+2.0%", ""), DollarModel("Ahorro", "450", "452", "+2.0%", ""), DollarModel("Blue", "450", "452", "7.0%", ""), DollarModel("MEP", "450", "452", "+2.0%", ""), DollarModel("CCL", "450", "452", "+2.0%", ""), DollarModel("Qatar", "450", "452", "+2.0%", ""), DollarModel("Oficial", "450", "452", "+2.0%", ""), DollarModel("Turista", "450", "452", "+2.0%", "") ) }
0
Kotlin
0
0
f358103fa5d9a5d3473422d655a1ca9db538d46b
2,036
DolarApp
MIT License
kotlinx-coroutines-core/jvm/src/Executors.kt
jeziellago
367,042,540
true
{"Kotlin": 3239863, "Java": 30193, "SCSS": 7897, "Shell": 3332, "Python": 3107, "HTML": 1675, "JavaScript": 1127, "CSS": 319}
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.internal.* import java.io.* import java.util.concurrent.* import kotlin.coroutines.* /** * [CoroutineDispatcher] that has underlying [Executor] for dispatching tasks. * Instances of [ExecutorCoroutineDispatcher] should be closed by the owner of the dispatcher. * * This class is generally used as a bridge between coroutine-based API and * asynchronous API that requires an instance of the [Executor]. */ public abstract class ExecutorCoroutineDispatcher: CoroutineDispatcher(), Closeable { /** @suppress */ @ExperimentalStdlibApi public companion object Key : AbstractCoroutineContextKey<CoroutineDispatcher, ExecutorCoroutineDispatcher>( CoroutineDispatcher, { it as? ExecutorCoroutineDispatcher }) /** * Underlying executor of current [CoroutineDispatcher]. */ public abstract val executor: Executor /** * Closes this coroutine dispatcher and shuts down its executor. * * It may throw an exception if this dispatcher is global and cannot be closed. */ public abstract override fun close() } /** * Converts an instance of [ExecutorService] to an implementation of [ExecutorCoroutineDispatcher]. * * If the underlying executor throws [RejectedExecutionException] on * attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the * resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues), * then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the * [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete. */ @JvmName("from") // this is for a nice Java API, see issue #255 public fun ExecutorService.asCoroutineDispatcher(): ExecutorCoroutineDispatcher = ExecutorCoroutineDispatcherImpl(this) /** * Converts an instance of [Executor] to an implementation of [CoroutineDispatcher]. * * If the underlying executor throws [RejectedExecutionException] on * attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the * resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues), * then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the * [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete. */ @JvmName("from") // this is for a nice Java API, see issue #255 public fun Executor.asCoroutineDispatcher(): CoroutineDispatcher = (this as? DispatcherExecutor)?.dispatcher ?: ExecutorCoroutineDispatcherImpl(this) /** * Converts an instance of [CoroutineDispatcher] to an implementation of [Executor]. * * It returns the original executor when used on the result of [Executor.asCoroutineDispatcher] extensions. */ public fun CoroutineDispatcher.asExecutor(): Executor = (this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this) private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor { override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block) override fun toString(): String = dispatcher.toString() } private class ExecutorCoroutineDispatcherImpl(override val executor: Executor) : ExecutorCoroutineDispatcherBase() { init { initFutureCancellation() } } internal abstract class ExecutorCoroutineDispatcherBase : ExecutorCoroutineDispatcher(), Delay { private var removesFutureOnCancellation: Boolean = false internal fun initFutureCancellation() { removesFutureOnCancellation = removeFutureOnCancel(executor) } override fun dispatch(context: CoroutineContext, block: Runnable) { try { executor.execute(wrapTask(block)) } catch (e: RejectedExecutionException) { unTrackTask() cancelJobOnRejection(context, e) Dispatchers.IO.dispatch(context, block) } } /* * removesFutureOnCancellation is required to avoid memory leak. * On Java 7+ we reflectively invoke ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true) and we're fine. * On Java 6 we're scheduling time-based coroutines to our own thread safe heap which supports cancellation. */ override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) { val future = if (removesFutureOnCancellation) { scheduleBlock(ResumeUndispatchedRunnable(this, continuation), continuation.context, timeMillis) } else { null } // If everything went fine and the scheduling attempt was not rejected -- use it if (future != null) { continuation.cancelFutureOnCancellation(future) return } // Otherwise fallback to default executor DefaultExecutor.scheduleResumeAfterDelay(timeMillis, continuation) } override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle { val future = if (removesFutureOnCancellation) { scheduleBlock(block, context, timeMillis) } else { null } return when { future != null -> DisposableFutureHandle(future) else -> DefaultExecutor.invokeOnTimeout(timeMillis, block, context) } } private fun scheduleBlock(block: Runnable, context: CoroutineContext, timeMillis: Long): ScheduledFuture<*>? { return try { (executor as? ScheduledExecutorService)?.schedule(block, timeMillis, TimeUnit.MILLISECONDS) } catch (e: RejectedExecutionException) { cancelJobOnRejection(context, e) null } } private fun cancelJobOnRejection(context: CoroutineContext, exception: RejectedExecutionException) { context.cancel(CancellationException("The task was rejected", exception)) } override fun close() { (executor as? ExecutorService)?.shutdown() } override fun toString(): String = executor.toString() override fun equals(other: Any?): Boolean = other is ExecutorCoroutineDispatcherBase && other.executor === executor override fun hashCode(): Int = System.identityHashCode(executor) } private class ResumeUndispatchedRunnable( private val dispatcher: CoroutineDispatcher, private val continuation: CancellableContinuation<Unit> ) : Runnable { override fun run() { with(continuation) { dispatcher.resumeUndispatched(Unit) } } } /** * An implementation of [DisposableHandle] that cancels the specified future on dispose. * @suppress **This is unstable API and it is subject to change.** */ private class DisposableFutureHandle(private val future: Future<*>) : DisposableHandle { override fun dispose() { future.cancel(false) } override fun toString(): String = "DisposableFutureHandle[$future]" }
0
null
0
1
e88e58d5c2b2f0f119bdbb6d5e43454fb7226982
7,184
kotlinx.coroutines
Apache License 2.0
services/hanke-service/src/main/kotlin/fi/hel/haitaton/hanke/HankeErrorSerializer.kt
City-of-Helsinki
300,534,352
false
null
package fi.hel.haitaton.hanke import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.ser.std.StdSerializer class HankeErrorSerializer : StdSerializer<HankeError>(HankeError::class.java) { override fun serialize(value: HankeError?, gen: JsonGenerator, provider: SerializerProvider) { if (value != null) { gen.writeStartObject() gen.writeStringField("errorCode", value.errorCode) gen.writeStringField("errorMessage", value.errorMessage) gen.writeEndObject() } } }
1
Kotlin
4
1
89ac42586cfb1355f79b09062ba54736a4a6adfd
624
haitaton-backend
MIT License
src/iosMain/kotlin/com/myunidays/kiterable/IterableApi.kt
MyUNiDAYS
561,441,423
false
{"Kotlin": 23934, "Ruby": 1725}
package com.myunidays.kiterable import com.myunidays.kiterable.models.Context import com.myunidays.kiterable.models.IterableConfig import com.myunidays.kiterable.models.IterableInAppMessage import com.myunidays.kiterable.models.PayloadData import platform.Foundation.NSData import platform.UIKit.UIApplicationLaunchOptionsKey val shared: IterableApi get() = IterableApi.getInstance() val optionalShared: IterableApi? get() = IterableApi.getOptionalInstance() private var internalInstance: IterableApiInterface? = null actual class IterableApi internal constructor(private val ios: IterableApiInterface) { actual companion object { actual fun initialize(context: Context, apiKey: String, config: IterableConfig): IterableApi { throw Error("iOS needs to use the initialize method with IterableApiImpl being passed.") } fun initialize(ios: IterableApiInterface, apiKey: String, launchOptions: Map<UIApplicationLaunchOptionsKey, Any>, config: IterableConfig): IterableApi { internalInstance = ios internalInstance!!.initialize(apiKey, launchOptions, config) return instance } actual fun getInstance(): IterableApi = instance fun getOptionalInstance(): IterableApi? = if (internalInstance != null) instance else null private val instance: IterableApi by lazy { IterableApi(internalInstance!!) } } actual val payloadData: PayloadData? get() = ios.getPayloadData() actual val inAppManager: IterableInAppManager get() = ios.inAppManager actual fun setUserId(userId: String?) = ios.setUserId(userId) actual fun setEmail(email: String?) = ios.setEmail(email) actual fun getPayloadData(key: String): String? = ios.getPayloadData(key) actual fun getMessages(): List<IterableInAppMessage> = inAppManager.messages actual fun getMessage(predicate: (IterableInAppMessage) -> Boolean): IterableInAppMessage? = getMessages().firstOrNull(predicate) actual fun showMessage( message: IterableInAppMessage, consume: Boolean, onClick: IterableHelper.IterableUrlCallback, ) = inAppManager.showMessage(message, consume, onClick) actual fun getAndTrackDeepLink(uri: String, onCallback: IterableHelper.IterableActionHandler?) = ios.getAndTrackDeepLink(uri, onCallback) fun register(token: NSData) = ios.register(token) fun disableDeviceForCurrentUser() = ios.disableDeviceForCurrentUser() } interface IterableApiInterface { val inAppManager: IterableInAppManager fun initialize(apiKey: String, launchOptions: Map<UIApplicationLaunchOptionsKey, Any>?, config: IterableConfig) fun setUserId(userId: String?) fun setEmail(email: String?) fun getPayloadData(): PayloadData? fun getPayloadData(key: String): String? fun getMessages(): List<IterableInAppMessage> fun getAndTrackDeepLink(uri: String, onCallback: IterableHelper.IterableActionHandler?) fun register(token: NSData) fun disableDeviceForCurrentUser() }
0
Kotlin
0
0
c46ffeba0688063b2ac4a4fce38e244b36ce3a58
3,050
KIterable-pre-template
MIT License
app/src/main/java/com/richard/ticketmaster/di/NetworkModule.kt
AbdulRehmanNazar
807,679,848
false
{"Kotlin": 39545}
package com.richard.ticketmaster.di import android.content.Context import com.richard.ticketmaster.data.api.APIService import com.richard.ticketmaster.data.local.AddressDao import com.richard.ticketmaster.data.local.AppDataBase import com.richard.ticketmaster.data.local.CityDao import com.richard.ticketmaster.data.local.EmbeddedVennuDao import com.richard.ticketmaster.data.local.EventDao import com.richard.ticketmaster.data.local.EventDateDao import com.richard.ticketmaster.data.local.ImageDao import com.richard.ticketmaster.data.local.StateDao import com.richard.ticketmaster.data.local.VennuDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun getBaseURL(): String = "https://app.ticketmaster.com/discovery/v2/" @Provides fun provideOkhttpClient( @ApplicationContext appContext: Context ): OkHttpClient { val interceptor = HttpLoggingInterceptor() interceptor.setLevel(HttpLoggingInterceptor.Level.BODY) return OkHttpClient.Builder() .addInterceptor(interceptor) .build(); } @Singleton @Provides fun provideRetrofit(baseURL: String, client: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(baseURL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() } @Singleton @Provides fun provideAPIService(retrofit: Retrofit): APIService { return retrofit.create(APIService::class.java) } @Provides @Singleton fun provideDataBase(@ApplicationContext appContext: Context): AppDataBase { return AppDataBase.getDatabase(appContext) } @Provides @Singleton fun provideEventDAO(appDataBase: AppDataBase): EventDao { return appDataBase.eventDao() } @Provides @Singleton fun provideImageDAO(appDataBase: AppDataBase): ImageDao { return appDataBase.imageDao() } @Provides @Singleton fun provideEmbeddedVennueDAO(appDataBase: AppDataBase): EmbeddedVennuDao { return appDataBase.embededVenueDao() } @Provides @Singleton fun provideVennueDAO(appDataBase: AppDataBase): VennuDao { return appDataBase.venueDao() } @Provides @Singleton fun provideStateDAO(appDataBase: AppDataBase): StateDao { return appDataBase.stateDao() } @Provides @Singleton fun provideCityDAO(appDataBase: AppDataBase): CityDao { return appDataBase.cityDao() } @Provides @Singleton fun provideAddressDAO(appDataBase: AppDataBase): AddressDao { return appDataBase.addressDao() } @Provides @Singleton fun provideEventDateDao(appDataBase: AppDataBase): EventDateDao { return appDataBase.eventDateDao() } }
0
Kotlin
0
0
6cc1420f418ce15e09a509f68614a686cfc7822b
3,212
MusicEvents
Apache License 2.0
src/test/kotlin/com/turbomates/time/period/OffsetDateTimeTest.kt
turbomates
556,838,637
false
{"Kotlin": 17004, "Makefile": 1218}
package com.turbomates.time.period import org.junit.jupiter.api.Test import java.time.OffsetDateTime import java.time.ZoneOffset import kotlin.test.assertEquals class OffsetDateTimeTest { @Test fun `start of week`() { assertEquals( OffsetDateTime.of(2022, 6, 27, 0, 0, 0, 0, ZoneOffset.UTC), OffsetDateTime.of(2022, 7, 1, 10, 0, 0, 0, ZoneOffset.UTC).startOf(PeriodType.WEEKS) ) assertEquals( OffsetDateTime.of(2022, 7, 4, 0, 0, 0, 0, ZoneOffset.UTC), OffsetDateTime.of(2022, 7, 6, 22, 53, 0, 0, ZoneOffset.UTC).startOf(PeriodType.WEEKS) ) } }
0
Kotlin
0
0
2dad3e4cd6ba38412251c1ac91dd273145878ab2
639
kotlin-time
MIT License
app/src/main/java/nick/mirosh/newsapp/di/ServiceModule.kt
nsmirosh
644,001,365
false
{"Kotlin": 68302}
package nick.mirosh.newsapp.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.ExperimentalCoroutinesApi import nick.mirosh.newsapp.data.repository.NetworkConnectivityManager import nick.mirosh.newsapp.domain.network.repository.NetworkConnectivityService import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class ServiceModule { @Binds @ExperimentalCoroutinesApi @Singleton abstract fun bindNetworkConnectivityRepository( networkConnectivityManager: NetworkConnectivityManager ): NetworkConnectivityService }
0
Kotlin
1
2
40ba93be62c96df3476d3facee7d51c440e714da
668
NewsApp
MIT License
app/src/main/java/com/lianyi/paimonsnotebook/ui/screen/cultivate_project/view/CultivateProjectScreen.kt
QooLianyi
435,314,581
false
{"Kotlin": 1855635}
package com.lianyi.paimonsnotebook.ui.screen.cultivate_project.view import android.os.Bundle import androidx.activity.compose.setContent import androidx.compose.animation.Crossfade import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModelProvider import com.lianyi.paimonsnotebook.R import com.lianyi.paimonsnotebook.common.components.dialog.ConfirmDialog import com.lianyi.paimonsnotebook.common.components.layout.column.TabBarColumnLayout import com.lianyi.paimonsnotebook.common.components.lazy.ContentSpacerLazyColumn import com.lianyi.paimonsnotebook.common.components.loading.ContentLoadingLayout import com.lianyi.paimonsnotebook.common.components.loading.ContentLoadingPlaceholder import com.lianyi.paimonsnotebook.common.components.placeholder.EmptyPagePlaceholder import com.lianyi.paimonsnotebook.common.components.placeholder.ErrorPlaceholder import com.lianyi.paimonsnotebook.common.components.popup.IconTitleInformationPopupWindow import com.lianyi.paimonsnotebook.common.components.widget.button.TitleAndDescriptionActionButton import com.lianyi.paimonsnotebook.common.core.base.BaseActivity import com.lianyi.paimonsnotebook.common.database.cultivate.data.CultivateEntityType import com.lianyi.paimonsnotebook.common.extension.modifier.radius.radius import com.lianyi.paimonsnotebook.ui.screen.cultivate_project.components.items.CultivateAvatarCard import com.lianyi.paimonsnotebook.ui.screen.cultivate_project.components.items.CultivateItemWeaponCard import com.lianyi.paimonsnotebook.ui.screen.cultivate_project.components.page.CultivateProjectOverallPage import com.lianyi.paimonsnotebook.ui.screen.cultivate_project.viewmodel.CultivateProjectScreenViewModel import com.lianyi.paimonsnotebook.ui.theme.PaimonsNotebookTheme class CultivateProjectScreen : BaseActivity() { private val viewModel by lazy { ViewModelProvider(this)[CultivateProjectScreenViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PaimonsNotebookTheme(this) { ContentLoadingLayout( loadingState = viewModel.loadingState, loadingContent = { ContentLoadingPlaceholder() }, emptyContent = { EmptyPagePlaceholder(title = "当前没有养成计划") { TitleAndDescriptionActionButton( title = "前往养成计划设置页", description = "前往养成计划设置界面添加一个养成计划", modifier = Modifier .padding(16.dp, 0.dp) .fillMaxWidth(), onClick = viewModel::goOptionScreen ) } }, errorContent = { ErrorPlaceholder() }, defaultContent = {} ) { TabBarColumnLayout( tabs = viewModel.tabs, onTabBarSelect = viewModel::onSelectTabBar, tabsSpace = 12.dp, topSlot = { Row( modifier = Modifier .fillMaxSize() .padding(horizontal = 12.dp), horizontalArrangement = Arrangement.End, ) { Crossfade( targetState = viewModel.currentPageIndex == 1, label = "" ) { if (it) { Icon( painter = painterResource(id = if (viewModel.showOverallPageGridList) R.drawable.ic_list_square else R.drawable.ic_grid_1), contentDescription = null, modifier = Modifier .padding(2.dp) .radius(3.dp) .size(32.dp) .clickable { viewModel.switchShowOverallPageGridList() } .padding(4.dp) ) } } Icon( painter = painterResource(id = R.drawable.ic_navigation), contentDescription = null, modifier = Modifier .padding(2.dp) .radius(3.dp) .size(32.dp) .clickable { viewModel.goOptionScreen() } .padding(4.dp) ) } } ) { Crossfade(targetState = viewModel.currentPageIndex, label = "") { when (it) { 1 -> CultivateProjectOverallPage( showGridLayout = viewModel.showOverallPageGridList, overallMaterialBaseInfoGroupList = viewModel.overallMaterialBaseInfoGroupList, overallMaterialBaseInfoGroupListFlatten = viewModel.overallMaterialBaseInfoGroupListFlatten, onShowMaterialInfoPopupDialog = viewModel::onShowMaterialInfoPopupDialog, onShowEntityInfoPopupDialog = viewModel::onShowEntityInfoPopupDialog, getOverallEntityBaseInfoListByMaterialId = viewModel::getOverallEntityBaseInfoListByMaterialId ) else -> CultivateProjectPage() } } } } if (viewModel.showDeleteEntityConfirmDialog) { ConfirmDialog( title = "删除养成项", content = viewModel.deleteEntityConfirmDialogContent, onConfirm = viewModel::deleteCurrentSelectedEntity, onCancel = viewModel::entityConfirmDialogDismissRequest ) } if (viewModel.showPopupWindow) { IconTitleInformationPopupWindow( data = viewModel.showPopupWindowInfo, popupProvider = viewModel.popupWindowProvider, onDismissRequest = viewModel::onPopupWindowDismissRequest ) } } } } @Composable private fun CultivateProjectPage() { ContentSpacerLazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp), statusBarPaddingEnabled = false ) { viewModel.entityCultivateItemsPairList.forEach { (entity, items) -> when (entity.type) { CultivateEntityType.Weapon -> { val weaponData = viewModel.getWeaponData(entity.itemId) ?: return@forEach val cultivateItemsMap = items.associateBy { it.itemId } item( key = "${entity.projectId}_${entity.itemId}_${entity.addTime}" ) { CultivateItemWeaponCard( weaponData = weaponData, entity = entity, cultivateItemsMap = cultivateItemsMap, getMaterialsByCultivateItemId = viewModel::getMaterialListByCultivateItemId, getMaterialInfo = viewModel::getMaterialData, onClickDelete = viewModel::onClickCultivateCardDelete, onEmitMaterialItemUpdateQueue = viewModel::onEmitMaterialItemUpdateQueue, onShowMaterialInfoPopupDialog = viewModel::onShowMaterialInfoPopupDialog ) } } CultivateEntityType.Avatar -> { val avatarData = viewModel.getAvatarData(entity.itemId) ?: return@forEach //角色养成id map val avatarCultivateMap = viewModel.getAvatarCultivateIdMap(avatarData) //计算项map val cultivateItemsMap = items.associateBy { it.itemId } item( key = "${entity.projectId}_${entity.itemId}_${entity.addTime}" ) { CultivateAvatarCard( avatarData = avatarData, entity = entity, cultivateItems = items, avatarCultivateMap = avatarCultivateMap, cultivateItemsMap = cultivateItemsMap, getCultivateMaterialsListByCultivateItemId = viewModel::getMaterialListByCultivateItemId, getMaterialInfo = viewModel::getMaterialData, onClickDelete = viewModel::onClickCultivateCardDelete, onEmitMaterialItemUpdateQueue = viewModel::onEmitMaterialItemUpdateQueue, onShowMaterialInfoPopupDialog = viewModel::onShowMaterialInfoPopupDialog ) } } else -> {} } } } } }
1
Kotlin
2
36
7af1f8cce2f8eea3f72b3735e820508510b3112e
11,263
PaimonsNotebook
MIT License