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
compiler/testData/diagnostics/tests/delegatedProperty/typeMismatchForGetWithGeneric.kt
JakeWharton
99,388,807
false
null
// !DIAGNOSTICS: -UNUSED_PARAMETER import kotlin.reflect.KProperty class A class B { val b: Int by <!INAPPLICABLE_CANDIDATE!>Delegate<A>()<!> } val bTopLevel: Int by <!INAPPLICABLE_CANDIDATE!>Delegate<A>()<!> class C { val c: Int by Delegate<C>() } val cTopLevel: Int by Delegate<Nothing?>() class Delegate<T> { operator fun getValue(t: T, p: KProperty<*>): Int { return 1 } }
184
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
396
kotlin
Apache License 2.0
src/2021/Day12.kt
nagyjani
572,361,168
false
null
//package `2021` // //import java.io.File //import java.util.* // //fun main() { // Day12().solve() //} // //class Day12 { // // val input0 = """ // start-A // start-b // A-c // A-b // b-d // A-end // b-end // """.trimIndent() // // val input1 = """ //dc-end //HN-start //start-kj //dc-start //dc-HN //LN-dc //HN-end //kj-sa //kj-HN //kj-dc // """.trimIndent() // // val input2 = """ //fs-end //he-DX //fs-he //start-DX //pj-DX //end-zg //zg-sl //zg-pj //pj-he //RW-he //fs-DX //pj-RW //zg-RW //start-pj //he-WI //zg-he //pj-fs //start-RW // """.trimIndent() // //// class CaveMapIteratorState(val path: CavePath) { //// val tried = mutableSetOf<String>() //// fun nextPath(): CavePath? { //// val cave = path.lastCave() //// return //// } //// } // // class CavePaths(val caves: Caves, val visitNum: Int): Iterable<CavePath> { // override fun iterator(): Iterator<CavePath> { // return CavePathIterator(caves, visitNum) // } // } // // class CavePathIterator(caves: Caves, val visitNum: Int): Iterator<CavePath> { // val nodes = mutableListOf(CavePathIteratorNode(CavePath(), caves, visitNum)) // var next = findNext() // override fun hasNext(): Boolean { // return next != null // } // override fun next(): CavePath { // val r = next // next = findNext() // return r!! // } // tailrec fun findNext(): CavePath? { // if (nodes.isEmpty()) { // return null // } // if (nodes.last().hasNext) { // nodes.add(nodes.last().next()) // } else { //// println("-:${nodes.last().path.path}") // nodes.removeLast() // } // if (nodes.isEmpty()) { // return null // } // if (nodes.last().path.complete) { //// println("+:${nodes.last().path.path}") // return nodes.last().path // } // return findNext() // } // } // // class CavePathIteratorNode(val path: CavePath, val caves: Caves, val visitNum: Int) { // val remainingNextCaves = mutableSetOf<String>().apply{ // addAll(caves.neighbours(path.lastCave).filter{ it.isBig() || !path.visited(it, visitNum)}) // } // val hasNext get() = path.lastCave != "end" && remainingNextCaves.isNotEmpty() // fun next(): CavePathIteratorNode { // val nextCave = remainingNextCaves.first().also{ remainingNextCaves.remove(it) } // return CavePathIteratorNode(path.next(nextCave), caves, visitNum) // } // } // // class CavePath(val lastCave: String = "start", val basePath: CavePath? = null) { // val complete get() = lastCave == "end" // val path: String get() = basePath?.path?.plus(",")?.plus(lastCave)?:lastCave // fun visited(cave: String): Boolean { // return visited(cave, this) // } // tailrec fun visited(cave: String, path: CavePath?): Boolean { // if (path == null) { // return false // } // if (path.lastCave == cave) { // return true // } // return visited(cave, path.basePath) // } // fun visited(cave: String, num: Int): Boolean { // return visited(cave, this, num) // } // tailrec fun visited(cave: String, path: CavePath?, num: Int): Boolean { // if (cave == "start") { // return true // } // if (path == null) { // return false // } // val m = generateSequence(path){it.basePath} // .map { it.lastCave } // .filter{!it.isBig()} // .fold(mutableMapOf<String, Int>()){acc, it -> acc[it] = acc.getOrDefault(it,0)+1; acc} // return !(m.getOrDefault(cave, 0) < 1 || m.getOrDefault(cave, 0)<2 && m.values.all{it<2}) //// if (path.lastCave == cave) { //// if (num == 1) { //// return true //// } //// return visited(cave, path.basePath, num-1) //// } //// return visited(cave, path.basePath, num) // } // fun next(nextCave: String): CavePath { // return CavePath(nextCave, this) // } // } // // class CavesBuilder { // val caves = mutableMapOf<String, MutableSet<String>>() // fun add(c1: String, c2: String): CavesBuilder { // caves[c1]?.add(c2)?:mutableSetOf(c2).let{caves[c1] = it} // caves[c2]?.add(c1)?:mutableSetOf(c1).let{caves[c2] = it} // return this // } // fun build(): Caves { // return Caves(caves) // } // } // // class Caves(val caves: Map<String, Set<String>>) { // fun neighbours(cave: String): Set<String> { // return caves[cave]!! // } // } // // fun solve() { // val f = File("src/2021/inputs/day12.in") // val s = Scanner(f) //// val s = Scanner(input0) //// val s = Scanner(input1) //// val s = Scanner(input2) // val cb = CavesBuilder() // while (s.hasNextLine()) { // s.nextLine().split("-").let { cb.add(it[0], it[1]) } // } // val c = cb.build() // val paths = CavePaths(c, 2) // println("${paths.toList().size}") //// println("${paths.toList().map { it.path }}") // } //}
0
Kotlin
0
0
4fea7b4abfde1d2ac1f05a94eff484f8db99b594
5,665
advent-of-code
Apache License 2.0
sample/src/main/java/contacts/sample/util/BundleExt.kt
vestrel00
223,332,584
false
{"Kotlin": 1616347, "Shell": 635}
package contacts.sample.util import android.os.Build import android.os.Bundle import java.io.Serializable inline fun <reified T : Serializable> Bundle.getSerializableCompat(name: String): T? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { getSerializable(name, T::class.java) } else { @Suppress("Deprecation") getSerializable(name) as T? }
26
Kotlin
35
573
383594d2708296f2fbc6ea1f10b117d3acd1f46a
392
contacts-android
Apache License 2.0
app/src/main/java/io/tanlnm/my/weather/domain/repository/WeatherRepository.kt
tanlnm512
765,975,271
false
{"Kotlin": 43380}
package io.tanlnm.my.weather.domain.repository import io.tanlnm.my.weather.data.model.Weather import kotlinx.coroutines.flow.Flow interface WeatherRepository { fun searchWeatherByCity(query: String, units: String): Flow<Result<Weather>> fun searchWeatherByCityId(id: String, units: String): Flow<Result<Weather>> }
0
Kotlin
0
0
60361d57eefe3cc60d4f85e1b9f4939f40f4b93c
324
my_weather
Apache License 2.0
app/src/main/java/ml/dvnlabs/animize/ui/fragment/navigation/Updates.kt
rootdavinalfa
177,693,326
false
null
/* * Copyright (c) 2020. * Animize Devs * Copyright 2019 - 2020 * <NAME> <<EMAIL>> * This program used for watching anime without ads. * */ package ml.dvnlabs.animize.ui.fragment.navigation import android.os.Bundle import android.view.* import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import ml.dvnlabs.animize.R import ml.dvnlabs.animize.databinding.FragmentUpdatesBinding import ml.dvnlabs.animize.ui.recyclerview.list.update.NotificationUpdateAdapter import ml.dvnlabs.animize.ui.viewmodel.ListViewModel import ml.dvnlabs.animize.util.notification.StarredNotificationWorker import org.koin.androidx.viewmodel.ext.android.sharedViewModel class Updates : Fragment() { private val listVM : ListViewModel by sharedViewModel() private var binding: FragmentUpdatesBinding? = null private var adapter: NotificationUpdateAdapter? = null private var layoutManager: LinearLayoutManager? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { inflater.inflate(R.layout.fragment_updates, container, false) binding = FragmentUpdatesBinding.inflate(inflater) (activity as AppCompatActivity).setSupportActionBar(binding!!.updateToolbar) layoutManager = LinearLayoutManager(requireContext()) adapter = NotificationUpdateAdapter(R.layout.rv_update) binding!!.updateList.layoutManager = layoutManager binding!!.updateList.adapter = adapter binding!!.updateToolbar.title = "Updates" listVM.listNotification.observe(viewLifecycleOwner, Observer { adapter?.setNotification(it) }) setHasOptionsMenu(true) return binding!!.root } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.toolRefresh -> { GlobalScope.launch { StarredNotificationWorker.setupTaskImmediately(requireContext()) } true } else -> { super.onOptionsItemSelected(item) } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.refresh_standard, menu) super.onCreateOptionsMenu(menu, inflater) } }
1
null
1
2
c12aa046a42712794dc3f7e06dbbcee654c1e79f
2,524
animize
Apache License 2.0
ivy-design/src/main/java/com/ivy/design/l3_ivyComponents/ScreenTitle.kt
ILIYANGERMANOV
442,188,120
false
null
package com.ivy.design.l3_ivyComponents import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.ivy.design.l0_system.UI import com.ivy.design.l0_system.colorAs import com.ivy.design.utils.IvyComponentPreview @Composable fun ScreenTitleLarge( text: String, paddingStart: Dp = 0.dp, textColor: Color = UI.colors.primary ) { ScreenTitle( modifier = Modifier .padding(start = paddingStart), text = text, textStyle = UI.typo.h1.colorAs(textColor) ) } @Composable fun ScreenTitle( text: String, paddingStart: Dp = 0.dp, textColor: Color = UI.colors.primary ) { ScreenTitle( modifier = Modifier .padding(start = paddingStart), text = text, textStyle = UI.typo.h2.colorAs(textColor) ) } @Composable fun ScreenTitle( modifier: Modifier = Modifier, text: String, textStyle: TextStyle ) { Text( modifier = modifier, text = text, style = textStyle ) } @Preview @Composable private fun Preview_Large() { IvyComponentPreview { ScreenTitleLarge(text = "Home") } } @Preview @Composable private fun Preview_Standard() { IvyComponentPreview { ScreenTitle(text = "Home") } }
0
Kotlin
1
1
eab596d90f3580dea527d404a0f453e5b9d2167e
1,576
ivy-design-android
MIT License
shared-client/src/commonMain/kotlin/ml/dev/kotlin/minigames/shared/ui/component/set/SetCard.kt
avan1235
455,960,870
false
null
package ml.dev.kotlin.minigames.shared.ui.component.set import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.Surface import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.min import ml.dev.kotlin.minigames.shared.model.* import ml.dev.kotlin.minigames.shared.ui.component.SizedCanvas import ml.dev.kotlin.minigames.shared.ui.theme.* @OptIn(ExperimentalAnimationApi::class) @Composable internal fun SetCard( setCardData: SetCard, selected: Boolean, width: Dp, height: Dp, padding: Dp = 6.dp, elevation: Dp = 4.dp, onClick: () -> Unit ) { val count = when (setCardData.count) { CardCount.One -> 1 CardCount.Two -> 2 CardCount.Three -> 3 } val color = when (setCardData.color) { CardColor.Green -> GreenColor CardColor.Purple -> PurpleColor CardColor.Pink -> PinkColor } val fill = when (setCardData.fill) { CardFill.Full -> fullFill CardFill.Part -> partFill CardFill.None -> noneFill } val innerWidth = width - elevation * 2 val innerHeight = height - elevation * 2 val elementWidth = innerWidth - padding * 2 val elementHeight = (innerHeight - padding * 4) / 3 Box( modifier = Modifier.size(width, height), contentAlignment = Alignment.Center ) { Surface( modifier = Modifier.size(innerWidth, innerHeight), elevation = elevation, shape = Shapes.large, ) { Column( modifier = Modifier .fillMaxHeight() .background(Color.White), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { repeat(count) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { when (setCardData.shape) { CardShape.Diamond -> Diamond(elementWidth, elementHeight, color, fill) CardShape.Oval -> Oval(elementWidth, elementHeight, color, fill) CardShape.Squiggle -> Squiggle(elementWidth, elementHeight, color, fill) } } if (it < count - 1) { Spacer(modifier = Modifier.height(padding)) } } } } AnimatedVisibility( visible = selected, enter = fadeIn(), exit = fadeOut(), ) { Box( modifier = Modifier .fillMaxSize() .padding(12.dp), contentAlignment = Alignment.BottomEnd ) { Box( modifier = Modifier .size(min(innerWidth, innerHeight) / 5) .clip(CircleShape) .background(BlueColor) .padding(2.dp), contentAlignment = Alignment.Center ) { Icon(imageVector = Icons.Default.Check, contentDescription = "check", tint = Color.White) } } } Box( modifier = Modifier .padding(padding) .size(innerWidth, innerHeight) .clip(Shapes.large) .clickable { onClick() } ) } } @Composable private fun Diamond( width: Dp, height: Dp, color: Color, fill: DrawScope.(color: Color) -> Unit, ) { SizedCanvas(width, height) { val path = Path() path.moveTo(0f, size.height / 2) path.lineTo(size.width / 2, 0f) path.lineTo(size.width, size.height / 2) path.lineTo(size.width / 2, size.height) path.lineTo(0f, size.height / 2) clipPath( path = path, clipOp = ClipOp.Intersect ) { drawPath( path = path, color = color, style = stroke(width, height, this), ) fill(color) } } } @Composable private fun Oval( width: Dp, height: Dp, color: Color, fill: DrawScope.(color: Color) -> Unit, ) { SizedCanvas(width, height) { val path = Path() path.arcTo( rect = Rect( 0f, 0f, size.width / 2, size.height ), startAngleDegrees = 90f, sweepAngleDegrees = 180f, forceMoveTo = false, ) path.lineTo(size.width - size.height / 2, 0f) path.arcTo( rect = Rect(size.width - size.height, 0f, size.width, size.height), startAngleDegrees = 270f, sweepAngleDegrees = 180f, forceMoveTo = false, ) path.lineTo( size.height / 2, size.height ) clipPath( path = path, clipOp = ClipOp.Intersect ) { drawPath( path = path, color = color, style = stroke(width, height, this) ) fill(color) } } } @Composable private fun Squiggle( width: Dp, height: Dp, color: Color, fill: DrawScope.(color: Color) -> Unit, ) { SizedCanvas(width, height) { val path = Path() path.moveTo( size.width * 0.936f, size.height * 0.27f ) path.cubicTo( size.width * 1.0116f, size.height * 0.6642f, size.width * 0.8073f, size.height * 1.0944f, size.width * 0.567f, size.height * 0.972f ) path.cubicTo( size.width * 0.4707f, size.height * 0.9234f, size.width * 0.3798f, size.height * 0.756f, size.width * 0.243f, size.height * 0.954f ) path.cubicTo( size.width * 0.0864f, size.height * 1.1808f, size.width * 0.0486f, size.height * 1.0493999999999999f, size.width * 0.045f, size.height * 0.72f ) path.cubicTo( size.width * 0.0414f, size.height * 0.396f, size.width * 0.1719f, size.height * 0.1746f, size.width * 0.324f, size.height * 0.216f ) path.cubicTo( size.width * 0.5328f, size.height * 0.2736f, size.width * 0.5571f, size.height * 0.567f, size.width * 0.801f, size.height * 0.252f ) path.cubicTo( size.width * 0.8577f, size.height * 0.18f, size.width * 0.9081f, size.height * 0.1242f, size.width * 0.936f, size.height * 0.27f ) path.translate(Offset(0f, -size.height * 0.123f)) clipPath( path = path, clipOp = ClipOp.Intersect ) { drawPath( path = path, color = color, style = stroke(width, height, this) ) fill(color) } } } private val partFill: DrawScope.(Color) -> Unit = { color -> val count = 24 repeat(count) { drawRect( topLeft = Offset(it * (1f / (count + 0.5f)) * size.width, 0f), color = color, size = Size( 1f / (count + 0.5f) / 2 * size.width, size.height ) ) } } private val fullFill: DrawScope.(Color) -> Unit = { color -> drawRect( topLeft = Offset.Zero, color = color, size = Size(size.width, size.height) ) } private val noneFill: DrawScope.(Color) -> Unit = { } private fun stroke(width: Dp, height: Dp, density: Density): DrawStyle = with(density) { Stroke(width = (min(width, height) / 10).toPx() + 1f) }
0
null
3
57
cc6696090b503b36e5289834ac83ae1ce57cb84e
9,096
mini-games
MIT License
buildSrc/src/main/kotlin/AndroidX.kt
Czeach
439,389,096
false
{"Kotlin": 78963, "Swift": 345}
object AndroidX { private const val appCompatVersion = "1.3.0-rc01" const val appCompat = "androidx.appcompat:appcompat:$appCompatVersion" private const val coreVersion = "1.6.0" const val core = "androidx.core:core-ktx:$coreVersion" }
0
Kotlin
0
1
1375fb8b5c8e4a96212337d5bef22a7f6458be63
252
Breaking-Bad
MIT License
web/src/test/kotlin/no/nav/su/se/bakover/web/routes/søknadsbehandling/IverksettSøknadsbehandlingRouteTest.kt
navikt
227,366,088
false
{"Kotlin": 8954579, "Shell": 3838, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.web.routes.søknadsbehandling import arrow.core.left import arrow.core.right import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.ktor.client.request.header import io.ktor.client.request.patch import io.ktor.client.statement.bodyAsText import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.server.testing.testApplication import no.nav.su.se.bakover.common.Brukerrolle import no.nav.su.se.bakover.domain.oppdrag.UtbetalingFeilet import no.nav.su.se.bakover.domain.søknadsbehandling.SøknadsbehandlingService import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.IverksettSøknadsbehandlingCommand import no.nav.su.se.bakover.domain.søknadsbehandling.iverksett.KunneIkkeIverksetteSøknadsbehandling import no.nav.su.se.bakover.service.søknadsbehandling.SøknadsbehandlingServices import no.nav.su.se.bakover.test.iverksattSøknadsbehandlingUføre import no.nav.su.se.bakover.web.TestServicesBuilder import no.nav.su.se.bakover.web.defaultRequest import no.nav.su.se.bakover.web.jwtStub import no.nav.su.se.bakover.web.requestSomAttestant import no.nav.su.se.bakover.web.routes.sak.sakPath import no.nav.su.se.bakover.web.stubs.asBearerToken import no.nav.su.se.bakover.web.testSusebakover import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import java.util.UUID internal class IverksettSøknadsbehandlingRouteTest { private val navIdentSaksbehandler = "random-saksbehandler-id" private val navIdentAttestant = "random-attestant-id" @Test fun `Forbidden når den som behandlet saken prøver å attestere seg selv`() { testApplication { application { testSusebakover( services = TestServicesBuilder.services( søknadsbehandling = SøknadsbehandlingServices( søknadsbehandlingService = mock(), iverksettSøknadsbehandlingService = mock { on { iverksett(any<IverksettSøknadsbehandlingCommand>()) } doReturn KunneIkkeIverksetteSøknadsbehandling.AttestantOgSaksbehandlerKanIkkeVæreSammePerson.left() }, ), ), ) } client.patch("$sakPath/${UUID.randomUUID()}/behandlinger/${UUID.randomUUID()}/iverksett") { header( HttpHeaders.Authorization, jwtStub.createJwtToken( subject = "random", roller = listOf(Brukerrolle.Attestant), navIdent = navIdentSaksbehandler, ).asBearerToken(), ) }.apply { status shouldBe HttpStatusCode.Forbidden } } } @Test fun `OK når bruker er attestant, og sak ble behandlet av en annen person`() { testApplication { application { testSusebakover( services = TestServicesBuilder.services( søknadsbehandling = SøknadsbehandlingServices( søknadsbehandlingService = mock(), iverksettSøknadsbehandlingService = mock { on { iverksett(any<IverksettSøknadsbehandlingCommand>()) } doReturn iverksattSøknadsbehandlingUføre().right() }, ), ), ) } client.patch("$sakPath/${UUID.randomUUID()}/behandlinger/${UUID.randomUUID()}/iverksett") { header( HttpHeaders.Authorization, jwtStub.createJwtToken( subject = "random", roller = listOf(Brukerrolle.Attestant), navIdent = navIdentAttestant, ).asBearerToken(), ) }.apply { status shouldBe HttpStatusCode.OK } } } @Test fun `Feiler dersom man ikke får sendt til utbetaling`() { testApplication { application { testSusebakover( services = TestServicesBuilder.services( søknadsbehandling = SøknadsbehandlingServices( søknadsbehandlingService = mock(), iverksettSøknadsbehandlingService = mock { on { iverksett(any<IverksettSøknadsbehandlingCommand>()) } doReturn KunneIkkeIverksetteSøknadsbehandling.KunneIkkeUtbetale(UtbetalingFeilet.Protokollfeil) .left() }, ), ), ) } requestSomAttestant( HttpMethod.Patch, "$sakPath/${UUID.randomUUID()}/behandlinger/${UUID.randomUUID()}/iverksett", ).apply { status shouldBe HttpStatusCode.InternalServerError bodyAsText() shouldContain "Kunne ikke utføre utbetaling" } } } @Test fun `Forbidden når bruker ikke er attestant`() { testApplication { application { testSusebakover( services = TestServicesBuilder.services( søknadsbehandling = SøknadsbehandlingServices( søknadsbehandlingService = mock { on { hent(any()) } doReturn SøknadsbehandlingService.FantIkkeBehandling.left() }, iverksettSøknadsbehandlingService = mock(), ), ), ) } defaultRequest( HttpMethod.Patch, "$sakPath/rubbish/behandlinger/${UUID.randomUUID()}/iverksett", listOf(Brukerrolle.Saksbehandler), navIdentSaksbehandler, ).apply { status shouldBe HttpStatusCode.Forbidden } defaultRequest( HttpMethod.Patch, "$sakPath/${UUID.randomUUID()}/behandlinger/${UUID.randomUUID()}/iverksett", listOf(Brukerrolle.Saksbehandler), ).apply { status shouldBe HttpStatusCode.Forbidden } } } }
9
Kotlin
1
1
d7157394e11b5b3c714a420a96211abb0a53ea45
6,587
su-se-bakover
MIT License
opendc-experiments/opendc-experiments-tf20/src/main/kotlin/org/opendc/experiments/tf20/keras/shape/TensorShape.kt
atlarge-research
79,902,234
false
{"Kotlin": 1488033, "Java": 655053, "JavaScript": 339348, "MDX": 28948, "CSS": 18038, "Dockerfile": 3592, "Shell": 280}
/* * Copyright (c) 2021 AtLarge Research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opendc.experiments.tf20.keras.shape import kotlin.math.abs /** * Represents the shape of a tensor. * * @param dims The sizes of the tensor dimensions. */ public class TensorShape(vararg dims: Long) { /** * The dimensions of the tensor represented as [LongArray]. */ private val localDims: LongArray = dims /** * Return amount of elements in Tensor with the given shape. */ public val numElements: Long get() { var prod = 1L for (i in 0 until rank) { prod *= abs(localDims[i]) } return prod } /** * Returns the rank of this shape. */ public val rank: Int get() = localDims.size /** * Returns the value of a dimension * * @param i The index at which to retrieve a dimension. * @return The size of dimension i */ public operator fun get(i: Int): Long { return localDims[i] } /** * Test whether dimension i in this shape is known * * @param i Target dimension to test * @return Whether dimension i is unknown (equal to -1) */ private fun isKnown(i: Int): Boolean { return localDims[i] != -1L } /** * Get the size of a target dimension. * * @param i Target dimension. * @return The size of dimension i */ public fun size(i: Int): Long { return localDims[i] } /** * Clone the [TensorShape] and return a new instance. */ public fun clone(): TensorShape { return TensorShape(*localDims) } /** * Create a string representation of this [TensorShape]. */ override fun toString(): String { return localDims.contentToString().replace("-1", "None") } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TensorShape if (!localDims.contentEquals(other.localDims)) return false return true } override fun hashCode(): Int { return localDims.contentHashCode() } }
34
Kotlin
46
68
5047e4a25a0814f96852882f02c4017e1d5f81e7
3,279
opendc
MIT License
src/test/kotlin/com/devstromo/behavioral/template/pattern/TemplateMethodPatternUnitTest.kt
devstromo
726,667,072
false
{"Kotlin": 50616}
package com.devstromo.behavioral.template.pattern import org.junit.jupiter.api.Test import org.mockito.Mockito.* class TemplateMethodPatternUnitTest { @Test fun `Test CSVDataProcessor steps`() { val csvProcessor = spy(CSVDataProcessor()) csvProcessor.process() val inOrder = inOrder(csvProcessor) inOrder.verify(csvProcessor).readData() inOrder.verify(csvProcessor).processData() inOrder.verify(csvProcessor).writeData() } @Test fun `Test JSONDataProcessor steps`() { val jsonProcessor = spy(JSONDataProcessor()) jsonProcessor.process() val inOrder = inOrder(jsonProcessor) inOrder.verify(jsonProcessor).readData() inOrder.verify(jsonProcessor).processData() inOrder.verify(jsonProcessor).writeData() } }
0
Kotlin
0
0
a3c4640e86cc92125c3e4370c995fda2b6e12f92
831
design-patterns-kotlin
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/modules/nft/NftManager.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.bankwallet.modules.nft import io.horizontalsystems.bankwallet.core.ICoinManager import io.horizontalsystems.bankwallet.entities.Account import io.horizontalsystems.bankwallet.entities.Address import io.horizontalsystems.bankwallet.entities.CoinValue import io.horizontalsystems.bankwallet.modules.hsnft.HsNftApiV1Response import io.horizontalsystems.bankwallet.modules.nft.asset.NftAssetModuleAssetItem import io.horizontalsystems.marketkit.models.CoinType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt class NftManager( private val nftDao: NftDao, private val apiProvider: INftApiProvider, private val coinManager: ICoinManager ) { suspend fun getCollectionAndAssetsFromCache(accountId: String): Map<NftCollectionRecord, List<NftAssetRecord>> { val collections = nftDao.getCollections(accountId) val assets = nftDao.getAssets(accountId) return map(assets, collections) } suspend fun getCollectionAndAssetsFromApi( account: Account, address: Address ): Map<NftCollectionRecord, List<NftAssetRecord>> = withContext(Dispatchers.IO) { val collections = apiProvider.getCollectionRecords(address, account) val assets = apiProvider.getAssetRecords(address, account) nftDao.replaceCollectionAssets(account.id, collections, assets) map(assets, collections) } private fun map( assets: List<NftAssetRecord>, collections: List<NftCollectionRecord> ): Map<NftCollectionRecord, List<NftAssetRecord>> { val assetsGroupByCollection = assets.groupBy { it.collectionUid } return collections.associateWith { val collectionAssets = assetsGroupByCollection[it.uid] ?: listOf() collectionAssets }.toSortedMap { o1, o2 -> o1.name.compareTo(o2.name, ignoreCase = true) } } fun nftAssetPriceToCoinValue(nftAssetPrice: NftAssetPrice?): CoinValue? { if (nftAssetPrice == null) return null return coinManager.getPlatformCoin(CoinType.fromId(nftAssetPrice.coinTypeId)) ?.let { platformCoin -> CoinValue(platformCoin, nftAssetPrice.value) } } fun assetItem( assetRecord: NftAssetRecord, collectionName: String, collectionLinks: HsNftApiV1Response.Collection.Links?, totalSupply: Int, averagePrice7d: NftAssetPrice? = null, averagePrice30d: NftAssetPrice? = null, floorPrice: NftAssetPrice? = null, bestOffer: NftAssetPrice? = null, sale: NftAssetModuleAssetItem.Sale? = null ) = NftAssetModuleAssetItem( name = assetRecord.name, imageUrl = assetRecord.imageUrl, collectionName = collectionName, collectionUid = assetRecord.collectionUid, description = assetRecord.description, contract = assetRecord.contract, tokenId = assetRecord.tokenId, assetLinks = assetRecord.links, collectionLinks = collectionLinks, stats = NftAssetModuleAssetItem.Stats( lastSale = priceItem(assetRecord.lastSale), average7d = priceItem(averagePrice7d), average30d = priceItem(averagePrice30d), collectionFloor = priceItem(floorPrice), bestOffer = priceItem(bestOffer), sale = sale ), onSale = assetRecord.onSale, attributes = assetRecord.attributes.map { attribute -> NftAssetModuleAssetItem.Attribute( attribute.type, attribute.value, getAttributePercentage(attribute, totalSupply)?.let { "$it%" }, getAttributeSearchUrl(attribute, assetRecord.collectionUid) ) } ) private fun priceItem(price: NftAssetPrice?) = nftAssetPriceToCoinValue(price)?.let { NftAssetModuleAssetItem.Price(it) } private fun getAttributeSearchUrl(attribute: NftAssetAttribute, collectionUid: String): String { return "https://opensea.io/assets/${collectionUid}?search[stringTraits][0][name]=${attribute.type}" + "&search[stringTraits][0][values][0]=${attribute.value}" + "&search[sortAscending]=true&search[sortBy]=PRICE" } private fun getAttributePercentage(attribute: NftAssetAttribute, totalSupply: Int): Number? = if (attribute.count > 0 && totalSupply > 0) { val percent = (attribute.count * 100f / totalSupply) when { percent >= 10 -> percent.roundToInt() percent >= 1 -> (percent * 10).roundToInt() / 10f else -> (percent * 100).roundToInt() / 100f } } else { null } }
136
Kotlin
219
402
5ce20e6e4e0f75a76496051ba6f78312bc641a51
4,786
unstoppable-wallet-android
MIT License
ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/queue/QueueACCTestSupport.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.kdsl.acceptance.tests.queue import net.nemerosa.ontrack.kdsl.acceptance.tests.support.waitUntil import net.nemerosa.ontrack.kdsl.spec.Ontrack import net.nemerosa.ontrack.kdsl.spec.extension.queue.QueueRecordState import net.nemerosa.ontrack.kdsl.spec.extension.queue.queue class QueueACCTestSupport( private val ontrack: Ontrack, ) { fun waitForQueueRecordToBe(queueID: String, state: QueueRecordState) { waitUntil( task = "Queue record $queueID must be in state $state", initial = 1_000L, timeout = 30_000L, ) { val record = ontrack.queue.findQueueRecordByID(queueID) record != null && record.state == state } } fun postMockMessage(message: String): String = ontrack.queue.mock.post(message) }
44
null
27
96
fde26a48ea7b18689851fe579635f4ed72ad2c5a
856
ontrack
MIT License
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/algorithms/painter/stripe/refentry/AbstractReferenceEntryStripePainter.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meistercharts.algorithms.painter.stripe.refentry import com.meistercharts.algorithms.painter.stripe.AbstractStripePainter import com.meistercharts.history.HistoryEnumSet import com.meistercharts.history.ReferenceEntryData import com.meistercharts.history.ReferenceEntryDataSeriesIndex import com.meistercharts.history.ReferenceEntryDifferentIdsCount import com.meistercharts.history.ReferenceEntryId /** * Abstract base class for referenceEntry stripe painters */ abstract class AbstractReferenceEntryStripePainter : AbstractStripePainter<ReferenceEntryDataSeriesIndex, ReferenceEntryId, ReferenceEntryDifferentIdsCount, HistoryEnumSet, ReferenceEntryData?>(), ReferenceEntryStripePainter { /** * Provides the current aggregation mode */ abstract val configuration: Configuration override fun paintingVariables(): ReferenceEntryStripePainterPaintingVariables { return paintingVariables } /** * The painting properties that are held */ private val paintingVariables = ReferenceEntryStripePainterPaintingVariables() override fun haveRelevantValuesChanged(dataSeriesIndex: ReferenceEntryDataSeriesIndex, value1: ReferenceEntryId, value2: ReferenceEntryDifferentIdsCount, value3: HistoryEnumSet, value4: ReferenceEntryData?): Boolean { val paintingVariablesForDataSeries = forDataSeriesIndex(dataSeriesIndex) val currentId = paintingVariablesForDataSeries.currentValue1 val currentCount = paintingVariablesForDataSeries.currentValue2 val currentEnumSet = paintingVariablesForDataSeries.currentValue3 val currentReferenceData = paintingVariablesForDataSeries.currentValue4 //do not check - these values must never change for the same [ReferenceEntryId] return currentId != value1 || currentCount != value2 || currentEnumSet != value3 } open class Configuration { } }
3
null
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
2,463
meistercharts
Apache License 2.0
app/src/main/java/com/car_inspection/library/MiscUtils.kt
ProjectFreelancerMobile
143,440,982
false
{"Java": 685952, "Kotlin": 291627, "IDL": 11675}
package com.car_inspection.library import android.content.Context import android.content.res.Configuration /** * Created by wanglei on 05/01/2018. */ object MiscUtils { fun isOrientationLandscape(context: Context): Boolean { val isOrientationLandscape: Boolean val orientation = context.resources.configuration.orientation isOrientationLandscape = when (orientation) { Configuration.ORIENTATION_LANDSCAPE -> true Configuration.ORIENTATION_PORTRAIT -> false else -> false } return isOrientationLandscape } }
1
null
1
1
aa2d2a67a684ebbc021b42d27fa2ed7ac7dafd12
596
Car_Inspection
MIT License
app/src/main/kotlin/com/rahulografy/axmecomm/ui/main/home/productfilter/ProductFilterFragmentViewModel.kt
RahulSDeshpande
293,636,598
false
null
package com.rahulografy.axmecomm.ui.main.home.productfilter import androidx.databinding.ObservableField import com.rahulografy.axmecomm.ui.base.view.BaseViewModel import com.rahulografy.axmecomm.ui.main.home.productfilter.manager.ProductFilterManager import com.rahulografy.axmecomm.ui.main.home.productfilter.model.ProductFilterCategoryItem import com.rahulografy.axmecomm.util.SingleLiveEvent import javax.inject.Inject class ProductFilterFragmentViewModel @Inject constructor( private val productFilterManager: ProductFilterManager ) : BaseViewModel() { val productFilterCategoryItemList = ObservableField<List<ProductFilterCategoryItem>>() val productFilterSaveEvent = SingleLiveEvent<Boolean>() val productFilterCancelEvent = SingleLiveEvent<Boolean>() val productFilterResetEvent = SingleLiveEvent<Boolean>() fun getProductFilterCategoryItemList() = productFilterManager.productFilterCategoryItemListFinal fun onProductFilterItemSelected( productFilterCategoryItem: ProductFilterCategoryItem, productCategoryItemId: Int, productCategoryItemValue: String, productItemId: Int, productItemValue: String, isSelected: Boolean ) { productFilterManager.onProductFilterItemSelected( productCategoryItemId = productCategoryItemId, productCategoryItemValue = productCategoryItemValue, productItemId = productItemId, productItemValue = productItemValue, productFilterCategoryItem = productFilterCategoryItem, isSelected = isSelected ) } fun saveProductFilter() { productFilterManager.updateProductFilterCategoryItemListTempToFinal() productFilterSaveEvent.value = true } fun cancelProductFilter() { productFilterManager.resetProductFilterCategoryItemListTemp() productFilterCancelEvent.value = true } fun resetProductFilter() { productFilterManager.resetProductFilterCategoryItemListTempAndFinal() productFilterResetEvent.value = true } }
0
Kotlin
0
2
bc7c1bb7aabae352bbe567a415b4b6bec1642a28
2,086
dctk-axm-ecomm-android
MIT License
app/src/main/java/io/customer/remotehabits/ui/component/Card.kt
customerio
355,687,244
false
null
package io.customer.remotehabits.ui.component import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.customer.remotehabits.ui.theme.RHTheme @Composable fun RemoteHabitCard( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Card( backgroundColor = RHTheme.colors.cardBackground, shape = RoundedCornerShape(size = 12.dp), border = BorderStroke(width = 1.dp, color = RHTheme.colors.surface), modifier = modifier ) { content() } }
3
Kotlin
0
1
5b0468b6a3379f329c078540c7a5e18a23488e2a
721
RemoteHabits-Android
MIT License
src/main/kotlin/ch02/2.4.3_1_IteratingOverMaps.kt
Kotlin
531,157,893
false
{"Kotlin": 49621, "Java": 876}
package ch02.ex4_3_1_IteratingOverMaps import java.util.TreeMap fun main() { val binaryReps = TreeMap<Char, String>() for (c in 'A'..'F') { val binary = c.code.toString(radix = 2) binaryReps[c] = binary } for ((letter, binary) in binaryReps) { println("$letter = $binary") } }
0
Kotlin
4
30
ed05aed5460e379145a7bd531ac15c7fa2f53f33
324
kotlin-in-action-2e
MIT License
src/main/kotlin/com/amazon/ion/plugin/intellij/helpers/ContentCorrectnessHelper.kt
amazon-ion
60,200,377
false
null
package com.amazon.ion.plugin.intellij.helpers import org.apache.commons.codec.binary.Base64 object ContentCorrectnessHelper { /** * Validates that a sequence of character is valid Base64. This is in order * to validate Ion Blobs. * * Should not return an exception, only true or false if the content is invalid. */ @JvmStatic fun isValidBase64(text: CharSequence) = runCatching { text.toString() == String( Base64.decodeBase64(text.toString()) ).let { Base64.encodeBase64String(it.toByteArray()) } }.getOrElse { false } }
13
null
22
29
3dab4e1787dee0e4ddb9c5336c781ec1652cd412
604
ion-intellij-plugin
Apache License 2.0
src/main/kotlin/kotlinmud/attributes/mapper/AttributeMapper.kt
brandonlamb
275,313,206
true
{"Kotlin": 435931, "Dockerfile": 133, "Shell": 126}
package kotlinmud.attributes.mapper import kotlinmud.attributes.model.Attributes import kotlinmud.fs.helper.end fun mapAttributeList(attributes: List<Attributes>): String { return attributes.joinToString { mapAttributes(it) } + end() } fun mapAttributes(attributes: Attributes): String { return """${attributes.strength} ${attributes.intelligence} ${attributes.wisdom} ${attributes.dexterity} ${attributes.constitution}~ ${attributes.hp} ${attributes.mana} ${attributes.mv}~ ${attributes.hit} ${attributes.dam}~ ${attributes.acSlash} ${attributes.acBash} ${attributes.acPierce} ${attributes.acMagic}~""" }
0
null
0
0
fc03c6230b9b3b66cd63994e74ddd7897732d527
617
kotlinmud
MIT License
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/platform/WindowManager.kt
komamj
332,680,050
true
{"Java Properties": 43, "Shell": 59, "Markdown": 61, "Java": 5103, "HTML": 17, "Kotlin": 4410, "Python": 32, "Proguard": 41, "Batchfile": 13, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 2, "C++": 4}
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.runtime.Composable import androidx.compose.runtime.ExperimentalComposeApi import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.snapshots.snapshotFlow import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.collect /** * Provides information about the Window that is hosting this compose hierarchy. */ @Stable interface WindowManager { /** * Indicates whether the window hosting this compose hierarchy is in focus. * * When there are multiple windows visible, either in a multi-window environment or if a * popup or dialog is visible, this property can be used to determine if the current window * is in focus. */ val isWindowFocused: Boolean } /** * Provides a callback that is called whenever the window gains or loses focus. */ @OptIn( ExperimentalComposeApi::class, InternalCoroutinesApi::class ) @Composable fun WindowFocusObserver(onWindowFocusChanged: (isWindowFocused: Boolean) -> Unit) { val windowManager = AmbientWindowManager.current val callback = rememberUpdatedState(onWindowFocusChanged) LaunchedEffect(windowManager) { snapshotFlow { windowManager.isWindowFocused }.collect { callback.value(it) } } } internal class WindowManagerImpl : WindowManager { private val _isWindowFocused = mutableStateOf(false) override var isWindowFocused: Boolean set(value) { _isWindowFocused.value = value } get() = _isWindowFocused.value }
0
null
0
0
f42c5f033a9e71bbaf580392cebaa6b274f2aca0
2,305
androidx
Apache License 2.0
okhttp/src/jvmTest/java/okhttp3/HeadersKotlinTest.kt
yschimke
42,286,486
false
null
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.time.Instant import java.util.Date import okhttp3.Headers.Companion.headersOf import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class HeadersKotlinTest { @Test fun getOperator() { val headers = headersOf("a", "b", "c", "d") assertThat(headers["a"]).isEqualTo("b") assertThat(headers["c"]).isEqualTo("d") assertThat(headers["e"]).isNull() } @Test fun iteratorOperator() { val headers = headersOf("a", "b", "c", "d") val pairs = mutableListOf<Pair<String, String>>() for ((name, value) in headers) { pairs += name to value } assertThat(pairs).containsExactly("a" to "b", "c" to "d") } @Test fun builderGetOperator() { val builder = Headers.Builder() builder.add("a", "b") builder.add("c", "d") assertThat(builder["a"]).isEqualTo("b") assertThat(builder["c"]).isEqualTo("d") assertThat(builder["e"]).isNull() } @Test fun builderSetOperator() { val builder = Headers.Builder() builder["a"] = "b" builder["c"] = "d" builder["e"] = Date(0L) builder["g"] = Instant.EPOCH assertThat(builder.get("a")).isEqualTo("b") assertThat(builder.get("c")).isEqualTo("d") assertThat(builder.get("e")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT") assertThat(builder.get("g")).isEqualTo("Thu, 01 Jan 1970 00:00:00 GMT") } }
2
null
9159
6
ef459b1d8b0530c915386c527e8a141c88cd5c15
1,988
okhttp
Apache License 2.0
verik-compiler/src/main/kotlin/io/verik/compiler/core/declaration/vk/CoreVkUnpacked.kt
frwang96
269,980,078
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ package io.verik.compiler.core.declaration.vk import io.verik.compiler.ast.element.expression.common.ECallExpression import io.verik.compiler.ast.element.expression.common.EExpression import io.verik.compiler.ast.element.expression.common.EReferenceExpression import io.verik.compiler.core.common.Core import io.verik.compiler.core.common.CorePropertyDeclaration import io.verik.compiler.core.common.CoreScope import io.verik.compiler.core.common.TransformableCoreFunctionDeclaration import io.verik.compiler.resolve.TypeConstraint /** * Core declarations from Unpacked. */ object CoreVkUnpacked : CoreScope(Core.Vk.C_Unpacked) { val P_size = object : CorePropertyDeclaration(parent, "size") { override fun transform(referenceExpression: EReferenceExpression): EExpression { return CoreVkPacked.P_size.transform(referenceExpression) } } val F_get_Int = object : TransformableCoreFunctionDeclaration(parent, "get", "fun get(Int)") { override fun getTypeConstraints(callExpression: ECallExpression): List<TypeConstraint> { return CoreVkPacked.F_get_Int.getTypeConstraints(callExpression) } override fun transform(callExpression: ECallExpression): EExpression { return CoreVkPacked.F_get_Int.transform(callExpression) } } val F_get_Ubit = object : TransformableCoreFunctionDeclaration(parent, "get", "fun get(Ubit)") { override fun getTypeConstraints(callExpression: ECallExpression): List<TypeConstraint> { return CoreVkPacked.F_get_Ubit.getTypeConstraints(callExpression) } override fun transform(callExpression: ECallExpression): EExpression { return CoreVkPacked.F_get_Ubit.transform(callExpression) } } val F_set_Int_E = object : TransformableCoreFunctionDeclaration(parent, "set", "fun set(Int, E)") { override fun getTypeConstraints(callExpression: ECallExpression): List<TypeConstraint> { return CoreVkPacked.F_set_Int_E.getTypeConstraints(callExpression) } override fun transform(callExpression: ECallExpression): EExpression { return CoreVkPacked.F_set_Int_E.transform(callExpression) } } val F_set_Ubit_E = object : TransformableCoreFunctionDeclaration(parent, "set", "fun set(E)") { override fun getTypeConstraints(callExpression: ECallExpression): List<TypeConstraint> { return CoreVkPacked.F_set_Ubit_E.getTypeConstraints(callExpression) } override fun transform(callExpression: ECallExpression): EExpression { return CoreVkPacked.F_set_Ubit_E.transform(callExpression) } } }
0
Kotlin
1
33
ee22969235460fd144294bcbcbab0338c638eb92
2,744
verik
Apache License 2.0
ComposeViews/src/commonMain/kotlin/com/lt/compose_views/chain_scrollable_component/ChainScrollableComponentState.kt
ltttttttttttt
370,338,027
false
null
/* * Copyright lt 2023 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lt.compose_views.chain_scrollable_component import androidx.compose.animation.core.Animatable import androidx.compose.runtime.Stable import com.lt.compose_views.util.ComposePosition import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlin.math.abs /** * creator: lt 2022/9/29 <EMAIL> * effect : [ChainScrollableComponent]的状态 * State of the [ChainScrollableComponent] * warning: */ @Stable class ChainScrollableComponentState internal constructor( val minPx: Float, val maxPx: Float, val composePosition: ComposePosition, val coroutineScope: CoroutineScope, private val onScrollStop: ((state: ChainScrollableComponentState, delta: Float) -> Boolean)?, ) { val orientationIsHorizontal = composePosition.isHorizontal() //滚动的位置的动画对象 internal val scrollPosition = Animatable(if (composePosition == ComposePosition.Bottom || composePosition == ComposePosition.End) maxPx else 0f) /** * 获取滚动的位置的值 * Get number of scroll position */ fun getScrollPositionValue(): Float = scrollPosition.value /** * 获取滚动的位置的百分比,0f-1f,min-max * Get percentage of scroll position */ fun getScrollPositionPercentage(): Float = abs(getScrollPositionValue() / (maxPx - minPx)) /** * 修改滚动的位置 * Set number of scroll position */ fun setScrollPosition(value: Float) { coroutineScope.launch { scrollPosition.snapTo(value) } } suspend fun snapToScrollPosition(value: Float) { scrollPosition.snapTo(value) } /** * 以动画形式修改滚动的位置 * Set number of scroll position, with animate */ fun setScrollPositionWithAnimate(value: Float) { coroutineScope.launch { scrollPosition.animateTo(value) } } suspend fun animateToScrollPosition(value: Float) { scrollPosition.animateTo(value) } //调用[onScrollStop],触发停止滚动时的回调 internal fun callOnScrollStop(delta: Float): Boolean { return onScrollStop?.invoke(this, delta) == true } }
5
Kotlin
34
93
fe826432521dfdd3a06e814ef118e9bdc9608f91
2,677
ComposeViews
Apache License 2.0
ktorfit-ksp/src/main/kotlin/de/jensklingenberg/ktorfit/utils/KSFunctionDeclarationExt.kt
Foso
203,655,484
false
null
package de.jensklingenberg.ktorfit.utils import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.getAnnotationsByType import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.Modifier import de.jensklingenberg.ktorfit.model.annotations.CustomHttp import de.jensklingenberg.ktorfit.model.annotations.FormUrlEncoded import de.jensklingenberg.ktorfit.model.annotations.Headers import de.jensklingenberg.ktorfit.model.annotations.HttpMethod import de.jensklingenberg.ktorfit.model.annotations.HttpMethodAnnotation import de.jensklingenberg.ktorfit.model.annotations.Multipart import de.jensklingenberg.ktorfit.model.annotations.Streaming @OptIn(KspExperimental::class) fun KSFunctionDeclaration.getHeaderAnnotation(): Headers? { return this.getAnnotationsByType(de.jensklingenberg.ktorfit.http.Headers::class).firstOrNull()?.let { headers -> return Headers(headers.value.toList()) } } @OptIn(KspExperimental::class) fun KSFunctionDeclaration.getFormUrlEncodedAnnotation(): FormUrlEncoded? { return this.getAnnotationsByType(de.jensklingenberg.ktorfit.http.FormUrlEncoded::class).firstOrNull()?.let { return FormUrlEncoded() } } @OptIn(KspExperimental::class) fun KSFunctionDeclaration.getStreamingAnnotation(): Streaming? { return this.getAnnotationsByType(de.jensklingenberg.ktorfit.http.Streaming::class).firstOrNull()?.let { return Streaming() } } @OptIn(KspExperimental::class) fun KSFunctionDeclaration.getMultipartAnnotation(): Multipart? { return this.getAnnotationsByType(de.jensklingenberg.ktorfit.http.Multipart::class).firstOrNull()?.let { return Multipart() } } @OptIn(KspExperimental::class) fun KSFunctionDeclaration.parseHTTPMethodAnno(name: String): HttpMethodAnnotation? = when (val annotation = this.getAnnotationByName(name)) { null -> { null } else -> { if (name == "HTTP") { this.getAnnotationsByType(de.jensklingenberg.ktorfit.http.HTTP::class).firstOrNull()?.let { CustomHttp(it.path, HttpMethod.CUSTOM, it.hasBody, it.method) } } else { val value = annotation.getArgumentValueByName<String>("value").orEmpty() HttpMethodAnnotation(value, HttpMethod.valueOf(name)) } } } private fun KSFunctionDeclaration.getAnnotationByName(name: String): KSAnnotation? = this.annotations.toList().firstOrNull { it.shortName.asString() == name } fun <T> KSAnnotation.getArgumentValueByName(name: String): T? = this.arguments.firstOrNull { it.name?.asString() == name }?.value as? T val KSFunctionDeclaration.isSuspend: Boolean get() = (this).modifiers.contains(Modifier.SUSPEND)
32
null
39
1,522
3da92274c6f168a2521ac2427388da760f231a45
2,862
Ktorfit
Apache License 2.0
start/src/main/java/com/example/healthconnect/codelab/presentation/navigation/Drawer.kt
android
626,810,909
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.healthconnectsample.presentation.navigation import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement 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.height import androidx.compose.foundation.layout.width import androidx.compose.material.ScaffoldState import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.healthconnectsample.R import com.example.healthconnectsample.presentation.theme.HealthConnectTheme import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch /** * The side navigation drawer used to explore each Health Connect feature. */ @Composable fun Drawer( scope: CoroutineScope, scaffoldState: ScaffoldState, navController: NavController ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Image( modifier = Modifier .width(96.dp) .clickable { navController.navigate(Screen.WelcomeScreen.route) { navController.graph.startDestinationRoute?.let { route -> popUpTo(route) { saveState = true } } launchSingleTop = true restoreState = true } scope.launch { scaffoldState.drawerState.close() } }, painter = painterResource(id = R.drawable.ic_health_connect_logo), contentDescription = stringResource(id = R.string.health_connect_logo) ) } Spacer(modifier = Modifier.height(16.dp)) Text( modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, text = stringResource(id = R.string.app_name) ) Spacer(modifier = Modifier.height(16.dp)) Screen.values().filter { it.hasMenuItem }.forEach { item -> DrawerItem( item = item, selected = item.route == currentRoute, onItemClick = { navController.navigate(item.route) { // See: https://developer.android.com/jetpack/compose/navigation#nav-to-composable navController.graph.startDestinationRoute?.let { route -> popUpTo(route) { saveState = true } } launchSingleTop = true restoreState = true } scope.launch { scaffoldState.drawerState.close() } } ) } } } @Preview @Composable fun DrawerPreview() { val scope = rememberCoroutineScope() val scaffoldState = rememberScaffoldState() val navController = rememberNavController() HealthConnectTheme { Drawer( scope = scope, scaffoldState = scaffoldState, navController = navController ) } }
9
null
92
8
5b74df42ad64fec9b34baf93044d8a82dda83440
4,921
android-health-connect-codelab
Apache License 2.0
kdoc-core/src/main/kotlin/kdoc/core/database/schema/admin/actor/ActorTable.kt
perracodex
819,398,266
false
{"Kotlin": 486868, "Dockerfile": 3109, "CSS": 2680, "HTML": 487}
/* * Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license. */ package kdoc.core.database.schema.admin.actor import kdoc.core.database.columns.autoGenerate import kdoc.core.database.columns.kotlinUuid import kdoc.core.database.columns.references import kdoc.core.database.schema.admin.rbac.RbacRoleTable import kdoc.core.database.schema.base.TimestampedTable import kdoc.core.security.utils.EncryptionUtils import org.jetbrains.exposed.crypt.Encryptor import org.jetbrains.exposed.crypt.encryptedVarchar import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ReferenceOption import org.jetbrains.exposed.sql.Table import kotlin.uuid.Uuid /** * Database table definition holding Actors. * An Actor is a user with specific role and designated access to a set of concrete scopes. */ public object ActorTable : TimestampedTable(name = "actor") { private val encryptor: Encryptor = EncryptionUtils.getEncryptor(type = EncryptionUtils.Type.AT_REST) /** * The unique id of the Actor record. */ public val id: Column<Uuid> = kotlinUuid( name = "actor_id" ).autoGenerate() /** * The actor's unique username. */ public val username: Column<String> = varchar( name = "username", length = 16 ).uniqueIndex( customIndexName = "uq_actor__username" ) /** * The actor's encrypted password. */ public val password: Column<String> = encryptedVarchar( name = "password", cipherTextLength = encryptor.maxColLength(inputByteSize = 128), encryptor = encryptor ) /** * The associated [RbacRoleTable] id. */ public val roleId: Column<Uuid> = kotlinUuid( name = "role_id" ).references( fkName = "fk_rbac_role__role_id", ref = RbacRoleTable.id, onDelete = ReferenceOption.RESTRICT, onUpdate = ReferenceOption.RESTRICT ) /** * Whether the Actor is locked and therefore has full restricted access. */ public val isLocked: Column<Boolean> = bool( name = "is_locked" ) override val primaryKey: Table.PrimaryKey = PrimaryKey( firstColumn = id, name = "pk_actor_id" ) }
0
Kotlin
0
0
66887c97ec65f4ce3dbd392a99fa327cdda7ffb5
2,259
kdoc
MIT License
app/src/main/kotlin/common/network/network.kt
meoyawn
42,546,144
false
{"Kotlin": 43443}
package common.network import java.net.URLEncoder fun urlEncode(s: String): String = URLEncoder.encode(s, "utf-8")
0
Kotlin
0
4
7f5e60440dd2ef318978d210a8205e568ab1f284
120
headphone-reminder
MIT License
src/main/kotlin/world/cepi/crates/rewards/RangeReward.kt
Project-Cepi
333,213,821
false
null
package world.cepi.crates.rewards import net.kyori.adventure.text.Component import net.minestom.server.coordinate.Point import net.minestom.server.entity.Player import net.minestom.server.instance.Instance import world.cepi.crates.model.LootCrate import net.minestom.server.utils.math.IntRange fun dispatchRange( range: IntRange, target: Player, lootcrate: LootCrate, instance: Instance, position: Point, lambdaProcessor: (target: Player, lootcrate: LootCrate, instance: Instance, position: Point, decidedNumber: Int) -> Component ): Component { val decidedNumber = ((range.minimum.coerceAtLeast(0))..(range.maximum.coerceAtMost(Int.MAX_VALUE))).random() return lambdaProcessor(target, lootcrate, instance, position, decidedNumber) }
3
Kotlin
0
3
ee4df4ad6155707e756d458654a17efc3702eb0f
756
LootboxExtension
MIT License
dataset/src/main/kotlin/org/jetbrains/kotlinx/dl/dataset/preprocessor/TensorPreprocessing.kt
nedimAT
403,983,430
true
{"Kotlin": 1225101, "Jupyter Notebook": 43951}
/* * Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.dataset.preprocessor /** * The whole tensor preprocessing pipeline DSL. * * It supports the following ops: * - [rescaling] See [Rescaling] preprocessor. * - [customPreprocessor] See [CustomPreprocessor] preprocessor. * * It's a part of the [org.jetbrains.kotlinx.dl.dataset.preprocessor.Preprocessing] pipeline DSL. */ public class TensorPreprocessing { /** */ public lateinit var rescaling: Rescaling /** */ public var customPreprocessors: MutableList<Preprocessor> = mutableListOf() /** True, if [rescaling] is initialized. */ public val isRescalingInitialized: Boolean get() = ::rescaling.isInitialized } /** */ public fun TensorPreprocessing.rescale(block: Rescaling.() -> Unit) { rescaling = Rescaling().apply(block) }
0
null
0
0
8bd3711471bee32a652ead7e33dbac1d914b2712
1,030
KotlinDL
Apache License 2.0
app/src/main/java/com/example/gpt/ui/composable/screen/AudioMessageScreen.kt
palexis3
620,162,996
false
null
package com.example.gpt.ui.composable.screen import android.Manifest import android.content.Context import android.content.pm.PackageManager import com.example.gpt.manager.AudioManager import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text 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.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Alignment.Companion.End import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.example.gpt.R import com.example.gpt.ui.composable.ShowCardHeader import com.example.gpt.ui.composable.ShowLoading import com.example.gpt.ui.composable.ShowMessageContent import com.example.gpt.ui.theme.EIGHT_DP import com.example.gpt.ui.theme.FOUR_DP import com.example.gpt.ui.theme.SIX_DP import com.example.gpt.ui.theme.TWELVE_DP import com.example.gpt.ui.viewmodel.AudioMessageUiState import com.example.gpt.ui.viewmodel.AudioViewModel import com.example.gpt.utils.createAudioFile import com.example.gpt.utils.fileIsNotEmpty import com.example.gpt.utils.hasMicrophone import java.io.File @OptIn(ExperimentalLifecycleComposeApi::class) @Composable fun AudioMessageScreen( audioViewModel: AudioViewModel = hiltViewModel() ) { val context = LocalContext.current val audioMessageUiState by audioViewModel.audioMessageUiState.collectAsStateWithLifecycle() val audioFile by remember { mutableStateOf(context.createAudioFile()) } val audioManager by remember { mutableStateOf(AudioManager(context, audioFile.path)) } var startPlaying by remember { mutableStateOf(false) } var startRecording by remember { mutableStateOf(false) } val permissionCheckResult = ContextCompat.checkSelfPermission( context, Manifest.permission.RECORD_AUDIO ) val permissionLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), onResult = { success -> if (success) { audioManager.startRecording() } else { Toast.makeText(context, R.string.audio_permission_denied, Toast.LENGTH_SHORT).show() } }) Column( modifier = Modifier .fillMaxSize() .padding(TWELVE_DP) .verticalScroll(rememberScrollState()) ) { Text( modifier = Modifier.align(alignment = CenterHorizontally), text = stringResource(id = R.string.record_audio), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(SIX_DP)) ShowRecordButton( modifier = Modifier.align(alignment = CenterHorizontally), context = context, startRecording = startRecording, onRecord = { shouldRecord -> startRecording = shouldRecord if (shouldRecord) { startPlaying = false audioViewModel.resetAudioUiFlow() } if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) { if (shouldRecord) { audioManager.startRecording() } else { audioManager.stopRecording() } } else { permissionLauncher.launch(Manifest.permission.RECORD_AUDIO) } }) Spacer(modifier = Modifier.height(30.dp)) if (fileIsNotEmpty(audioFile) && !startRecording) { Text( modifier = Modifier.align(alignment = CenterHorizontally), text = stringResource(id = R.string.playback_audio), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(SIX_DP)) ShowPlayButton( modifier = Modifier.align(alignment = CenterHorizontally), audioFile = audioFile, startPlaying = startPlaying, onPlay = { shouldPlay -> startPlaying = shouldPlay if (shouldPlay) { val wasPlaybackSuccessful = audioManager.startPlayback() if (!wasPlaybackSuccessful) { Toast.makeText( context, context.getString(R.string.playback_error), Toast.LENGTH_SHORT ).show() } } else { audioManager.stopPlayback() } }) Spacer(modifier = Modifier.height(30.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(TWELVE_DP), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Button( onClick = { audioViewModel.createTranscription(audioFile) }) { Text(text = stringResource(id = R.string.transcribe_audio)) } Spacer(modifier = Modifier.width(FOUR_DP)) Button( onClick = { audioViewModel.createTranslation(audioFile) }) { Text(text = stringResource(id = R.string.translate_audio)) } } Spacer(modifier = Modifier.height(32.dp)) ShowAudioMessageUiState( modifier = Modifier.align(End), audioMessageUiState ) } } } @Composable fun ShowAudioMessageUiState( modifier: Modifier, audioMessageUiState: AudioMessageUiState ) { Row( modifier = modifier, ) { when (audioMessageUiState) { is AudioMessageUiState.Uninitialized -> {} is AudioMessageUiState.Loading -> ShowLoading() is AudioMessageUiState.Error -> ShowAudioMessageContent(text = stringResource(id = R.string.error)) is AudioMessageUiState.Success -> { ShowAudioMessageContent(text = audioMessageUiState.audioMessageUi.text) } } } } @Composable fun ShowAudioMessageContent(text: String) { val cardBackgroundColor = when (text) { stringResource(id = R.string.error) -> MaterialTheme.colorScheme.errorContainer else -> MaterialTheme.colorScheme.secondaryContainer } val color = when (text) { stringResource(id = R.string.error) -> MaterialTheme.colorScheme.error else -> MaterialTheme.colorScheme.secondary } val messageModifier: Modifier = Modifier.padding( start = TWELVE_DP, top = FOUR_DP, bottom = SIX_DP, end = TWELVE_DP ) Card( modifier = Modifier .widthIn(200.dp, 275.dp) .padding(FOUR_DP), colors = CardDefaults.cardColors( containerColor = cardBackgroundColor ), elevation = CardDefaults.cardElevation( defaultElevation = EIGHT_DP ), shape = RoundedCornerShape(TWELVE_DP) ) { ShowCardHeader(text = stringResource(id = R.string.gpt)) Spacer(modifier = Modifier.height(2.dp)) ShowMessageContent( text = text, modifier = messageModifier, textStyle = TextStyle( color =color, fontSize = 18.sp ) ) } } @Composable fun ShowPlayButton( modifier: Modifier, audioFile: File, onPlay: (Boolean) -> Unit, startPlaying: Boolean ) { Button( modifier = modifier, enabled = fileIsNotEmpty(audioFile), onClick = { onPlay(!startPlaying) }) { when (startPlaying) { true -> Icon(painterResource(id = R.drawable.pause_icon), "pause") false -> Icon(imageVector = Icons.Filled.PlayArrow, contentDescription = "play") } Text( text = when (startPlaying) { true -> stringResource(id = R.string.stop_playback) false -> stringResource(id = R.string.start_playback) } ) } } @Composable fun ShowRecordButton( modifier: Modifier, context: Context, onRecord: (Boolean) -> Unit, startRecording: Boolean ) { Button( modifier = modifier, enabled = context.hasMicrophone(), onClick = { onRecord(!startRecording) }) { when (startRecording) { true -> Icon(painterResource(id = R.drawable.pause_icon), "pause") false -> Icon(imageVector = Icons.Filled.PlayArrow, contentDescription = "play") } Text( text = when (startRecording) { true -> stringResource(id = R.string.stop_recording) false -> stringResource(id = R.string.start_recording) } ) } }
1
Kotlin
1
0
da0257306cfdab8365b9e299d7c05706e838fa7b
11,037
GPT
Apache License 2.0
src/main/kotlin/org/bibletranslationtools/vtt/Subtitle.kt
Bible-Translation-Tools
791,910,914
false
{"Kotlin": 69403}
package org.bibletranslationtools.vtt interface Subtitle { /** * Returns the index of the first event that occurs after a given time (exclusive). * * @param timeUs The time in microseconds. * @return The index of the next event, or [C.INDEX_UNSET] if there are no events after the * specified time. */ fun getNextEventTimeIndex(timeUs: Long): Int /** * Returns the number of event times, where events are defined as points in time at which the cues * returned by [.getCues] changes. * * @return The number of event times. */ fun getEventTimeCount(): Int /** * Returns the event time at a specified index. * * @param index The index of the event time to obtain. * @return The event time in microseconds. */ fun getEventTime(index: Int): Long /** * Retrieve the cues that should be displayed at a given time. * * @param timeUs The time in microseconds. * @return A list of cues that should be displayed, possibly empty. */ fun getCues(timeUs: Long): List<Cue> }
0
Kotlin
0
0
fc40015a5657f2fd22b45fadab9f29d103cb1263
1,100
kotlin-vtt
Apache License 2.0
RecyclerViewDemo/app/src/main/java/com/derrick/park/recyclerviewdemo/SWAdapter.kt
nk18chi
226,992,098
true
{"Kotlin": 439531}
package com.example.recycleviewdemo import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.layout_sw_list_item.view.* interface OnSWClickListener { fun onClick(v: View, item: SWChar) } class SWAdapter(private val delegate: OnSWClickListener, private val swChars: Array<SWChar>) : RecyclerView.Adapter<SWAdapter.SWViewHolder>() { // inflates a layout and return the viewHolder object override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SWViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate(R.layout.layout_sw_list_item, parent, false) return SWViewHolder(itemView) } // tells the recyclerView how many total items we have to display override fun getItemCount(): Int = swChars.size // binds data with viewHolder override fun onBindViewHolder(holder: SWViewHolder, position: Int) { holder.bind(swChars[position]) holder.itemView.setOnClickListener { v -> delegate.onClick(v, swChars[position]) } } // ViewHolder class SWViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val nameTextView: TextView = itemView.nameTextView private val dataTextView: TextView = itemView.dataTextView fun bind(item: SWChar) { nameTextView.text = item.name dataTextView.text = "Height: ${item.height}, Mass: ${item.mass}" } } }
0
Kotlin
3
1
47a0ad057d1357ebe971e3bf0b3abddb8cd1abc4
1,602
android-kotlin-fundamentals-starter-apps
The Unlicense
src/test/kotlin/no/nav/familie/ef/sak/mapper/SøknadsskjemaMapperTest.kt
navikt
206,805,010
false
{"Kotlin": 3880816, "Gherkin": 163948, "Dockerfile": 180}
package no.nav.familie.ef.sak.mapper import no.nav.familie.ef.sak.opplysninger.søknad.mapper.SøknadsskjemaMapper import no.nav.familie.kontrakter.ef.søknad.Adresse import no.nav.familie.kontrakter.ef.søknad.Stønadsstart import no.nav.familie.kontrakter.ef.søknad.Søknadsfelt import no.nav.familie.kontrakter.ef.søknad.Testsøknad import no.nav.familie.kontrakter.ef.søknad.TestsøknadBuilder import no.nav.familie.kontrakter.ef.søknad.Utenlandsopphold import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.time.LocalDate internal class SøknadsskjemaMapperTest { @Test internal fun `skal mappe søknad som mangler datoer for stønadsstart`() { val stønadsstart = Søknadsfelt( "Stønadsstart", Stønadsstart( null, null, Søknadsfelt( "Søker du stønad fra et bestemt tidspunkt", false, ), ), ) val kontraktsøknad = Testsøknad.søknadOvergangsstønad.copy(stønadsstart = stønadsstart) val søknadTilLagring = SøknadsskjemaMapper.tilDomene(kontraktsøknad) assertThat(søknadTilLagring.søkerFraBestemtMåned).isEqualTo(false) assertThat(søknadTilLagring.søkerFra).isNull() assertThat(søknadTilLagring.datoPåbegyntSøknad).isNull() } @Test internal fun `skal mappe samboer fødselsdato`() { val nyPerson = TestsøknadBuilder.Builder().defaultPersonMinimum(fødselsdato = LocalDate.now()) val søknad = TestsøknadBuilder.Builder().setBosituasjon(samboerdetaljer = nyPerson).build().søknadOvergangsstønad val søknadTilLagring = SøknadsskjemaMapper.tilDomene(søknad) assertThat(søknadTilLagring.bosituasjon.samboer!!.fødselsdato!!).isEqualTo(LocalDate.now()) } @Test internal fun `skal mappe feltet skalBoHosSøker`() { val svarSkalBarnetBoHosSøker = "jaMenSamarbeiderIkke" val barn = TestsøknadBuilder.Builder() .defaultBarn() .copy( skalBarnetBoHosSøker = Søknadsfelt("", "", null, svarSkalBarnetBoHosSøker), ) val søknad = TestsøknadBuilder.Builder() .build().søknadOvergangsstønad.copy(barn = Søknadsfelt("", listOf(barn))) val søknadTilLagring = SøknadsskjemaMapper.tilDomene(søknad) assertThat(søknadTilLagring.barn.first().skalBoHosSøker).isEqualTo(svarSkalBarnetBoHosSøker) } @Nested inner class AdresseTilAdresseopplysninger { @Test internal fun `skal mappe adress fra personalia til opplysninger om adresse då det er den som vises til brukeren`() { val adresse = Adresse( adresse = "adresse", postnummer = "1234", poststedsnavn = "Sted", land = null, ) val søknad = TestsøknadBuilder.Builder().setPersonalia(adresse = adresse).build().søknadOvergangsstønad assertThat(SøknadsskjemaMapper.tilDomene(søknad).adresseopplysninger?.adresse).isEqualTo("adresse, 1234 Sted") } @Test internal fun `poststed skal ikke vises hvis det ikke er med`() { val adresse = Adresse( adresse = "adresse", postnummer = "1234", poststedsnavn = null, land = "Land", ) val søknad = TestsøknadBuilder.Builder().setPersonalia(adresse = adresse).build().søknadOvergangsstønad assertThat(SøknadsskjemaMapper.tilDomene(søknad).adresseopplysninger?.adresse).isEqualTo("adresse, 1234, Land") } @Test internal fun `tomme element skal håndteres`() { val adresse = Adresse( adresse = "adresse", postnummer = "", poststedsnavn = null, land = "", ) val søknad = TestsøknadBuilder.Builder().setPersonalia(adresse = adresse).build().søknadOvergangsstønad assertThat(SøknadsskjemaMapper.tilDomene(søknad).adresseopplysninger?.adresse).isEqualTo("adresse") } } @Nested inner class LandIMedlemskap { @Test internal fun `skal ikke inneholde oppholdsland om ikke sendt med`() { val søknad = TestsøknadBuilder.Builder().build().søknadOvergangsstønad val søknadTilLagring = SøknadsskjemaMapper.tilDomene(søknad) assertThat(søknadTilLagring.medlemskap.oppholdsland).isNull() } @Test internal fun `skal inneholde oppholdsland om innsendt`() { val oppholdsland = Søknadsfelt( label = "I hvilket land oppholder du deg?", verdi = "Polen", svarId = "POL", ) val søknad = TestsøknadBuilder.Builder().setMedlemskapsdetaljer(oppholdsland = oppholdsland).build().søknadOvergangsstønad val søknadTilLagring = SøknadsskjemaMapper.tilDomene(søknad) assertThat(søknadTilLagring.medlemskap.oppholdsland).isEqualTo("POL") } @Test internal fun `utenlandsperiode skal inneholde land om innsendt`() { val utenlandsperioder = listOf( Utenlandsopphold( fradato = Søknadsfelt("Fra", LocalDate.of(2021, 1, 1)), tildato = Søknadsfelt("Til", LocalDate.of(2022, 1, 1)), land = Søknadsfelt("I hvilket land oppholdt du deg i?", svarId = "ESP", verdi = "Spania"), årsakUtenlandsopphold = Søknadsfelt("Årsak til utenlandsopphold", "Ferie"), ), ) val søknad = TestsøknadBuilder.Builder().setMedlemskapsdetaljer(utenlandsopphold = utenlandsperioder).build().søknadOvergangsstønad val søknadTilLagring = SøknadsskjemaMapper.tilDomene(søknad) assertThat(søknadTilLagring.medlemskap.utenlandsopphold.first().fradato).isEqualTo(LocalDate.of(2021, 1, 1)) assertThat(søknadTilLagring.medlemskap.utenlandsopphold.first().tildato).isEqualTo(LocalDate.of(2022, 1, 1)) assertThat(søknadTilLagring.medlemskap.utenlandsopphold.first().land).isEqualTo("ESP") assertThat(søknadTilLagring.medlemskap.utenlandsopphold.first().årsakUtenlandsopphold).isEqualTo("Ferie") } } }
3
Kotlin
2
0
6334fed4ea795a48703b562f55ef3f207b60effc
6,674
familie-ef-sak
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/model/AppointmentDetails.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3867444, "Shell": 9529, "Dockerfile": 1514}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.model import com.fasterxml.jackson.annotation.JsonFormat import io.swagger.v3.oas.annotations.media.Schema import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AppointmentType import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime @Schema( description = """ Described on the UI as an "Appointment" and represents the scheduled event on a specific date and time. Contains the full details of all the appointment properties and the summary collection of prisoners attending this appointment. An appointment is part of either a series of an appointments on a schedule or a set of appointments on the same day. The summary information of which appointment collection they are part of is included in these details. All updates and cancellations happen at this appointment level with the parent appointment series being immutable. """, ) data class AppointmentDetails( @Schema( description = "The internally generated identifier for this appointment", example = "123456", ) val id: Long, @Schema( description = """ Summary of the appointment series this appointment is part of. Will be null if this appointment is part of a set of appointments on the same day. """, ) val appointmentSeries: AppointmentSeriesSummary?, @Schema( description = """ Summary of the appointment set this appointment is part of Will be null if this appointment is part of a series of an appointments on a schedule. """, ) val appointmentSet: AppointmentSetSummary?, @Schema( description = "The appointment type (INDIVIDUAL or GROUP)", example = "INDIVIDUAL", ) val appointmentType: AppointmentType, @Schema( description = "The sequence number of this appointment within the appointment series", example = "3", ) val sequenceNumber: Int, @Schema( description = "The NOMIS AGENCY_LOCATIONS.AGY_LOC_ID value for mapping to NOMIS", example = "SKI", ) val prisonCode: String, @Schema( description = """ The appointment's name combining the optional custom name with the category description. If custom name has been specified, the name format will be "Custom name (Category description)" """, ) val appointmentName: String, @Schema( description = """ Summary of the prisoner or prisoners attending this appointment and their attendance record if any. Attendees are at the appointment level to allow for per appointment attendee changes. """, ) val attendees: List<AppointmentAttendeeSummary> = emptyList(), @Schema( description = """ The summary of the appointment's category. Can be different to the parent appointment series if this appointment has been edited. """, ) val category: AppointmentCategorySummary, @Schema(description = "The tier for this appointment, as defined by the Future Prison Regime team") val tier: EventTier?, @Schema(description = "The organiser of this appointment") val organiser: EventOrganiser?, @Schema( description = """ Free text name further describing the appointment. Used as part of the appointment name with the format "Custom name (Category description) if specified. """, example = "Meeting with the governor", ) val customName: String?, @Schema( description = """ The summary of the internal location this appointment will take place. Can be different to the parent appointment series if this appointment has been edited. Will be null if in cell = true """, ) val internalLocation: AppointmentLocationSummary?, @Schema( description = """ Flag to indicate if the location of the appointment is in cell rather than an internal prison location. Internal location will be null if in cell = true """, example = "false", ) val inCell: Boolean, @Schema( description = "The date this appointment is taking place on", ) @JsonFormat(pattern = "yyyy-MM-dd") val startDate: LocalDate, @Schema( description = "The starting time of this appointment", example = "13:00", ) @JsonFormat(pattern = "HH:mm") val startTime: LocalTime, @Schema( description = "The end time of this appointment", example = "13:30", ) @JsonFormat(pattern = "HH:mm") val endTime: LocalTime?, @Schema( description = """ Indicates that this appointment has expired i.e. it's start date and time is in the past """, example = "false", ) val isExpired: Boolean, @Schema( description = """ Extra information for the prisoner or prisoners attending this appointment. Shown only on the appointments details page and on printed movement slips. Wing staff will be notified there is extra information via the unlock list. """, example = "This appointment will help adjusting to life outside of prison", ) val extraInformation: String?, @Schema( description = "The date and time this appointment was created. Will not change", ) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val createdTime: LocalDateTime, @Schema( description = """ The username of the user that created this appointment """, ) val createdBy: String, @Schema( description = """ Indicates that this appointment has been independently changed from the original state it was in when it was created as part of an appointment series """, example = "false", ) val isEdited: Boolean, @Schema( description = """ The date and time this appointment was last changed. Will be null if this appointment has not been altered since it was created """, ) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val updatedTime: LocalDateTime?, @Schema( description = """ The username of the user that last edited this appointment. Will be null if this appointment has not been altered since it was created """, ) val updatedBy: String?, @Schema( description = """ Indicates that this appointment has been cancelled """, example = "false", ) val isCancelled: Boolean, @Schema( description = """ Indicates that this appointment has been deleted and removed from scheduled events. """, example = "false", ) val isDeleted: Boolean, @Schema( description = """ The date and time this appointment was cancelled. Will be null if this appointment has not been cancelled """, ) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") val cancelledTime: LocalDateTime?, @Schema( description = """ The username of the user who cancelled this appointment. Will be null if this appointment has not been cancelled """, ) val cancelledBy: String?, )
6
Kotlin
0
1
e3da2736ad7186e0efd907276a0a98bc41383370
6,896
hmpps-activities-management-api
MIT License
plugins/android-extensions/android-extensions-idea/testData/android/completion/fqNameInTag/fqNameInTag.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
package com.myapp import android.app.Activity import kotlinx.android.synthetic.layout.* class MyActivity: Activity() { val button = this.MyBu<caret> } // EXIST: MyButton
0
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
177
kotlin
Apache License 2.0
app/src/main/java/com/just/machine/di/AppModule.kt
Primary-hacker1
307,921,656
false
null
package com.just.machine.di import com.just.machine.helper.Net import com.just.machine.api.BaseApiService import com.just.machine.helper.UriConfig import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun providerBaseApi(): BaseApiService { return providerRetrofit().create(BaseApiService::class.java) } @Provides @Singleton fun providerRetrofit(): Retrofit { return Net.getRetrofit(UriConfig.BASE_URL, 6000L) } }
1
null
19
74
22abe4998fa6af959565e00d0826e683f32ff12f
674
MVVMJetpack
Apache License 2.0
apps/bekreftelse-api/src/main/kotlin/no/nav/paw/bekreftelse/api/Dependencies.kt
navikt
794,874,233
false
{"Kotlin": 721361, "Dockerfile": 143}
package no.nav.paw.bekreftelse.api import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.serialization.jackson.jackson import io.micrometer.prometheusmetrics.PrometheusConfig import io.micrometer.prometheusmetrics.PrometheusMeterRegistry import no.nav.paw.config.kafka.KafkaConfig import no.nav.paw.config.kafka.streams.KafkaStreamsFactory import no.nav.paw.kafkakeygenerator.auth.AzureM2MConfig import no.nav.paw.kafkakeygenerator.auth.azureAdM2MTokenClient import no.nav.paw.kafkakeygenerator.client.KafkaKeyConfig import no.nav.paw.kafkakeygenerator.client.KafkaKeysClient import no.nav.paw.kafkakeygenerator.client.kafkaKeysClient import no.nav.paw.bekreftelse.api.config.ApplicationConfig import no.nav.paw.bekreftelse.api.kafka.BekreftelseProducer import no.nav.paw.bekreftelse.api.kafka.InternState import no.nav.paw.bekreftelse.api.kafka.InternStateSerde import no.nav.paw.bekreftelse.api.kafka.appTopology import no.nav.paw.bekreftelse.api.services.AutorisasjonService import no.nav.poao_tilgang.client.PoaoTilgangCachedClient import no.nav.poao_tilgang.client.PoaoTilgangHttpClient import org.apache.kafka.common.serialization.Serdes import org.apache.kafka.streams.KafkaStreams import org.apache.kafka.streams.StoreQueryParameters import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler import org.apache.kafka.streams.state.QueryableStoreTypes import org.apache.kafka.streams.state.ReadOnlyKeyValueStore import org.apache.kafka.streams.state.Stores import org.slf4j.LoggerFactory fun createDependencies( applicationConfig: ApplicationConfig, kafkaConfig: KafkaConfig, kafkaStreamsConfig: KafkaConfig, azureM2MConfig: AzureM2MConfig, kafkaKeyConfig: KafkaKeyConfig ): Dependencies { val logger = LoggerFactory.getLogger("rapportering-api") val azureM2MTokenClient = azureAdM2MTokenClient(applicationConfig.naisEnv, azureM2MConfig) val kafkaKeysClient = kafkaKeysClient(kafkaKeyConfig) { azureM2MTokenClient.createMachineToMachineToken(kafkaKeyConfig.scope) } val prometheusMeterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT) val httpClient = HttpClient { install(ContentNegotiation) { jackson() } } val streamsConfig = KafkaStreamsFactory(applicationConfig.applicationIdSuffix, kafkaStreamsConfig) .withDefaultKeySerde(Serdes.LongSerde::class) .withDefaultValueSerde(SpecificAvroSerde::class) val streamsBuilder = StreamsBuilder() .addStateStore( Stores.keyValueStoreBuilder( Stores.persistentKeyValueStore(applicationConfig.bekreftelseStateStoreName), Serdes.Long(), InternStateSerde(), ) ) val topology = streamsBuilder.appTopology( prometheusRegistry = prometheusMeterRegistry, bekreftelseHendelseLoggTopic = applicationConfig.bekreftelseHendelseLoggTopic, bekreftelseStateStoreName = applicationConfig.bekreftelseStateStoreName, ) val kafkaStreams = KafkaStreams( topology, streamsConfig.properties.apply { put("application.server", applicationConfig.hostname) } ) kafkaStreams.setUncaughtExceptionHandler { throwable -> logger.error("Uventet feil: ${throwable.message}", throwable) StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_APPLICATION } kafkaStreams.start() val bekreftelseStateStore: ReadOnlyKeyValueStore<Long, InternState> = kafkaStreams.store( StoreQueryParameters.fromNameAndType( applicationConfig.bekreftelseStateStoreName, QueryableStoreTypes.keyValueStore() ) ) val health = Health(kafkaStreams) val bekreftelseProducer = BekreftelseProducer(kafkaConfig, applicationConfig) val poaoTilgangClient = PoaoTilgangCachedClient( PoaoTilgangHttpClient( applicationConfig.poaoClientConfig.url, { azureM2MTokenClient.createMachineToMachineToken(applicationConfig.poaoClientConfig.scope) } ) ) val autorisasjonService = AutorisasjonService(poaoTilgangClient) return Dependencies( kafkaKeysClient, httpClient, kafkaStreams, prometheusMeterRegistry, bekreftelseStateStore, health, bekreftelseProducer, autorisasjonService ) } data class Dependencies( val kafkaKeysClient: KafkaKeysClient, val httpClient: HttpClient, val kafkaStreams: KafkaStreams, val prometheusMeterRegistry: PrometheusMeterRegistry, val bekreftelseStateStore: ReadOnlyKeyValueStore<Long, InternState>, val health: Health, val bekreftelseProducer: BekreftelseProducer, val autorisasjonService: AutorisasjonService )
0
Kotlin
0
1
b1c3dfd591983dd071d94b6dbdc04120ba7c6688
4,961
paw-arbeidssoekerregisteret-monorepo-intern
MIT License
snowplow-tracker/src/main/java/com/snowplowanalytics/core/tracker/Logger.kt
snowplow
20,056,757
false
null
/* * Copyright (c) 2015-2023 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.core.tracker import android.util.Log import androidx.annotation.RestrictTo import com.snowplowanalytics.core.utils.NotificationCenter.postNotification import com.snowplowanalytics.snowplow.event.TrackerError import com.snowplowanalytics.snowplow.tracker.LogLevel import com.snowplowanalytics.snowplow.tracker.LoggerDelegate /** * Custom logger class to easily manage debug mode and appending * of 'SnowplowTracker' to the log TAG as well as logging the * Thread. */ @RestrictTo(RestrictTo.Scope.LIBRARY) object Logger { private val TAG = Logger::class.java.simpleName private var level = 0 var delegate: LoggerDelegate? = DefaultLoggerDelegate() /** * Set the logger delegate that receive logs from the tracker. * * @param delegate The app logger delegate. */ set(delegate) { field = delegate ?: DefaultLoggerDelegate() } /** * Updates the logging level. * * @param newLevel The new log-level to use */ @JvmStatic fun updateLogLevel(newLevel: LogLevel) { level = newLevel.level } // -- Log methods /** * Diagnostic Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun track(tag: String, msg: String, vararg args: Any?) { e(tag, msg, *args) try { var throwable: Throwable? = null for (arg in args) { if (Throwable::class.java.isInstance(arg)) { throwable = arg as? Throwable? break } } val event = TrackerError(tag, getMessage(msg, *args), throwable) val notificationData: MutableMap<String, Any> = HashMap() notificationData["event"] = event postNotification("SnowplowTrackerDiagnostic", notificationData) } catch (e: Exception) { v(TAG, "Error logger can't report the error: $e") } } /** * Error Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun e(tag: String, msg: String, vararg args: Any?) { if (level >= 1) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.error(source, message) } } /** * Debug Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun d(tag: String, msg: String, vararg args: Any?) { if (level >= 2) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.debug(source, message) } } /** * Verbose Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun v(tag: String, msg: String, vararg args: Any?) { if (level >= 3) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.verbose(source, message) } } /** * Returns a formatted logging String * * @param msg The message to log * @param args Any extra args to log * @return the formatted message */ private fun getMessage(msg: String, vararg args: Any?): String { return thread() + "|" + String.format(msg, *args) } /** * Returns the updated tag. * * @param tag the tag to be appended to * @return the appended tag */ private fun getTag(tag: String): String { return "SnowplowTracker->$tag" } /** * Returns the name of the current * thread. * * @return the thread's name */ private fun thread(): String { return Thread.currentThread().name } } /** * Default internal logger delegate */ @RestrictTo(RestrictTo.Scope.LIBRARY) internal class DefaultLoggerDelegate : LoggerDelegate { override fun error(tag: String, msg: String) { Log.e(tag, msg) } override fun debug(tag: String, msg: String) { Log.d(tag, msg) } override fun verbose(tag: String, msg: String) { Log.v(tag, msg) } }
16
null
62
102
0605fd08181d2017e544e5c1daa862b910ef439c
5,154
snowplow-android-tracker
Apache License 2.0
snowplow-tracker/src/main/java/com/snowplowanalytics/core/tracker/Logger.kt
snowplow
20,056,757
false
null
/* * Copyright (c) 2015-2023 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.core.tracker import android.util.Log import androidx.annotation.RestrictTo import com.snowplowanalytics.core.utils.NotificationCenter.postNotification import com.snowplowanalytics.snowplow.event.TrackerError import com.snowplowanalytics.snowplow.tracker.LogLevel import com.snowplowanalytics.snowplow.tracker.LoggerDelegate /** * Custom logger class to easily manage debug mode and appending * of 'SnowplowTracker' to the log TAG as well as logging the * Thread. */ @RestrictTo(RestrictTo.Scope.LIBRARY) object Logger { private val TAG = Logger::class.java.simpleName private var level = 0 var delegate: LoggerDelegate? = DefaultLoggerDelegate() /** * Set the logger delegate that receive logs from the tracker. * * @param delegate The app logger delegate. */ set(delegate) { field = delegate ?: DefaultLoggerDelegate() } /** * Updates the logging level. * * @param newLevel The new log-level to use */ @JvmStatic fun updateLogLevel(newLevel: LogLevel) { level = newLevel.level } // -- Log methods /** * Diagnostic Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun track(tag: String, msg: String, vararg args: Any?) { e(tag, msg, *args) try { var throwable: Throwable? = null for (arg in args) { if (Throwable::class.java.isInstance(arg)) { throwable = arg as? Throwable? break } } val event = TrackerError(tag, getMessage(msg, *args), throwable) val notificationData: MutableMap<String, Any> = HashMap() notificationData["event"] = event postNotification("SnowplowTrackerDiagnostic", notificationData) } catch (e: Exception) { v(TAG, "Error logger can't report the error: $e") } } /** * Error Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun e(tag: String, msg: String, vararg args: Any?) { if (level >= 1) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.error(source, message) } } /** * Debug Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun d(tag: String, msg: String, vararg args: Any?) { if (level >= 2) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.debug(source, message) } } /** * Verbose Level Logging * * @param tag the log tag * @param msg the log message * @param args extra arguments to be formatted */ @JvmStatic fun v(tag: String, msg: String, vararg args: Any?) { if (level >= 3) { val source = getTag(tag) val message = getMessage(msg, *args) delegate?.verbose(source, message) } } /** * Returns a formatted logging String * * @param msg The message to log * @param args Any extra args to log * @return the formatted message */ private fun getMessage(msg: String, vararg args: Any?): String { return thread() + "|" + String.format(msg, *args) } /** * Returns the updated tag. * * @param tag the tag to be appended to * @return the appended tag */ private fun getTag(tag: String): String { return "SnowplowTracker->$tag" } /** * Returns the name of the current * thread. * * @return the thread's name */ private fun thread(): String { return Thread.currentThread().name } } /** * Default internal logger delegate */ @RestrictTo(RestrictTo.Scope.LIBRARY) internal class DefaultLoggerDelegate : LoggerDelegate { override fun error(tag: String, msg: String) { Log.e(tag, msg) } override fun debug(tag: String, msg: String) { Log.d(tag, msg) } override fun verbose(tag: String, msg: String) { Log.v(tag, msg) } }
16
null
62
102
0605fd08181d2017e544e5c1daa862b910ef439c
5,154
snowplow-android-tracker
Apache License 2.0
auth-foundation/src/test/java/com/okta/authfoundation/client/NetworkUtilsTest.kt
okta
445,628,677
false
null
/* * Copyright 2022-Present Okta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.okta.authfoundation.client import com.google.common.truth.Truth.assertThat import com.okta.authfoundation.client.events.RateLimitExceededEvent import com.okta.authfoundation.client.internal.performRequest import com.okta.authfoundation.client.internal.performRequestNonJson import com.okta.authfoundation.credential.Credential import com.okta.authfoundation.events.EventHandler import com.okta.testhelpers.OktaRule import com.okta.testhelpers.RequestMatchers.doesNotContainHeader import com.okta.testhelpers.RequestMatchers.doesNotContainHeaderWithValue import com.okta.testhelpers.RequestMatchers.header import com.okta.testhelpers.RequestMatchers.path import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.slot import io.mockk.unmockkAll import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runTest import kotlinx.serialization.SerializationException import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.SocketPolicy import org.junit.After import org.junit.Rule import org.junit.Test import org.mockito.kotlin.mock import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.math.pow import kotlin.test.assertFailsWith import kotlin.time.Duration.Companion.seconds @OptIn(ExperimentalCoroutinesApi::class) class NetworkingTest { @get:Rule val oktaRule = OktaRule() @After fun tearDown() { unmockkAll() } @Test fun testPerformRequest(): Unit = runTest { oktaRule.enqueue( path("/test"), header("accept", "application/json") ) { response -> response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestErrorStatusCodesCallMapper(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo":"bar"}""") response.setResponseCode(401) } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request, { true }) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestExceptionInMapper(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest<JsonObject, String>(JsonObject.serializer(), request, { true }) { throw IllegalArgumentException("Test Exception From Mapper") } val message = (result as OidcClientResult.Error<String>).exception.message assertThat(message).isEqualTo("Test Exception From Mapper") } @Test fun testPerformRequestNetworkFailure(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.socketPolicy = SocketPolicy.DISCONNECT_AT_START } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request, { true }) { it["foo"]!!.jsonPrimitive.content } val message = (result as OidcClientResult.Error<String>).exception.message assertThat(message).contains("EOF") } @Test fun testPerformRequestErrorStatusReturnsError(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo":"bar"}""") response.setResponseCode(401) } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(401) assertThat(httpResponseException.error).isNull() assertThat(httpResponseException.errorDescription).isNull() } @Test fun testPerformRequestErrorStatusReturnsErrorDeserialized(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"error":"bar","error_description":"baz"}""") response.setResponseCode(401) } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(401) assertThat(httpResponseException.error).isEqualTo("bar") assertThat(httpResponseException.errorDescription).isEqualTo("baz") } @Test fun testPerformRequestNonJson(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequestNonJson(request) val result2 = (result as OidcClientResult.Success<Unit>).result assertThat(result2).isEqualTo(Unit) } @Test fun testPerformRequestFailsWhileReadingResponse(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo}""") // Intentionally invalid json. } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(SerializationException::class.java) } @Test fun testPerformRequestFailsWhileReadingErrorResponse(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo}""") // Intentionally invalid json. response.setResponseCode(401) response.socketPolicy = SocketPolicy.DISCONNECT_AT_END } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) assertThat(exception).hasMessageThat().isEqualTo("HTTP Error: status code - 401") } @Test fun testPerformRequestHasNoTagWithNoCredential(): Unit = runTest { val interceptor = RecordingInterceptor() val builder = oktaRule.okHttpClient.newBuilder() builder.addInterceptor(interceptor) val configuration = oktaRule.createConfiguration(builder.build()) val oidcClient = OidcClient.create(configuration, oktaRule.createEndpoints()) oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oidcClient.performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") assertThat(interceptor.request?.tag(Credential::class.java)).isNull() } @Test fun testPerformRequestHasTagWhenCredentialIsAttachedToOidcClient(): Unit = runTest { val interceptor = RecordingInterceptor() val builder = oktaRule.okHttpClient.newBuilder() builder.addInterceptor(interceptor) val configuration = oktaRule.createConfiguration(builder.build()) val credential = mock<Credential>() val oidcClient = OidcClient.create(configuration, oktaRule.createEndpoints()) .withCredential(credential) oktaRule.enqueue( path("/test"), ) { response -> response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oidcClient.performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") assertThat(interceptor.request?.tag(Credential::class.java)).isNotNull() assertThat(interceptor.request?.tag(Credential::class.java)).isEqualTo(credential) } @Test fun testPerformRequestEnsuresTheCoroutineIsActiveBeforeMakingNetworkRequest(): Unit = runTest { val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val startedCountDownLatch = CountDownLatch(1) val cancelledCountDownLatch = CountDownLatch(1) val job = async(Dispatchers.IO) { startedCountDownLatch.countDown() assertThat(cancelledCountDownLatch.await(1, TimeUnit.SECONDS)).isTrue() oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { throw IllegalStateException("We got a response.") } } assertThat(startedCountDownLatch.await(1, TimeUnit.SECONDS)).isTrue() job.cancel() cancelledCountDownLatch.countDown() assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(0) } @Test fun testPerformRequestRawResponseEnsuresTheCoroutineIsActiveBeforeMakingNetworkRequest(): Unit = runTest { val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val startedCountDownLatch = CountDownLatch(1) val cancelledCountDownLatch = CountDownLatch(1) val job = async(Dispatchers.IO) { startedCountDownLatch.countDown() assertThat(cancelledCountDownLatch.await(1, TimeUnit.SECONDS)).isTrue() oktaRule.createOidcClient().performRequest(request) throw IllegalStateException("We got a response.") } assertThat(startedCountDownLatch.await(1, TimeUnit.SECONDS)).isTrue() job.cancel() cancelledCountDownLatch.countDown() assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(0) } @Test fun testPerformRequestRawResponse(): Unit = runTest { oktaRule.enqueue( path("/test"), ) { response -> response.setBody("") response.setResponseCode(302) response.addHeader("location", "example:/callback") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val response = oktaRule.createOidcClient().performRequest(request) val successResponse = response as OidcClientResult.Success<Response> assertThat(successResponse.result.code).isEqualTo(302) assertThat(successResponse.result.header("location")).isEqualTo("example:/callback") } @Test fun testPerformRequestRawResponseNetworkFailure(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.socketPolicy = SocketPolicy.DISCONNECT_AFTER_REQUEST } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(request) val message = (result as OidcClientResult.Error<Response>).exception.message assertThat(message).contains("Failed to connect to") } @Test fun testPerformRequestWithAlternateAcceptHeader(): Unit = runTest { oktaRule.enqueue( path("/test"), header("accept", "application/ion+json; okta-version=1.0.0"), doesNotContainHeaderWithValue("accept", "application/json"), ) { response -> response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .addHeader("accept", "application/ion+json; okta-version=1.0.0") .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestWithNon429ErrorHasNoRetry(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(401) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried request after getting non-429 response.") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(401) assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun `do not retry request when verbatim response is expected`() = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request, shouldAttemptJsonDeserialization = { true }) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestWithNon429ErrorAndRateLimitHeadersDoesNotRetry() = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(401) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried request after getting non-429 response.") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(401) assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun testPerformRequestDoesNotRetryOnNetworkFailure(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.socketPolicy = SocketPolicy.DISCONNECT_AT_START } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried request after network failure.") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request, { true }) { it["foo"]!!.jsonPrimitive.content } val message = (result as OidcClientResult.Error<String>).exception.message assertThat(message).contains("EOF") assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun testPerformRequestRetryOn429ErrorAndStopOnSuccess(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestRetryOn429FollowedByDifferentError(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(404) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(404) } @Test fun testPerformRequestRetryContainsRetryForHeader(): Unit = runTest { val requestId = "requestId1234" oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response, requestId = requestId) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue( path("/test"), header("x-okta-retry-for", requestId) ) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestRetryDoesNotContainRetryForHeaderIfRequestIdMissing(): Unit = runTest { oktaRule.enqueue( path("/test"), doesNotContainHeader("x-okta-retry-for") ) { response -> response.setResponseCode(429) setRateLimitHeaders(response, requestId = null) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue( path("/test"), doesNotContainHeader("x-okta-retry-for") ) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestRetryContainsRetryCountHeader(): Unit = runTest { val retries = 3 oktaRule.enqueue( path("/test"), doesNotContainHeader("x-okta-retry-count") ) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } for (i in 1 until retries) { oktaRule.enqueue( path("/test"), header("x-okta-retry-count", i.toString()) ) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } } oktaRule.enqueue( path("/test"), header("x-okta-retry-count", retries.toString()) ) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") } @Test fun testPerformRequestRetryAfterMinimumDelay(): Unit = runTest { val minDelaySeconds = 20L val rateLimitEventHandler = getRateLimitExceededEventHandler(minDelaySeconds = minDelaySeconds) oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders( response, rateLimitResetEpochTime = TIME_EPOCH_SECS - 500 ) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val startTime = currentTime val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val elapsedTime = currentTime - startTime assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") assertThat(elapsedTime).isEqualTo(minDelaySeconds.seconds.inWholeMilliseconds) } @Test fun testPerformRequestRetryAtResetTime(): Unit = runTest { val rateLimitResetAfterSeconds = 500L oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders( response, rateLimitResetEpochTime = TIME_EPOCH_SECS + rateLimitResetAfterSeconds, ) response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { response -> setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val startTime = currentTime val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val elapsedTime = currentTime - startTime assertThat((result as OidcClientResult.Success<String>).result).isEqualTo("bar") assertThat(elapsedTime).isEqualTo(rateLimitResetAfterSeconds.seconds.inWholeMilliseconds) } @Test fun testPerformRequestRetryUpToMaxRetriesOn429ErrorResponse(): Unit = runTest { val maxRetries = 5 val rateLimitEventHandler = getRateLimitExceededEventHandler(maxRetries = maxRetries) oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) for (i in 0 until maxRetries + 1) { // One try + maxRetries retries oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setBody("""{"foo":"bar"}""") } } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(429) } @Test fun testPerformRequestRetryCancelsOnCoroutineCancellation(): Unit = runTest { val fetchedFirstRequestCountDownLatch = CountDownLatch(1) oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders( response, rateLimitResetEpochTime = TIME_EPOCH_SECS - 500 ) response.setBody("""{"foo":"bar"}""") fetchedFirstRequestCountDownLatch.countDown() } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried the request after coroutine cancellation") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val job = launch(Dispatchers.IO) { oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { throw IllegalStateException("We got a response.") } } assertThat(fetchedFirstRequestCountDownLatch.await(1, TimeUnit.SECONDS)).isTrue() job.cancelAndJoin() assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun testPerformRequestRetryWithInvalidDateHeaderShouldReturn429Response(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response, responseHumanReadableDate = "abcde") response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried request after getting invalid 429 date header.") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(429) assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun testPerformRequestRetryWithInvalidRateLimitResetHeaderShouldReturn429Response(): Unit = runTest { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response) response.setHeader("x-rate-limit-reset", "abcde") response.setBody("""{"foo":"bar"}""") } oktaRule.enqueue(path("/test")) { _ -> throw IllegalStateException("Retried request after getting invalid 429 x-rate-limit-reset header.") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val result = oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val exception = (result as OidcClientResult.Error<String>).exception assertThat(exception).isInstanceOf(OidcClientResult.Error.HttpResponseException::class.java) val httpResponseException = exception as OidcClientResult.Error.HttpResponseException assertThat(httpResponseException.responseCode).isEqualTo(429) assertThat(oktaRule.mockWebServerDispatcher.numberRemainingInQueue()).isEqualTo(1) oktaRule.mockWebServerDispatcher.clear() } @Test fun testPerformRequestRetrySendsAnEventForEach429Response(): Unit = runTest { val maxRetries = 10 val events = mutableListOf<RateLimitExceededEvent>() val rateLimitEventHandler = object : EventHandler { override fun onEvent(event: Any) { val errorEvent = event as RateLimitExceededEvent errorEvent.maxRetries = maxRetries events.add(event) } } oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) for (i in 0 until maxRetries + 1) { // One try + maxRetries retries oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response) } } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat(events.size).isEqualTo(11) events.mapIndexed { index, event -> assertThat(event.retryCount).isEqualTo(index) } } @Test fun testPerformRequestRetryChangesDelayBasedOnHandledEvent(): Unit = runTest { val exponentBase = 2.0 val events = mutableListOf<RateLimitExceededEvent>() val rateLimitEventHandler = object : EventHandler { override fun onEvent(event: Any) { val errorEvent = event as RateLimitExceededEvent events.add(event) errorEvent.minDelaySeconds = exponentBase.pow(errorEvent.retryCount).toLong() } } oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) for (i in 0 until 4) { oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders( response, rateLimitResetEpochTime = TIME_EPOCH_SECS - 500, ) } } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val startTime = currentTime oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } val elapsedTime = currentTime - startTime assertThat(events.size).isEqualTo(4) assertThat(elapsedTime).isEqualTo((1 + 2 + 4).seconds.inWholeMilliseconds) } @Test fun testPerformRequestRetryChangesMaxRetriesBasedOnHandledEvent(): Unit = runTest { val events = mutableListOf<RateLimitExceededEvent>() val rateLimitEventHandler = object : EventHandler { override fun onEvent(event: Any) { val errorEvent = event as RateLimitExceededEvent events.add(event) // maxRetries should be changing on each iteration. By setting the event's maxRetries // to 10 on the 10th retry, there should be no further retries errorEvent.maxRetries = if (errorEvent.retryCount == 10) 10 else 1000 } } oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) for (i in 0 until 11) { // One try + 10 retries oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders( response, rateLimitResetEpochTime = TIME_EPOCH_SECS - 500, ) } } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() oktaRule.createOidcClient().performRequest(JsonObject.serializer(), request) { it["foo"]!!.jsonPrimitive.content } assertThat(events.size).isEqualTo(11) assertThat(events.last().retryCount).isEqualTo(10) } @Test fun testPerformRequestRetryClosesUnusedResponsesAfterEmittingEvent(): Unit = runTest { val events = mutableListOf<RateLimitExceededEvent>() val rateLimitEventHandler = object : EventHandler { override fun onEvent(event: Any) { val errorEvent = event as RateLimitExceededEvent errorEvent.minDelaySeconds = 0L events.add(errorEvent) assertThat(event.response.peekBody(Long.MAX_VALUE).string()).isEqualTo("") } } oktaRule.eventHandler.registerEventHandler(rateLimitEventHandler) for (i in 0 until 4) { // One try + 3 retries oktaRule.enqueue(path("/test")) { response -> response.setResponseCode(429) setRateLimitHeaders(response, rateLimitResetEpochTime = TIME_EPOCH_SECS - 500) } } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val response = oktaRule.createOidcClient().performRequest(request) assertThat(events.size).isEqualTo(4) val lastRetryEvent = events.removeLast() events.forEach { event -> val exception = assertFailsWith<IllegalStateException> { event.response.peekBody(Long.MAX_VALUE).string() } assertThat(exception.message).isEqualTo("closed") } // We already have retried up to maxRetries, and response is the same as last unsuccessful retry. // So, don't close it assertThat(response.getOrThrow().peekBody(Long.MAX_VALUE).string()).isEqualTo("") assertThat(lastRetryEvent.response.peekBody(Long.MAX_VALUE).string()).isEqualTo("") } @Test fun `prioritize custom okhttp interceptors when making requests`() = runTest { var lastCalledInterceptor: String? = null val customInterceptor = Interceptor { lastCalledInterceptor = "customInterceptor" it.proceed(it.request()) } val okHttpClient = oktaRule.okHttpClient.newBuilder() .addInterceptor(customInterceptor) .build() mockkObject(OidcUserAgentInterceptor) val oidcRequestSlot = slot<Interceptor.Chain>() every { OidcUserAgentInterceptor.intercept(capture(oidcRequestSlot)) } answers { lastCalledInterceptor = "oidcInterceptor" with(oidcRequestSlot.captured) { proceed(request()) } } val oidcConfiguration = oktaRule.createConfiguration(okHttpClient) oktaRule.enqueue( path("/test"), ) { response -> response.setBody("response") } val request = Request.Builder() .url(oktaRule.baseUrl.newBuilder().addPathSegments("test").build()) .build() val credential = mockk<Credential>() val oidcClient = OidcClient.create(oidcConfiguration, oktaRule.createEndpoints()) .withCredential(credential) oidcClient.performRequest(String.serializer(), request) { /** Ignore response */ } assertThat(lastCalledInterceptor).isEqualTo("customInterceptor") } private fun setRateLimitHeaders( response: MockResponse, rateLimitRemaining: Int = 0, rateLimitLimit: Int = 300, rateLimitResetEpochTime: Long = TIME_EPOCH_SECS + 50, responseHumanReadableDate: String = TIME_HTTP_DATE, requestId: String? = REQUEST_ID, ) { response.setHeader("x-rate-limit-remaining", rateLimitRemaining) response.setHeader("x-rate-limit-limit", rateLimitLimit) response.setHeader("x-rate-limit-reset", rateLimitResetEpochTime) response.setHeader("date", responseHumanReadableDate) requestId?.let { response.setHeader("x-okta-request-id", requestId) } } private fun getRateLimitExceededEventHandler( maxRetries: Int = 3, minDelaySeconds: Long = 5L, ): EventHandler { return object : EventHandler { override fun onEvent(event: Any) { val errorEvent = event as RateLimitExceededEvent errorEvent.maxRetries = maxRetries errorEvent.minDelaySeconds = minDelaySeconds } } } companion object { private const val TIME_HTTP_DATE = "Fri, 09 Sep 2022 00:00:00 GMT" private const val TIME_EPOCH_SECS = 1662681600L // TIME_HTTP_DATE in epoch time private const val REQUEST_ID = "requestId" } } private class RecordingInterceptor : Interceptor { var request: Request? = null override fun intercept(chain: Interceptor.Chain): Response { request = chain.request() return chain.proceed(chain.request()) } }
8
null
11
33
72776583e6e4066d576f36b4d73ed83216e61584
41,484
okta-mobile-kotlin
Apache License 2.0
src/main/kotlin/net/stckoverflw/pluginjam/command/PositionTpCommand.kt
KtFTW
471,456,546
false
{"Kotlin": 111636}
package net.stckoverflw.pluginjam.command import com.mojang.brigadier.arguments.StringArgumentType import net.axay.kspigot.commands.argument import net.axay.kspigot.commands.command import net.axay.kspigot.commands.requiresPermission import net.axay.kspigot.commands.runs import net.stckoverflw.pluginjam.config.impl.PostionsConfig class PositionTpCommand(val postionsConfig: PostionsConfig) { init { command("positiontp") { requiresPermission("pluginjam.positiontp") argument("name", StringArgumentType.string()) { runs { val name = getArgument<String>("name") val location = postionsConfig.getLocation(name) player.teleportAsync(location) } } } } }
0
Kotlin
0
3
9f1d3b0e55bb3049cf715339cf2211da1d9bbc6f
805
PluginJam-1
MIT License
src/test/kotlin/no/nav/familie/baks/mottak/hendelser/JournalføringHendelseServiceTest.kt
navikt
221,166,975
false
null
package no.nav.familie.ba.mottak.hendelser import io.mockk.* import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import no.nav.familie.ba.mottak.config.FeatureToggleService import no.nav.familie.ba.mottak.domene.HendelseConsumer import no.nav.familie.ba.mottak.domene.Hendelseslogg import no.nav.familie.ba.mottak.domene.HendelsesloggRepository import no.nav.familie.ba.mottak.integrasjoner.* import no.nav.familie.ba.mottak.integrasjoner.FagsakDeltagerRolle.FORELDER import no.nav.familie.ba.mottak.integrasjoner.FagsakStatus.LØPENDE import no.nav.familie.ba.mottak.task.JournalhendelseRutingTask import no.nav.familie.ba.mottak.task.OpprettJournalføringOppgaveTask import no.nav.familie.ba.mottak.task.SendTilSakTask import no.nav.familie.kontrakter.ba.infotrygd.InfotrygdSøkResponse import no.nav.familie.kontrakter.felles.oppgave.Oppgave import no.nav.familie.kontrakter.felles.oppgave.OppgaveResponse import no.nav.familie.kontrakter.felles.oppgave.Oppgavetype import no.nav.familie.prosessering.domene.Task import no.nav.familie.prosessering.domene.TaskRepository import no.nav.joarkjournalfoeringhendelser.JournalfoeringHendelseRecord import org.apache.kafka.clients.consumer.ConsumerRecord import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.slf4j.MDC import org.springframework.kafka.support.Acknowledgment @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JournalføringHendelseServiceTest { @MockK lateinit var mockJournalpostClient: JournalpostClient @MockK(relaxed = true) lateinit var mockOppgaveClient: OppgaveClient @MockK lateinit var sakClient: SakClient @MockK lateinit var infotrygdBarnetrygdClient: InfotrygdBarnetrygdClient @MockK lateinit var aktørClient: AktørClient @MockK(relaxed = true) lateinit var mockTaskRepository: TaskRepository @MockK(relaxed = true) lateinit var mockFeatureToggleService: FeatureToggleService @MockK(relaxed = true) lateinit var mockHendelsesloggRepository: HendelsesloggRepository @MockK(relaxed = true) lateinit var ack: Acknowledgment @InjectMockKs lateinit var service: JournalhendelseService @BeforeEach internal fun setUp() { MockKAnnotations.init(this) clearAllMocks() //Inngående papirsøknad, Mottatt every { mockJournalpostClient.hentJournalpost(JOURNALPOST_PAPIRSØKNAD) } returns Journalpost(journalpostId = JOURNALPOST_PAPIRSØKNAD, journalposttype = Journalposttype.I, journalstatus = Journalstatus.MOTTATT, bruker = Bruker("123456789012", BrukerIdType.AKTOERID), tema = "BAR", kanal = "SKAN_NETS", behandlingstema = null, dokumenter = null, journalforendeEnhet = null, sak = null) //Inngående digital, Mottatt every { mockJournalpostClient.hentJournalpost(JOURNALPOST_DIGITALSØKNAD) } returns Journalpost(journalpostId = JOURNALPOST_DIGITALSØKNAD, journalposttype = Journalposttype.I, journalstatus = Journalstatus.MOTTATT, bruker = Bruker("123456789012", BrukerIdType.AKTOERID), tema = "BAR", kanal = "NAV_NO", behandlingstema = null, dokumenter = null, journalforendeEnhet = null, sak = null) //Utgående digital, Mottatt every { mockJournalpostClient.hentJournalpost(JOURNALPOST_UTGÅENDE_DOKUMENT) } returns Journalpost(journalpostId = JOURNALPOST_UTGÅENDE_DOKUMENT, journalposttype = Journalposttype.U, journalstatus = Journalstatus.MOTTATT, bruker = Bruker("123456789012", BrukerIdType.AKTOERID), tema = "BAR", kanal = "SKAN_NETS", behandlingstema = null, dokumenter = null, journalforendeEnhet = null, sak = null) //Ikke barnetrygd every { mockJournalpostClient.hentJournalpost(JOURNALPOST_IKKE_BARNETRYGD) } returns Journalpost(journalpostId = JOURNALPOST_IKKE_BARNETRYGD, journalposttype = Journalposttype.U, journalstatus = Journalstatus.MOTTATT, bruker = Bruker("123456789012", BrukerIdType.AKTOERID), tema = "FOR", kanal = "NAV_NO", behandlingstema = null, dokumenter = null, journalforendeEnhet = null, sak = null) //ferdigstilt journalpost every { mockJournalpostClient.hentJournalpost(JOURNALPOST_FERDIGSTILT) } returns Journalpost(journalpostId = JOURNALPOST_FERDIGSTILT, journalposttype = Journalposttype.U, journalstatus = Journalstatus.FERDIGSTILT, bruker = Bruker("123456789012", BrukerIdType.AKTOERID), tema = "FOR", kanal = "NAV_NO", behandlingstema = null, dokumenter = null, journalforendeEnhet = null, sak = null) every { mockFeatureToggleService.isEnabled(any()) } returns true every { mockFeatureToggleService.isEnabled(any(), true) } returns true } @Test fun `Mottak av papirsøknader skal opprette JournalhendelseRutingTask`() { MDC.put("callId", "papir") val record = opprettRecord(JOURNALPOST_PAPIRSØKNAD) service.behandleJournalhendelse(record) val taskSlot = slot<Task>() verify { mockTaskRepository.save(capture(taskSlot)) } assertThat(taskSlot.captured).isNotNull assertThat(taskSlot.captured.payload).isEqualTo("SKAN_NETS") assertThat(taskSlot.captured.metadata.getProperty("callId")).isEqualTo("papir") assertThat(taskSlot.captured.taskStepType).isEqualTo(JournalhendelseRutingTask.TASK_STEP_TYPE) } @Test fun `Mottak av digital søknader skal opprette task`() { MDC.put("callId", "digital") val record = opprettRecord(JOURNALPOST_DIGITALSØKNAD) service.behandleJournalhendelse(record) val taskSlot = slot<Task>() verify { mockTaskRepository.save(capture(taskSlot)) } assertThat(taskSlot.captured).isNotNull assertThat(taskSlot.captured.payload).isEqualTo("NAV_NO") assertThat(taskSlot.captured.metadata.getProperty("callId")).isEqualTo("digital") assertThat(taskSlot.captured.taskStepType).isEqualTo(JournalhendelseRutingTask.TASK_STEP_TYPE) } @Test fun `Hendelser hvor journalpost er alt FERDIGSTILT skal ignoreres`() { val record = opprettRecord(JOURNALPOST_FERDIGSTILT) service.behandleJournalhendelse(record) verify(exactly = 0) { mockTaskRepository.save(any()) } } @Test fun `Utgående journalposter skal ignoreres`() { val record = opprettRecord(JOURNALPOST_UTGÅENDE_DOKUMENT) service.behandleJournalhendelse(record) verify(exactly = 0) { mockTaskRepository.save(any()) } } @Test fun `Oppretter oppgave dersom det ikke eksisterer en allerede`() { every { mockOppgaveClient.finnOppgaver(any(), any()) } returns listOf() val sakssystemMarkering = slot<String>() every { mockOppgaveClient.opprettJournalføringsoppgave(any(), capture(sakssystemMarkering)) } returns OppgaveResponse(1) every { mockTaskRepository.saveAndFlush(any<Task>()) } returns null every { aktørClient.hentPersonident(any()) } returns "12345678910" every { sakClient.hentRestFagsakDeltagerListe(any(), emptyList()) } returns listOf(RestFagsakDeltager("12345678910", FORELDER, 1L, LØPENDE)) every { infotrygdBarnetrygdClient.hentLøpendeUtbetalinger(any(), any()) } returns InfotrygdSøkResponse(emptyList(), emptyList()) every { infotrygdBarnetrygdClient.hentSaker(any(), any()) } returns InfotrygdSøkResponse(emptyList(), emptyList()) val task = OpprettJournalføringOppgaveTask( mockJournalpostClient, mockOppgaveClient, mockTaskRepository) task.doTask(Task.nyTask(SendTilSakTask.TASK_STEP_TYPE, "oppgavebeskrivelse").apply { this.metadata["journalpostId"] = JOURNALPOST_UTGÅENDE_DOKUMENT }) verify(exactly = 1) { mockTaskRepository.saveAndFlush(any()) } assertThat(sakssystemMarkering.captured).contains("oppgavebeskrivelse") } @Test fun `Oppretter ikke oppgave dersom det eksisterer en allerede`() { every { mockOppgaveClient.finnOppgaver(any(), Oppgavetype.Journalføring) } returns listOf() every { mockOppgaveClient.finnOppgaver(JOURNALPOST_UTGÅENDE_DOKUMENT, Oppgavetype.Journalføring) } returns listOf(Oppgave(123)) every { mockOppgaveClient.finnOppgaver(JOURNALPOST_PAPIRSØKNAD, Oppgavetype.Fordeling) } returns listOf(Oppgave(123)) val task = OpprettJournalføringOppgaveTask( mockJournalpostClient, mockOppgaveClient, mockTaskRepository) task.doTask(Task.nyTask(SendTilSakTask.TASK_STEP_TYPE, JOURNALPOST_UTGÅENDE_DOKUMENT).apply { this.metadata["journalpostId"] = JOURNALPOST_UTGÅENDE_DOKUMENT }) task.doTask(Task.nyTask(SendTilSakTask.TASK_STEP_TYPE, JOURNALPOST_PAPIRSØKNAD).apply { this.metadata["journalpostId"] = JOURNALPOST_PAPIRSØKNAD }) verify(exactly = 0) { mockTaskRepository.saveAndFlush(any<Task>()) } } @Test fun `Kaster exception dersom journalstatus annet enn MOTTATT`() { val task = OpprettJournalføringOppgaveTask( mockJournalpostClient, mockOppgaveClient, mockTaskRepository) Assertions.assertThrows(IllegalStateException::class.java) { task.doTask(Task.nyTask(SendTilSakTask.TASK_STEP_TYPE, JOURNALPOST_FERDIGSTILT).apply { this.metadata["journalpostId"] = JOURNALPOST_FERDIGSTILT }) } } @Test fun `Skal ignorere hendelse fordi den eksisterer i hendelseslogg`() { val consumerRecord = ConsumerRecord("topic", 1, OFFSET, 42L, opprettRecord(JOURNALPOST_PAPIRSØKNAD)) every { mockHendelsesloggRepository.existsByHendelseIdAndConsumer("hendelseId", HendelseConsumer.JOURNAL_AIVEN) } returns true service.prosesserNyHendelse(consumerRecord, ack) verify { ack.acknowledge() } verify(exactly = 0) { mockHendelsesloggRepository.save(any()) } } @Test fun `Mottak av gyldig hendelse skal delegeres til service`() { val consumerRecord = ConsumerRecord("topic", 1, OFFSET, 42L, opprettRecord(JOURNALPOST_PAPIRSØKNAD)) service.prosesserNyHendelse(consumerRecord, ack) verify { ack.acknowledge() } val slot = slot<Hendelseslogg>() verify(exactly = 1) { mockHendelsesloggRepository.save(capture(slot)) } assertThat(slot.captured).isNotNull assertThat(slot.captured.offset).isEqualTo(OFFSET) assertThat(slot.captured.hendelseId).isEqualTo(HENDELSE_ID) assertThat(slot.captured.consumer).isEqualTo(HendelseConsumer.JOURNAL_AIVEN) assertThat(slot.captured.metadata["journalpostId"]).isEqualTo(JOURNALPOST_PAPIRSØKNAD) assertThat(slot.captured.metadata["hendelsesType"]).isEqualTo("JournalpostMottatt") } @Test fun `Ikke gyldige hendelsetyper skal ignoreres`() { val ugyldigHendelsetypeRecord = opprettRecord(journalpostId = JOURNALPOST_PAPIRSØKNAD, hendelseType = "UgyldigType", temaNytt = "BAR") val consumerRecord = ConsumerRecord("topic", 1, OFFSET, 42L, ugyldigHendelsetypeRecord) service.prosesserNyHendelse(consumerRecord, ack) verify { ack.acknowledge() } verify(exactly = 0) { mockHendelsesloggRepository.save(any()) } } @Test fun `Hendelser hvor journalpost ikke har tema for Barnetrygd skal ignoreres`() { val ukjentTemaRecord = opprettRecord(journalpostId = JOURNALPOST_PAPIRSØKNAD, temaNytt = "UKJ") val consumerRecord = ConsumerRecord("topic", 1, OFFSET, 42L, ukjentTemaRecord) service.prosesserNyHendelse(consumerRecord, ack) verify { ack.acknowledge() } verify(exactly = 0) { mockHendelsesloggRepository.save(any()) } } private fun opprettRecord(journalpostId: String, hendelseType: String = "JournalpostMottatt", temaNytt: String = "BAR"): JournalfoeringHendelseRecord { return JournalfoeringHendelseRecord(HENDELSE_ID, 1, hendelseType, journalpostId.toLong(), "M", "BAR", temaNytt, "SKAN_NETS", "kanalReferanseId", "BAR") } companion object { const val JOURNALPOST_PAPIRSØKNAD = "111" const val JOURNALPOST_DIGITALSØKNAD = "222" const val JOURNALPOST_UTGÅENDE_DOKUMENT = "333" const val JOURNALPOST_IKKE_BARNETRYGD = "444" const val JOURNALPOST_FERDIGSTILT = "555" const val OFFSET = 21L const val HENDELSE_ID = "hendelseId" } }
5
null
0
2
f9dd1c17b33e70c8a8ee8d8edcbce1e6c1f6fee8
15,213
familie-baks-mottak
MIT License
app/src/main/java/co/com/lafemmeapp/lafemmeapp/presentation/utils/RateAppointmentDialogFragment.kt
Informatica-Empresarial
106,600,201
false
null
package co.com.lafemmeapp.lafemmeapp.presentation.utils import android.app.Activity import android.content.Context import android.os.Bundle import android.support.v4.content.ContextCompat import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import co.com.lafemmeapp.core.domain.entities.Appointment import co.com.lafemmeapp.lafemmeapp.AppModuleConstants import co.com.lafemmeapp.lafemmeapp.R import co.com.lafemmeapp.lafemmeapp.application.LaFemmeApplication import co.com.lafemmeapp.lafemmeapp.events.OnAppointmentRatedEvent import co.com.lafemmeapp.lafemmeapp.presentation.BaseFragment import co.com.lafemmeapp.utilmodule.presentation.view_interfaces.IFragmentCallbacks import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import me.zhanghai.android.materialratingbar.MaterialRatingBar /** * Created by oscargallon on 4/23/17. */ class RateAppointmentDialogFragment : BaseFragment(), IRateAppointmentDialogFragmentView { var mTVRateStatus: TextView? = null var mRBAppoitmentRate: MaterialRatingBar? = null var mRateAppointmentDialogFragmentPresenter: IRateAppointmentDialogFragmentPresenter? = null var mLYOptionsContainer: LinearLayout? = null var mTVOption1: TextView? = null var mTVOption2: TextView? = null var mTVOption3: TextView? = null var mTVOption4: TextView? = null var mBTNSendRate: Button? = null var mIVAvatar: ImageView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mRateAppointmentDialogFragmentPresenter?.onCreate(arguments) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater!!.inflate(R.layout.fragment_full_screen_dialog, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view?.let { mRateAppointmentDialogFragmentPresenter?.onCreateView(view) } } override fun onAttach(activity: Activity?) { super.onAttach(activity) mRateAppointmentDialogFragmentPresenter = RateAppointmentDialogFragmentPresenter(this, activity!!) mRateAppointmentDialogFragmentPresenter?.onAttach(activity as IFragmentCallbacks) } override fun onAttach(context: Context?) { super.onAttach(context) mRateAppointmentDialogFragmentPresenter = RateAppointmentDialogFragmentPresenter(this, context!!) mRateAppointmentDialogFragmentPresenter?.onAttach(context as IFragmentCallbacks) } override fun initViewComponents(view: View) { mTVRateStatus = view.findViewById(R.id.tv_rate_status) as TextView mRBAppoitmentRate = view.findViewById(R.id.rb_appointment_rate) as MaterialRatingBar mLYOptionsContainer = view.findViewById(R.id.ly_option_buttons_container) as LinearLayout mBTNSendRate = view.findViewById(R.id.btn_send_rate) as Button mTVOption1 = view.findViewById(R.id.tv_option_1) as TextView mTVOption2 = view.findViewById(R.id.tv_option_2) as TextView mTVOption3 = view.findViewById(R.id.tv_option_3) as TextView mTVOption4 = view.findViewById(R.id.tv_option_4) as TextView mIVAvatar = view.findViewById(R.id.iv_avatar) as ImageView } override fun showHideOptionsButtons(visibility: Int) { mLYOptionsContainer?.visibility = visibility } override fun initComponents() { mRBAppoitmentRate.let { mRateAppointmentDialogFragmentPresenter?.subscribeToRatingBarChanges(mRBAppoitmentRate!!) } mTVOption1?.setOnClickListener(this) mTVOption2?.setOnClickListener(this) mTVOption3?.setOnClickListener(this) mTVOption4?.setOnClickListener(this) mBTNSendRate?.setOnClickListener { if (mRBAppoitmentRate !== null) { var options: String? = "" if (mTVOption1 !== null && mTVOption1!!.tag !== null && mTVOption1!!.tag as Boolean) { options += mTVOption1!!.text.toString() } if (mTVOption2 !== null && mTVOption2!!.tag !== null && mTVOption2!!.tag as Boolean) { options += if (TextUtils.isEmpty(options)) mTVOption2!!.text.toString() else ", ${mTVOption2!!.text}" } if (mTVOption3 !== null && mTVOption3!!.tag !== null && mTVOption3!!.tag as Boolean) { options += if (TextUtils.isEmpty(options)) mTVOption3!!.text.toString() else ", ${mTVOption3!!.text}" } if (mTVOption4 !== null && mTVOption4!!.tag !== null && mTVOption4!!.tag as Boolean) { options += if (TextUtils.isEmpty(options)) mTVOption4!!.text.toString() else ", ${mTVOption4!!.text}" } mRateAppointmentDialogFragmentPresenter?.sendRate(options, mRBAppoitmentRate!!.rating) } } } override fun onClick(view: View) { if ((view as TextView).currentTextColor == resources.getColor(R.color.colorAccent)) { view.setTextColor(resources.getColor(R.color.colorPrimary)) view.background = resources.getDrawable(R.drawable.button_border_primary_white_background) view.tag = true } else { view.setTextColor(ContextCompat.getColor(activity, R.color.colorAccent)) view.background = resources.getDrawable(R.drawable.tertiary_button_rounded_background) view.tag = false } } override fun changeStatus(status: String) { mTVRateStatus?.text = status } override fun onAppointmentRated(appointment: Appointment) { LaFemmeApplication .getInstance() .getmBus() .post(OnAppointmentRatedEvent(appointment)) activity.onBackPressed() } override fun showMessage(title: String, description: String, action: String, showBothButtons: Boolean) { } override fun populateView() { } override fun showProgressDialog() { super.showProgressDialog() } override fun hideProgressDialog() { super.hideProgressDialog() } override fun showSpecialistAvatar(url: String) { mIVAvatar?.let { Picasso.with(mIVAvatar!!.context) .load(url) .transform(BitmapTransform(200, 200)) .memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE) .resize(200, 200) .into(mIVAvatar!!) } } companion object { fun newInstance(appointment: Appointment): RateAppointmentDialogFragment { val fragment = RateAppointmentDialogFragment() val bundle = Bundle() bundle.putParcelable(AppModuleConstants.VIEW_HISTORY_DETAIL, appointment) fragment.arguments = bundle return fragment } } }
1
null
1
1
486ab3eab99e9a06e70e32d1cbe34a9fa5a7fd81
7,546
AppAndroid
Apache License 2.0
src/main/kotlin/Utility/Functions.kt
JyotimoyKashyap
434,660,784
false
{"Kotlin": 12467, "Assembly": 190}
package Utility import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import org.jetbrains.skija.Image import java.io.ByteArrayOutputStream import java.net.HttpURLConnection import java.net.URL import javax.imageio.ImageIO fun loadNetworkImage(link: String): ImageBitmap { val url = URL(link) val connection = url.openConnection() as HttpURLConnection connection.connect() val inputStream = connection.inputStream val bufferedImage = ImageIO.read(inputStream) val stream = ByteArrayOutputStream() ImageIO.write(bufferedImage, "png", stream) val byteArray = stream.toByteArray() return Image.makeFromEncoded(byteArray).asImageBitmap() }
0
Kotlin
0
4
1d6278aa60fe930eff06b3d53e34c44fac07f837
720
WeatherComposeDesktopApp
Apache License 2.0
src/test/kotlin/com/expedia/graphql/generator/SchemaGeneratorTest.kt
d4rken
247,506,424
false
null
package com.expedia.graphql.schema.generator import com.expedia.graphql.TopLevelObjectDef import com.expedia.graphql.annotations.GraphQLDescription import com.expedia.graphql.annotations.GraphQLIgnore import com.expedia.graphql.schema.exceptions.ConflictingTypesException import com.expedia.graphql.schema.exceptions.InvalidSchemaException import com.expedia.graphql.schema.extensions.deepName import com.expedia.graphql.schema.testSchemaConfig import com.expedia.graphql.toSchema import graphql.GraphQL import graphql.schema.GraphQLObjectType import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertThrows import java.net.CookieManager import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue @Suppress("Detekt.UnusedPrivateMember", "Detekt.FunctionOnlyReturningConstant") class SchemaGeneratorTest { @Test fun `SchemaGenerator generates a simple GraphQL schema`() { val schema = toSchema( listOf(TopLevelObjectDef(QueryObject())), listOf(TopLevelObjectDef(MutationObject())), config = testSchemaConfig ) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute(" { query(value: 1) { id } }") val geo: Map<String, Map<String, Any>>? = result.getData() assertEquals(1, geo?.get("query")?.get("id")) } @Test fun `Schema generator exposes arrays of primitive types as function arguments`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithArray())), config = testSchemaConfig) val firstArgumentType = schema.queryType.getFieldDefinition("sumOf").arguments[0].type.deepName assertEquals("[Int!]!", firstArgumentType) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{ sumOf(ints: [1, 2, 3]) }") val sum = result.getData<Map<String, Int>>().values.first() assertEquals(6, sum) } @Test fun `Schema generator exposes arrays of complex types as function arguments`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithArray())), config = testSchemaConfig) val firstArgumentType = schema.queryType.getFieldDefinition("sumOfComplexArray").arguments[0].type.deepName assertEquals("[ComplexWrappingTypeInput!]!", firstArgumentType) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{sumOfComplexArray(objects: [{value: 1}, {value: 2}, {value: 3}])}") val sum = result.getData<Map<String, Int>>().values.first() assertEquals(6, sum) } @Test fun `SchemaGenerator ignores fields and functions with @Ignore`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithIgnored())), config = testSchemaConfig) assertTrue(schema.queryType.fieldDefinitions.none { it.name == "ignoredFunction" }) val resultType = schema.getObjectType("ResultWithIgnored") assertTrue(resultType.fieldDefinitions.none { it.name == "ignoredFunction" }) assertTrue(resultType.fieldDefinitions.none { it.name == "ignoredProperty" }) } @Test fun `SchemaGenerator generates a GraphQL schema with repeated types to test conflicts`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithRepeatedTypes())), config = testSchemaConfig) val resultType = schema.getObjectType("Result") val topLevelQuery = schema.getObjectType("TopLevelQuery") assertEquals("Result!", topLevelQuery.getFieldDefinition("query").type.deepName) assertEquals("SomeObject", resultType.getFieldDefinition("someObject").type.deepName) assertEquals("[Int!]!", resultType.getFieldDefinition("someIntValues").type.deepName) assertEquals("[Boolean!]!", resultType.getFieldDefinition("someBooleanValues").type.deepName) assertEquals("[SomeObject!]!", resultType.getFieldDefinition("someObjectValues").type.deepName) assertEquals("[SomeOtherObject!]!", resultType.getFieldDefinition("someOtherObjectValues").type.deepName) } @Test fun `SchemaGenerator generates a GraphQL schema with mixed nullity`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithNullableAndNonNullTypes())), config = testSchemaConfig) val resultType = schema.getObjectType("MixedNullityResult") val topLevelQuery = schema.getObjectType("TopLevelQuery") assertEquals("MixedNullityResult!", topLevelQuery.getFieldDefinition("query").type.deepName) assertEquals("String", resultType.getFieldDefinition("oneThing").type.deepName) assertEquals("String!", resultType.getFieldDefinition("theNextThing").type.deepName) } @Test fun `SchemaGenerator generates a GraphQL schema where the input types differ from the output types`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithInputObject())), config = testSchemaConfig) val topLevelQuery = schema.getObjectType("TopLevelQuery") assertEquals( "SomeObjectInput!", topLevelQuery.getFieldDefinition("query").getArgument("someObject").type.deepName ) assertEquals("SomeObject!", topLevelQuery.getFieldDefinition("query").type.deepName) } @Test fun `SchemaGenerator generates a GraphQL schema where the input and output enum is the same`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithInputEnum())), config = testSchemaConfig) val topLevelQuery = schema.getObjectType("TopLevelQuery") assertEquals("SomeEnum!", topLevelQuery.getFieldDefinition("query").getArgument("someEnum").type.deepName) assertEquals("SomeEnum!", topLevelQuery.getFieldDefinition("query").type.deepName) } @Test fun `SchemaGenerator documents types annotated with @Description`() { val schema = toSchema( listOf(TopLevelObjectDef(QueryObject())), listOf(TopLevelObjectDef(MutationObject())), config = testSchemaConfig ) val geo = schema.getObjectType("Geography") assertTrue(geo.description.startsWith("A place")) } @Test fun `SchemaGenerator documents arguments annotated with @Description`() { val schema = toSchema( listOf(TopLevelObjectDef(QueryObject())), listOf(TopLevelObjectDef(MutationObject())), config = testSchemaConfig ) val documentation = schema.queryType.fieldDefinitions.first().arguments.first().description assertEquals("A GraphQL value", documentation) } @Test fun `SchemaGenerator documents properties annotated with @Description`() { val schema = toSchema( listOf(TopLevelObjectDef(QueryObject())), listOf(TopLevelObjectDef(MutationObject())), config = testSchemaConfig ) val documentation = schema.queryType.fieldDefinitions.first().description assertEquals("A GraphQL query method", documentation) } @Test fun `SchemaGenerator can expose functions on result classes`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithDataThatContainsFunction())), config = testSchemaConfig) val resultWithFunction = schema.getObjectType("ResultWithFunction") val repeatFieldDefinition = resultWithFunction.getFieldDefinition("repeat") assertEquals("repeat", repeatFieldDefinition.name) assertEquals("Int!", repeatFieldDefinition.arguments.first().type.deepName) assertEquals("String!", repeatFieldDefinition.type.deepName) } @Test fun `SchemaGenerator can execute functions on result classes`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithDataThatContainsFunction())), config = testSchemaConfig) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{ query(something: \"thing\") { repeat(n: 3) } }") val data: Map<String, Map<String, Any>> = result.getData() assertEquals("thingthingthing", data["query"]?.get("repeat")) } @Suppress("Detekt.UnsafeCast") @Test fun `SchemaGenerator ignores private fields`() { val schema = toSchema(listOf(TopLevelObjectDef(QueryWithPrivateParts())), config = testSchemaConfig) val topLevelQuery = schema.getObjectType("TopLevelQuery") val query = topLevelQuery.getFieldDefinition("query") val resultWithPrivateParts = query.type as GraphQLObjectType assertEquals("ResultWithPrivateParts", resultWithPrivateParts.deepName) assertEquals(1, resultWithPrivateParts.fieldDefinitions.size) assertEquals("something", resultWithPrivateParts.fieldDefinitions[0].name) } @Test fun `SchemaGenerator throws when encountering java stdlib`() { assertThrows(RuntimeException::class.java) { toSchema(listOf(TopLevelObjectDef(QueryWithJavaClass())), config = testSchemaConfig) } } @Test fun `SchemaGenerator throws when encountering conflicting types`() { assertThrows(ConflictingTypesException::class.java) { toSchema(queries = listOf(TopLevelObjectDef(QueryWithConflictingTypes())), config = testSchemaConfig) } } @Test fun `SchemaGenerator should throw exception if no queries and no mutations are specified`() { assertThrows(InvalidSchemaException::class.java) { toSchema(emptyList(), emptyList(), config = testSchemaConfig) } } @Test fun `SchemaGenerator supports type references`() { val schema = toSchema(queries = listOf(TopLevelObjectDef(QueryWithParentChildRelationship())), config = testSchemaConfig) val graphQL = GraphQL.newGraphQL(schema).build() val result = graphQL.execute("{ query { name children { name } } }") val data = result.getData<Map<String, Map<String, Any>>>() assertNotNull(data) val res = data["query"] assertEquals("Bob", res?.get("name").toString()) val bobChildren = res?.get("children") as? List<Map<String, Any>> assertNotNull(bobChildren) val firstChild = bobChildren?.get(0) assertEquals("Alice", firstChild?.get("name")) assertNull(firstChild?.get("children")) } class QueryObject { @GraphQLDescription("A GraphQL query method") fun query(@GraphQLDescription("A GraphQL value") value: Int): Geography = Geography(value, GeoType.CITY, listOf()) } class QueryWithArray { fun sumOf(ints: Array<Int>): Int = ints.sum() fun sumOfComplexArray(objects: Array<ComplexWrappingType>): Int = objects.map { it.value }.sum() } class QueryWithIgnored { fun query(): ResultWithIgnored? = null @GraphQLIgnore @Suppress("Detekt.FunctionOnlyReturningConstant") fun ignoredFunction() = "payNoAttentionToMe" } class ResultWithIgnored(val something: String) { @GraphQLIgnore val ignoredProperty = "payNoAttentionToMe" @GraphQLIgnore @Suppress("Detekt.FunctionOnlyReturningConstant") fun ignoredFunction() = "payNoAttentionToMe" } class MutationObject { fun mutation(value: Int): Boolean = value > 0 } data class ComplexWrappingType(val value: Int) @GraphQLDescription("A place") data class Geography( val id: Int?, val type: GeoType, val locations: List<Location> ) enum class GeoType { CITY, STATE } data class Location(val lat: Double, val lon: Double) class QueryWithRepeatedTypes { fun query(): Result = Result( listOf(), listOf(), listOf(), listOf(), SomeObject("something") ) } data class Result( val someIntValues: List<Int>, val someBooleanValues: List<Boolean>, val someObjectValues: List<SomeObject>, val someOtherObjectValues: List<SomeOtherObject>, val someObject: SomeObject? ) data class SomeObject(val name: String) data class SomeOtherObject(val name: String) class QueryWithNullableAndNonNullTypes { fun query(): MixedNullityResult = MixedNullityResult("hey", "ho") } data class MixedNullityResult(val oneThing: String?, val theNextThing: String) class QueryWithInputObject { fun query(someObject: SomeObject): SomeObject = SomeObject("someName") } class QueryWithInputEnum { fun query(someEnum: SomeEnum): SomeEnum = SomeEnum.SomeValue } enum class SomeEnum { SomeValue } class QueryWithDataThatContainsFunction { fun query(something: String): ResultWithFunction? = ResultWithFunction(something) } class ResultWithFunction(private val something: String) { fun repeat(n: Int) = something.repeat(n) } class QueryWithPrivateParts { fun query(something: String): ResultWithPrivateParts? = null } class ResultWithPrivateParts(val something: String) { private val privateSomething: String = "soPrivate" private fun privateFunction(): Int = 2 } class QueryWithJavaClass { fun query(): java.net.CookieManager? = CookieManager() } class QueryWithConflictingTypes { @GraphQLDescription("A conflicting GraphQL query method") fun type1() = GeoType.CITY @GraphQLDescription("A second conflicting GraphQL query method") fun type2() = com.expedia.graphql.conflicts.GeoType.CITY } class QueryWithParentChildRelationship { fun query(): Person { val children = listOf(Person("Alice")) return Person("Bob", children) } } data class Person(val name: String, val children: List<Person>? = null) }
68
null
345
2
270c0b147753fc5c624de3601e3c064fc8d23946
14,026
graphql-kotlin
Apache License 2.0
buildSrc/src/main/kotlin/Maven.kt
adrielcafe
250,125,515
false
null
@file:Suppress("Unused", "MayBeConstant", "MemberVisibilityCanBePrivate") object Maven { const val GROUP_ID = "com.github.adrielcafe.kaptain" }
0
null
3
27
f03d8527d624f5c54add941c1247583317bb3b2e
149
kaptain
MIT License
app/src/main/java/com/example/boggle/ui/main/Fragment2.kt
mar19a
781,254,153
false
{"Kotlin": 9482}
package com.example.boggle.ui.main import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.activityViewModels import com.example.boggle.R import java.io.InputStream class Fragment2 : Fragment() { private lateinit var viewModel: MainViewModel private val sharedViewModel: SharedViewModel by activityViewModels() private lateinit var newGameButton: Button private val dictionary: MutableCollection<String> = mutableListOf() private var alreadySubmitted: MutableCollection<String> = mutableListOf() private var score: Int = 0 private fun getScoreStr(word: String): String { if (!isValidWord(word)) { return "Score: $score" } val vowelCount = word.count { it in "aeiou" } val consonantBonus = if (word.any { it in "szpxq" }) 2 else 1 val baseScore = vowelCount * 5 + (word.length - vowelCount) score += baseScore * consonantBonus val message = if (consonantBonus > 1) "Bravo! Double points!" else "Bravo!" showToast(message) return "Score: $score" } private fun isValidWord(word: String): Boolean { when { word.length < 4 -> showToast("Words should be at least 4 characters long") word.count { it in "aeiou" } < 2 -> showToast("At least 2 vowels should be used") alreadySubmitted.contains(word) -> showToast("Word already submitted") !dictionary.contains(word) -> showToast("This is not a word in English") else -> return true } score = (score - 10).coerceAtLeast(0) return false } private fun showToast(message: String) { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(this)[MainViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment2, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?){ super.onViewCreated(view, savedInstanceState) val inputStream: InputStream = getResources().assets.open("words.txt") inputStream.bufferedReader().forEachLine{ dictionary.add(it.lowercase()) } newGameButton = requireView().findViewById(R.id.new_game_button) newGameButton.setOnClickListener { sharedViewModel.newGameClick.value = true score = 0 alreadySubmitted = mutableListOf() val textView: TextView = requireView().findViewById<View>(R.id.score_text) as TextView textView.text = "Score: 0" } sharedViewModel.typedText.observe(viewLifecycleOwner) {str -> val textView: TextView = requireView().findViewById<View>(R.id.score_text) as TextView textView.text = getScoreStr(str) } } }
0
Kotlin
0
0
7c32e48aa20c1f018a37664a1b5d26f9ea3bf652
3,290
Boggle
MIT License
core/src/main/java/com/paulrybitskyi/gamedge/core/factories/ImageViewerGameUrlFactory.kt
mars885
289,036,871
false
null
/* * Copyright 2021 <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paulrybitskyi.gamedge.core.factories import com.paulrybitskyi.gamedge.common.domain.games.entities.Game import com.paulrybitskyi.hiltbinder.BindType import javax.inject.Inject interface ImageViewerGameUrlFactory { fun createCoverImageUrl(game: Game): String? fun createArtworkImageUrls(game: Game): List<String> fun createScreenshotImageUrls(game: Game): List<String> } @BindType internal class ImageViewerGameUrlFactoryImpl @Inject constructor( private val igdbImageUrlFactory: IgdbImageUrlFactory ) : ImageViewerGameUrlFactory { private companion object { private val IMAGE_SIZE = IgdbImageSize.HD } override fun createCoverImageUrl(game: Game): String? { return game.cover?.let { cover -> igdbImageUrlFactory.createUrl(cover, IgdbImageUrlFactory.Config(IMAGE_SIZE)) } } override fun createArtworkImageUrls(game: Game): List<String> { return igdbImageUrlFactory .createUrls(game.artworks, IgdbImageUrlFactory.Config(IMAGE_SIZE)) } override fun createScreenshotImageUrls(game: Game): List<String> { return igdbImageUrlFactory.createUrls( game.screenshots, IgdbImageUrlFactory.Config(IMAGE_SIZE) ) } }
4
null
63
659
69b3ada08cb877af9b775c6a4f3d9eb1c3470d9c
1,865
gamedge
Apache License 2.0
app/src/main/java/com/ainsigne/masterdetailitunes/data/ItunesItem.kt
cominteract
293,227,775
false
{"HTML": 730239, "Kotlin": 79776, "CSS": 4374}
package com.ainsigne.masterdetailitunes.data import androidx.room.ColumnInfo import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey /** * ItunesItem class for representing the itunes track properties */ @Entity(tableName = "itunes_items") data class ItunesItem ( /** * trackId [Long] the identifier used for the itunes track **/ @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "trackId") var trackId : Long? = null, /** * country [String] to identify which country the itunes track originated */ var country: String? = null, /** * trackName [String] the itunes track name */ var trackName: String? = null, /** * previewUrl [String] the url for preview audio or video */ var previewUrl: String? = null, /** * currency [String] the currency used for the track */ var currency: String? = null, /** * artworkUrl60 [String] the icon url for the itunes track */ var artworkUrl60: String? = null, /** * artworkUrl100 [String] the icon url for the itunes track */ var artworkUrl100: String? = null, /** * artworkUrl150 [String] the icon url for the itunes track */ var artworkUrl150: String? = null, /** * artworkUrl400 [String] the icon url for the itunes track */ var artworkUrl400: String? = null, /** * trackPrice [Double] the price of the itunes track */ var trackPrice: Double = 0.0, /** * trackRentalPrice [Double] the price of the itunes rental track */ var trackRentalPrice: Double = 0.0, /** * trackHdPrice [Double] the price of the itunes hd track */ var trackHdPrice: Double = 0.0, /** * trackBGColor [Int] the bg color of the track randomly assigned */ var trackBGColor: Int = 0, /** * trackHdRentalPrice [Double] the price of the itunes hd rental track */ var trackHdRentalPrice: Double = 0.0, /** * longDescription [String] the long description for the itunes track */ var longDescription: String? = null, /** * longDescription [String] the content advisory rating for the itunes track */ var contentAdvisoryRating: String? = null, /** * releaseDate [String] the release date for the itunes track */ var releaseDate : String? = null, /** * artistName [String] the artist name for the itunes track */ var artistName : String? = null, /** * primaryGenreName [String] the genre name for the itunes track */ var primaryGenreName: String? = null, /** * itunesSearch [ItunesSearch] the itune search parameters to identify what searched access the itunes track */ @field:Embedded(prefix = "itunesSearch_") var itunesSearch: ItunesSearch)
0
HTML
0
0
769838d37aa21685a8a0352d778ce43755ad1646
2,857
iTunesSearchCodingChallenge
MIT License
src/test/kotlin/org/amshove/kluent/tests/backtickassertions/ShouldNotThrowTheExceptionTests.kt
mrobakowski
113,612,831
true
{"Kotlin": 380083}
package org.amshove.kluent.tests.backtickassertions import org.amshove.kluent.AnyException import org.amshove.kluent.`should not throw the Exception` import org.amshove.kluent.`with cause` import org.amshove.kluent.`with message` import org.jetbrains.spek.api.Spek import java.io.IOException import kotlin.test.assertFails class ShouldNotThrowTheExceptionTests : Spek({ given("the should not throw the exception method") { on("providing a function that throws Exception A and shouldn't throw B") { it("should pass") { val func = { throw IllegalArgumentException() } func `should not throw the Exception` ArrayIndexOutOfBoundsException::class } } on("providing a function that doesn't throw an exception") { it("should pass") { val func = { Unit } func `should not throw the Exception` AnyException } } on("providing a function that does throw an exception without the expected message") { it("should pass") { val func = { throw Exception("Hello!") } func `should not throw the Exception` Exception::class `with message` "Another message" } } on("providing a function that does throw an exception with the expected message") { it("should pass") { val func = { throw Exception("The Message") } assertFails({ func `should not throw the Exception` Exception::class `with message` "The Message" }) } } on("providing a function that does throw an exception without the expected cause") { it("should pass") { val func = { throw Exception(RuntimeException()) } func `should not throw the Exception` Exception::class `with cause` IOException::class } } on("providing a function that does throw an exception with the expected cause") { it("should fail") { val func = { throw Exception(RuntimeException()) } assertFails({ func `should not throw the Exception` Exception::class `with cause` RuntimeException::class }) } } } })
0
Kotlin
0
0
e3ad0d9d9bfe923d5f93314cc1b8fd5aac14833d
2,257
Kluent
MIT License
app/src/main/java/matteocrippa/it/raincoat/FlurryProvider.kt
matteocrippa
115,443,025
false
null
package matteocrippa.it.raincoat import android.content.Context import android.util.Log /** * Created by matteocrippa on 27/12/2017. */ class FlurryProvider(private val context: Context, private val apiKey: String) : ProviderType { override var className = Class.forName("com.flurry.android.FlurryAgent") override var classInstance = className.getDeclaredMethod("build", Context::class.java, String::class.java) override var classFunction = className.getDeclaredMethod("logEvent", String::class.java, HashMap::class.java) init { val builder = className.getDeclaredMethod("Builder") try { builder.invoke(className) } catch (e: Exception) { Log.e("Raincoat", e.localizedMessage) } try { classInstance.invoke(builder, context, apiKey) } catch (e: Exception) { Log.e("Raincoat", e.localizedMessage) } } override fun log(eventName: String, parameters: HashMap<String, Any>?) { try { classFunction.invoke(classInstance, eventName, parameters) } catch (e: Exception) { Log.e("Raincoat", e.localizedMessage) } } }
1
Kotlin
5
25
2098e84f5b169c03a1a480e399e981650ba8316d
1,194
Raincoat
MIT License
simplerichtextviewlib/src/main/java/li/yz/simplerichtextviewlib/VerCenterImageSpan.kt
liyuzheng
201,436,863
false
null
package li.yz.simplerichtextviewlib import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.text.style.ImageSpan /** * desc: todo Overview * createed by liyuzheng on 2019/8/9 14:26 */ class VerCenterImageSpan : ImageSpan { constructor(arg0: Context, arg1: Bitmap) : super(arg0, arg1) constructor(context: Context, drawableInt: Int) : super(context, drawableInt) override fun getSize( paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt? ): Int { val d = drawable val rect = d.bounds if (fm != null) { val fmPaint = paint.fontMetricsInt val fontHeight = fmPaint.bottom - fmPaint.top val drHeight = rect.bottom - rect.top val top = drHeight / 2 - fontHeight / 4 val bottom = drHeight / 2 + fontHeight / 4 fm.ascent = -bottom fm.top = -bottom fm.bottom = top fm.descent = top } return rect.right } override fun draw( canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint ) { val b = drawable canvas.save() var transY = 0 transY = ((bottom - top) - b.bounds.bottom) / 2 + top canvas.translate(x, transY.toFloat()) b.draw(canvas) canvas.restore() } }
1
Kotlin
1
1
572adc8944771ace1df7d2899429950320886077
1,491
SimpleRichTextView
Apache License 2.0
client-api/src/main/kotlin/org/ostelco/prime/client/api/resources/ProductsResource.kt
mdheyab
157,444,239
true
{"Kotlin": 613166, "Java": 82884, "Shell": 48278, "Dockerfile": 4589}
package org.ostelco.prime.client.api.resources import io.dropwizard.auth.Auth import org.ostelco.prime.auth.AccessTokenPrincipal import org.ostelco.prime.client.api.store.SubscriberDAO import org.ostelco.prime.jsonmapper.asJson import javax.validation.constraints.NotNull import javax.ws.rs.GET import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import javax.ws.rs.core.Response.Status.CREATED /** * Products API. * */ @Path("/products") class ProductsResource(private val dao: SubscriberDAO) { @GET @Produces(MediaType.APPLICATION_JSON) fun getProducts(@Auth token: AccessTokenPrincipal?): Response { if (token == null) { return Response.status(Response.Status.UNAUTHORIZED) .build() } return dao.getProducts(token.name).fold( { apiError -> Response.status(apiError.status).entity(asJson(apiError)) }, { Response.status(Response.Status.OK).entity(asJson(it)) }) .build() } @POST @Path("{sku}/purchase") @Produces(MediaType.APPLICATION_JSON) fun purchaseProduct(@Auth token: AccessTokenPrincipal?, @NotNull @PathParam("sku") sku: String, @QueryParam("sourceId") sourceId: String?, @QueryParam("saveCard") saveCard: Boolean?): Response { /* 'false' is default. */ if (token == null) { return Response.status(Response.Status.UNAUTHORIZED) .build() } return dao.purchaseProduct(token.name, sku, sourceId, saveCard ?: false) .fold( { apiError -> Response.status(apiError.status).entity(asJson(apiError)) }, { productInfo -> Response.status(CREATED).entity(productInfo) } ).build() } }
0
Kotlin
0
0
dd306f17137828cc177836e1be4addccaef5982e
2,089
ostelco-core
Apache License 2.0
app/src/main/java/com/example/webbookmarker/ui/Fragments/AddNoteBottomSheet.kt
tushartripathi
684,671,869
false
{"Kotlin": 15703, "Java": 71}
package com.example.webbookmarker.ui.Fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.webbookmarker.databinding.FragmentBottomSheetBinding import com.example.webbookmarker.ui.TakeNote.MainActivity import com.google.android.material.bottomsheet.BottomSheetDialogFragment class AddNoteBottomSheet : BottomSheetDialogFragment() { lateinit var binding : FragmentBottomSheetBinding private val viewModel by lazy { (activity as MainActivity).viewModel } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentBottomSheetBinding.inflate(layoutInflater, container, false) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.closeIv.setOnClickListener{ dismiss() } binding.addBtn.setOnClickListener{ if(!binding.noteEt.text.isNullOrEmpty()) { var axis = viewModel.yAxisPosition.value viewModel.setNotesValue(binding.noteEt.text.toString()) dismiss() } } } override fun onDestroy() { super.onDestroy() viewModel.setLongPressValue(false) } }
0
Kotlin
0
0
d03808541fbe125d8b53cdf10bd739f656125e2b
1,417
Web_Bookmarker
MIT License
src/main/kotlin/turniplabs/industry/blocks/entities/lv/TileEntityRecycler.kt
FatherCheese
673,567,283
false
{"Kotlin": 207937, "Java": 3827}
package turniplabs.industry.blocks.entities import com.mojang.nbt.CompoundTag import com.mojang.nbt.ListTag import net.minecraft.core.entity.player.EntityPlayer import net.minecraft.core.item.ItemStack import net.minecraft.core.player.inventory.IInventory import sunsetsatellite.energyapi.impl.ItemEnergyContainer import sunsetsatellite.sunsetutils.util.Connection import sunsetsatellite.sunsetutils.util.Direction import turniplabs.industry.blocks.IndustryBlocks import turniplabs.industry.blocks.machines.BlockMacerator import turniplabs.industry.recipes.RecipesMacerator class TileEntityMacerator: TileEntityEnergyConductorDamageable(), IInventory { var active = false private var contents: Array<ItemStack?> private var currentCrushTime = 0 private val maxCrushTime = 160 init { contents = arrayOfNulls(4) setCapacity(1024) setTransfer(32) setMaxReceive(32) for (dir in Direction.values()) setConnection(dir, Connection.INPUT) } override fun getSizeInventory(): Int { return contents.size } override fun getStackInSlot(i: Int): ItemStack? { return contents[i] } override fun decrStackSize(i: Int, j: Int): ItemStack? { return if (contents[i] != null) { if (contents[i]!!.stackSize <= j) { val itemStack: ItemStack? = contents[i] contents[i] = null onInventoryChanged() return itemStack!! } val itemStack: ItemStack = contents[i]!!.splitStack(j) if (contents[i]!!.stackSize == 0) { contents[i] = null } onInventoryChanged() itemStack } else return null } override fun setInventorySlotContents(i: Int, itemStack: ItemStack?) { contents[i] = itemStack if (itemStack != null && itemStack.stackSize > inventoryStackLimit) itemStack.stackSize = inventoryStackLimit onInventoryChanged() } override fun getInvName(): String { return "Macerator" } override fun getInventoryStackLimit(): Int { return 64 } override fun canInteractWith(entityPlayer: EntityPlayer?): Boolean { if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this) return false return entityPlayer!!.distanceToSqr( (xCoord + 0.5f).toDouble(), (yCoord + 0.5f).toDouble(), (zCoord + 0.5f).toDouble() ) <= 64.0f } override fun updateEntity() { super.updateEntity() val hasEnergy: Boolean = energy > 0 var machineUpdated = false if (getStackInSlot(0) != null && getStackInSlot(0)?.item is ItemEnergyContainer) { provide(getStackInSlot(0), getMaxProvide(), false) onInventoryChanged() } if (getStackInSlot(1) != null && getStackInSlot(1)?.item is ItemEnergyContainer) { val stack: ItemStack? = getStackInSlot(1) receive(stack, maxReceive, false) onInventoryChanged() } if (!worldObj.isClientSide) { if (worldObj.getBlockId(xCoord, yCoord, zCoord) == IndustryBlocks.machineMacerator.id && currentCrushTime == 0 && contents[2] == null ) { BlockMacerator.updateBlockState(true, worldObj, xCoord, yCoord, zCoord) machineUpdated = true } } if (hasEnergy && canCrush()) { ++currentCrushTime --energy active = true if (currentCrushTime == maxCrushTime) { currentCrushTime = 0 crushItem() active = false machineUpdated = true } } else { currentCrushTime = 0 active = false } if (machineUpdated) onInventoryChanged() if (active) worldObj.markBlockDirty(xCoord, yCoord, zCoord) } override fun readFromNBT(compoundTag: CompoundTag?) { super.readFromNBT(compoundTag) val nbtTagList = compoundTag!!.getList("Items") contents = arrayOfNulls(sizeInventory) for (i in 0 until nbtTagList.tagCount()) { val compoundTag2: CompoundTag = nbtTagList.tagAt(i) as CompoundTag val byte: Int = compoundTag2.getByte("Slot").toInt() if (byte >= 0 && byte < contents.size) contents[byte] = ItemStack.readItemStackFromNbt(compoundTag2) } currentCrushTime = compoundTag.getShort("CookTime").toInt() energy = compoundTag.getShort("Energy").toInt() } override fun writeToNBT(compoundTag: CompoundTag?) { super.writeToNBT(compoundTag) compoundTag?.putShort("CookTime", currentCrushTime.toShort()) compoundTag?.putShort("Energy", energy.toShort()) val listTag = ListTag() for (i in contents.indices) { if (contents[i] != null) { val compoundTag2 = CompoundTag() compoundTag2.putByte("Slot", i.toByte()) contents[i]!!.writeToNBT(compoundTag2) listTag.addTag(compoundTag2) } } compoundTag!!.put("Items", listTag) } private fun canCrush(): Boolean { if (contents[2] == null) return false if (contents[2]!!.item == null) return false val itemStack: ItemStack? = RecipesMacerator.getResult(contents[2]!!.item.id) return when { contents[3] == null -> true !contents[3]!!.isItemEqual(itemStack) -> false contents[3]!!.stackSize < inventoryStackLimit && contents[3]!!.stackSize < contents[3]!!.maxStackSize -> true else -> contents[3]!!.stackSize < itemStack!!.maxStackSize } } private fun crushItem() { if (canCrush()) { val itemStack: ItemStack = RecipesMacerator.getResult(contents[2]!!.item.id) ?: return if (contents[3] == null) contents[3] = itemStack.copy() else if (contents[3]!!.itemID == itemStack.itemID) ++contents[3]!!.stackSize --contents[2]!!.stackSize if (contents[2]!!.stackSize <= 0) contents[2] = null } } fun getProgressScaled(i: Int): Int { return if (maxCrushTime == 0) 0 else (currentCrushTime * i) / maxCrushTime } }
1
Kotlin
2
1
9daa4a3ddbcdbb65ebc7fc2056d68d647c8b00b7
6,575
Industry2
Creative Commons Zero v1.0 Universal
core/src/main/kotlin/io/github/oleksivio/tl/kbot/core/model/annotation/validator/impl/AnimationFilterValidator.kt
oleksivio
145,889,451
false
null
package io.github.oleksivio.tl.kbot.core.model.annotation.validator.impl import io.github.oleksivio.tl.kbot.core.controller.handler.check.Validator import io.github.oleksivio.tl.kbot.core.model.annotation.validator.FilterValidator import io.github.oleksivio.tl.kbot.server.api.objects.std.game.Animation class AnimationFilterValidator(validator: Validator<Animation>) : FilterValidator<Animation>( Animation::class, validator )
0
Kotlin
0
5
d38b5be33c5217a3f91e44394995f112fd6b0ab9
434
tl-kbot
Apache License 2.0
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ClassOrderingSpec.kt
touki24
355,162,546
true
{"Kotlin": 2444877, "HTML": 4173, "Groovy": 2423, "Shell": 358, "CSS": 27}
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class ClassOrderingSpec : Spek({ val subject by memoized { ClassOrdering(Config.empty) } describe("ClassOrdering rule") { it("does not report when class contents are in expected order with property first") { val code = """ class InOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("does not report when class contents are in expected order with class initializer first") { val code = """ class InOrder(private val x: String) { init { check(x == "yes") } val y = x constructor(z: Int): this(z.toString()) fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("reports when class initializer block is out of order") { val code = """ class OutOfOrder(private val x: String) { val y = x constructor(z: Int): this(z.toString()) init { check(x == "yes") } fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("OutOfOrder (secondary constructor) " + "should not come before class initializer") } it("reports when secondary constructor is out of order") { val code = """ class OutOfOrder(private val x: String) { constructor(z: Int): this(z.toString()) val y = x init { check(x == "yes") } fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("OutOfOrder (secondary constructor) " + "should not come before y (property)") } it("reports when method is out of order") { val code = """ class OutOfOrder(private val x: String) { fun returnX() = x val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("returnX (function) should not come before y (property)") } it("reports when companion object is out of order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) companion object { const val IMPORTANT_VALUE = 3 } fun returnX() = x } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("Companion object should not come before returnX (function)") } it("does not report nested class order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) class Nested { fun foo() = 2 } fun returnX() = x } """ assertThat(subject.compileAndLint(code)).hasSize(0) } it("does not report anonymous object order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) object AnonymousObject { fun foo() = 2 } fun returnX() = x } """ assertThat(subject.compileAndLint(code)).hasSize(0) } it("does report all issues in a class with multiple misorderings") { val code = """ class MultipleMisorders(private val x: String) { companion object { const val IMPORTANT_VALUE = 3 } fun returnX() = x constructor(z: Int): this(z.toString()) val y = x } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(3) assertThat(findings[0].message) .isEqualTo("Companion object should not come before returnX (function)") assertThat(findings[1].message) .isEqualTo("returnX (function) should not come before MultipleMisorders (secondary constructor)") assertThat(findings[2].message) .isEqualTo("MultipleMisorders (secondary constructor) should not come before y (property)") } } })
0
null
0
1
da6259a15c986d248799cc5f2db308689e4fc68e
6,915
detekt
Apache License 2.0
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ClassOrderingSpec.kt
touki24
355,162,546
true
{"Kotlin": 2444877, "HTML": 4173, "Groovy": 2423, "Shell": 358, "CSS": 27}
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class ClassOrderingSpec : Spek({ val subject by memoized { ClassOrdering(Config.empty) } describe("ClassOrdering rule") { it("does not report when class contents are in expected order with property first") { val code = """ class InOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("does not report when class contents are in expected order with class initializer first") { val code = """ class InOrder(private val x: String) { init { check(x == "yes") } val y = x constructor(z: Int): this(z.toString()) fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("reports when class initializer block is out of order") { val code = """ class OutOfOrder(private val x: String) { val y = x constructor(z: Int): this(z.toString()) init { check(x == "yes") } fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("OutOfOrder (secondary constructor) " + "should not come before class initializer") } it("reports when secondary constructor is out of order") { val code = """ class OutOfOrder(private val x: String) { constructor(z: Int): this(z.toString()) val y = x init { check(x == "yes") } fun returnX() = x companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("OutOfOrder (secondary constructor) " + "should not come before y (property)") } it("reports when method is out of order") { val code = """ class OutOfOrder(private val x: String) { fun returnX() = x val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) companion object { const val IMPORTANT_VALUE = 3 } } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("returnX (function) should not come before y (property)") } it("reports when companion object is out of order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) companion object { const val IMPORTANT_VALUE = 3 } fun returnX() = x } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(1) assertThat(findings[0].message).isEqualTo("Companion object should not come before returnX (function)") } it("does not report nested class order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) class Nested { fun foo() = 2 } fun returnX() = x } """ assertThat(subject.compileAndLint(code)).hasSize(0) } it("does not report anonymous object order") { val code = """ class OutOfOrder(private val x: String) { val y = x init { check(x == "yes") } constructor(z: Int): this(z.toString()) object AnonymousObject { fun foo() = 2 } fun returnX() = x } """ assertThat(subject.compileAndLint(code)).hasSize(0) } it("does report all issues in a class with multiple misorderings") { val code = """ class MultipleMisorders(private val x: String) { companion object { const val IMPORTANT_VALUE = 3 } fun returnX() = x constructor(z: Int): this(z.toString()) val y = x } """ val findings = subject.compileAndLint(code) assertThat(findings).hasSize(3) assertThat(findings[0].message) .isEqualTo("Companion object should not come before returnX (function)") assertThat(findings[1].message) .isEqualTo("returnX (function) should not come before MultipleMisorders (secondary constructor)") assertThat(findings[2].message) .isEqualTo("MultipleMisorders (secondary constructor) should not come before y (property)") } } })
0
null
0
1
da6259a15c986d248799cc5f2db308689e4fc68e
6,915
detekt
Apache License 2.0
src/main/kotlin/pistonlang/compiler/piston/parser/Tokens.kt
PistonLang
594,852,711
false
null
package pistonlang.compiler.piston.parser import pistonlang.compiler.common.parser.nodes.GreenLeaf typealias PistonToken = GreenLeaf<PistonType> object Tokens { val thisKw = GreenLeaf(PistonType.thisKw, "this") val superKw = GreenLeaf(PistonType.superKw, "super") val nullKw = GreenLeaf(PistonType.nullKw, "null") val whereKw = GreenLeaf(PistonType.whereKw, "where") val importKw = GreenLeaf(PistonType.importKw, "import") val valKw = GreenLeaf(PistonType.valKw, "val") val varKw = GreenLeaf(PistonType.varKw, "var") val defKw = GreenLeaf(PistonType.defKw, "def") val classKw = GreenLeaf(PistonType.classKw, "class") val traitKw = GreenLeaf(PistonType.traitKw, "trait") val trueKw = GreenLeaf(PistonType.trueKw, "true") val falseKw = GreenLeaf(PistonType.falseKw, "false") val newline = GreenLeaf(PistonType.newline, "\n") val eof = GreenLeaf(PistonType.eof, "") val eq = GreenLeaf(PistonType.eq, "=") val eqEq = GreenLeaf(PistonType.eqEq, "==") val eMark = GreenLeaf(PistonType.unknown, "!") val eMarkEq = GreenLeaf(PistonType.eMarkEq, "!=") val less = GreenLeaf(PistonType.less, "<") val greater = GreenLeaf(PistonType.greater, ">") val lessEq = GreenLeaf(PistonType.lessEq, "<=") val greaterEq = GreenLeaf(PistonType.greaterEq, ">=") val andAnd = GreenLeaf(PistonType.andAnd, "&&") val orOr = GreenLeaf(PistonType.orOr, "||") val plus = GreenLeaf(PistonType.plus, "+") val minus = GreenLeaf(PistonType.minus, "-") val star = GreenLeaf(PistonType.star, "*") val slash = GreenLeaf(PistonType.slash, "/") val dot = GreenLeaf(PistonType.dot, ".") val comma = GreenLeaf(PistonType.comma, ",") val qMark = GreenLeaf(PistonType.qMark, "?") val colon = GreenLeaf(PistonType.colon, ":") val lParen = GreenLeaf(PistonType.lParen, "(") val rParen = GreenLeaf(PistonType.rParen, ")") val lBracket = GreenLeaf(PistonType.lBracket, "[") val rBracket = GreenLeaf(PistonType.rBracket, "]") val lBrace = GreenLeaf(PistonType.lBrace, "{") val rBrace = GreenLeaf(PistonType.rBrace, "}") val or = GreenLeaf(PistonType.unknown, "|") val and = GreenLeaf(PistonType.and, "&") val subtype = GreenLeaf(PistonType.subtype, "<:") val superType = GreenLeaf(PistonType.supertype, ">:") val nullChar = GreenLeaf(PistonType.unknown, "\u0000") val singleQuote = GreenLeaf(PistonType.charLiteral, "\'") }
0
Kotlin
0
0
3ad84cb6c0e108c30c15abc82f9094e73b8b06f6
2,463
compiler
MIT License
domain/src/main/java/com/vuxur/khayyam/domain/model/Poem.kt
deghat-farhad
518,348,997
false
{"Kotlin": 185801}
package com.vuxur.khayyam.domain.model data class Poem( val id: Int, val index: String, val hemistich1: String, val hemistich2: String, val hemistich3: String, val hemistich4: String, val isSuspicious: Boolean, val translation: Translation, )
18
Kotlin
0
0
886f705c81e11a1ee85a74ee9835e6af327ce81d
275
khayam
MIT License
src/main/kotlin/pl/jwizard/core/vote/SongChooserVotingSystemHandler.kt
jwizard-bot
512,298,084
false
{"Kotlin": 226798, "Dockerfile": 262}
/* * Copyright (c) 2024 by JWizard * Originally developed by Miłosz Gilga <https://miloszgilga.pl> */ package pl.jwizard.core.vote import com.sedmelluq.discord.lavaplayer.track.AudioTrack import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.api.requests.RestAction import org.apache.commons.lang3.StringUtils import pl.jwizard.core.bot.BotConfiguration import pl.jwizard.core.command.CompoundCommandEvent import pl.jwizard.core.command.embed.CustomEmbedBuilder import pl.jwizard.core.command.embed.EmbedColor import pl.jwizard.core.command.embed.UnicodeEmoji import pl.jwizard.core.i18n.I18nMiscLocale import pl.jwizard.core.i18n.I18nResLocale import pl.jwizard.core.log.AbstractLoggingBean import pl.jwizard.core.util.Formatter import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger class SongChooserVotingSystemHandler( private val loadedTracks: List<AudioTrack>, val botConfiguration: BotConfiguration, val event: CompoundCommandEvent, val onSelectTrackCallback: (audioTrack: AudioTrack) -> Unit, private val lockedGuilds: MutableList<String>, ) : VotingSystemHandler, AbstractLoggingBean(SongChooserVotingSystemHandler::class) { private val selectedIndex = AtomicInteger() private var elapsedTimeInSec = 0L private var countOfMaxTracks = 0 private var isRandom = true private var trimmedTracks = listOf<AudioTrack>() override fun initAndStart() { lockedGuilds.add(event.guildId) val guildDetails = botConfiguration.guildSettingsSupplier.fetchVotingSongChooserSettings(event.guildDbId) isRandom = guildDetails.randomAutoChooseTrack elapsedTimeInSec = guildDetails.timeAfterAutoChooseSec.toLong() countOfMaxTracks = guildDetails.tracksToChooseMax trimmedTracks = loadedTracks.subList(0, countOfMaxTracks) jdaLog.info( event, "Initialized voting for select song from results list: ${trimmedTracks.joinToString { it.info.title }}" ) val joiner = StringJoiner(StringUtils.EMPTY) val initEmbedMessage = botConfiguration.i18nService.getMessage( i18nLocale = I18nResLocale.SELECT_SONG_SEQUENCER, params = mapOf( "resultsFound" to trimmedTracks.size, "elapsedTime" to elapsedTimeInSec, "afterTimeResult" to botConfiguration.i18nService.getMessage( if (isRandom) I18nMiscLocale.RANDOM_RESULT else I18nMiscLocale.FIRST_RESULT, event.lang ), ), event.lang, ) joiner.add(initEmbedMessage) joiner.add("\n\n") for (index in trimmedTracks.indices) { joiner.add("`${index}` ") joiner.add(Formatter.createRichTrackTitle(trimmedTracks[index])) joiner.add("\n") } val embedMessage = CustomEmbedBuilder(botConfiguration, event) .addAuthor() .setDescription(joiner.toString()) .setColor(EmbedColor.WHITE.color()) .build() val hook = event.slashCommandEvent?.hook val messageAction = if (hook?.isExpired == false) { hook.sendMessageEmbeds(embedMessage) } else { event.textChannel.sendMessageEmbeds(embedMessage) } val emojisCallback: (message: Message) -> RestAction<List<Void>> = { message -> RestAction.allOf( UnicodeEmoji.getNumbers(countOfMaxTracks).map { message.addReaction(it.createEmoji()) }) } messageAction.queue { message -> emojisCallback(message).queue { fabricateEventWaiter(message) } } } private fun fabricateEventWaiter(message: Message) { botConfiguration.eventWaiter.waitForEvent( MessageReactionAddEvent::class.java, { onAfterSelect(it, message) }, { lockedGuilds.remove(event.guildId) onSelectTrackCallback(trimmedTracks[selectedIndex.get()]) }, elapsedTimeInSec, TimeUnit.SECONDS, { onAfterTimeout(message) } ) } private fun onAfterSelect(gEvent: MessageReactionAddEvent, message: Message): Boolean { if (gEvent.messageId != message.id || gEvent.user?.isBot == true) { return false // end on different message or bot self-instance } val emoji = gEvent.reaction.emoji if (gEvent.user != null && gEvent.userId != event.author.id) { message.removeReaction(emoji, gEvent.user as User).queue() return false // skip for non-invoking voting user } val selectedEmoji = UnicodeEmoji.getNumbers(countOfMaxTracks) .find { it.code == emoji.asReactionCode } ?: return false val index = selectedEmoji.index selectedIndex.set(index) message.clearReactions().queue() jdaLog.info( event, "Selecting track was ended successfully. Selected track ($selectedIndex): ${ Formatter.trackStr(trimmedTracks[index]) }" ) return true } private fun onAfterTimeout(message: Message) { val selectedIndex = if (isRandom) { Random().nextInt(0, trimmedTracks.size) } else { 0 } val selectedTrack = trimmedTracks[selectedIndex] jdaLog.info( event, "Selecting track from results is ended. Selected track (${selectedIndex}): ${ Formatter.trackStr(selectedTrack) }" ) message.clearReactions().queue() lockedGuilds.remove(event.guildId) onSelectTrackCallback(selectedTrack) } }
2
Kotlin
0
2
d306d5cbff3cf8b758d12762c58329691afc72ff
5,098
jwizard-core
Apache License 2.0
src/main/kotlin/ch/unibas/dmi/dbis/cottontail/model/basics/ColumnDef.kt
sauterl
202,150,029
true
{"Kotlin": 483171, "ANTLR": 12918}
package ch.unibas.dmi.dbis.cottontail.model.basics import ch.unibas.dmi.dbis.cottontail.database.column.* import ch.unibas.dmi.dbis.cottontail.model.exceptions.DatabaseException import ch.unibas.dmi.dbis.cottontail.model.exceptions.ValidationException import ch.unibas.dmi.dbis.cottontail.model.values.* import ch.unibas.dmi.dbis.cottontail.utilities.name.Name import java.lang.RuntimeException /** * A definition class for a Cottontail DB column be it in a DB or in-memory context. Specifies all the properties of such a and facilitates validation. * * @author <NAME> * @version 1.1 */ class ColumnDef<T: Any> (name: Name, val type: ColumnType<T>, val size: Int = -1, val nullable: Boolean = true) { /** * Companion object with some convenience methods. */ companion object { /** * Returns a [ColumnDef] with the provided attributes. The only difference as compared to using the constructor, is that the [ColumnType] can be provided by name. * * @param name Name of the new [Column] * @param type Name of the [ColumnType] of the new [Column] * @param size Size of the new [Column] (e.g. for vectors), where eligible. * @param nullable Whether or not the [Column] should be nullable. */ fun withAttributes(name: Name, type: String, size: Int = -1, nullable: Boolean = true): ColumnDef<*> = ColumnDef(name.toLowerCase(), ColumnType.forName(type), size, nullable) } /** The [Name] of this [ColumnDef]. Lower-case values are enforced since Cottontail DB is not case-sensitive! */ val name = name.toLowerCase() /** * Validates a value with regard to this [ColumnDef] and throws an Exception, if validation fails. * * @param value The value that should be validated. * @throws [DatabaseException.ValidationException] If validation fails. */ fun validateOrThrow(value: Value<*>?) { if (value != null) { if (!this.type.compatible(value)) { throw ValidationException("The type $type of column '$name' is not compatible with value $value.") } val cast = this.type.cast(value) when { cast is DoubleArrayValue && cast.size != this.size -> throw ValidationException("The size of column '$name' (sc=${this.size}) is not compatible with size of value (sv=${cast.size}).") cast is FloatArrayValue && cast.size != this.size -> throw ValidationException("The size of column '$name' (sc=${this.size}) is not compatible with size of value (sv=${cast.size}).") cast is LongArrayValue && cast.size != this.size -> throw ValidationException("The size of column '$name' (sc=${this.size}) is not compatible with size of value (sv=${cast.size}).") cast is IntArrayValue && cast.size != this.size -> throw ValidationException("The size of column '$name' (sc=${this.size}) is not compatible with size of value (sv=${cast.size}).") } } else if (!this.nullable) { throw ValidationException("The column '$name' cannot be null!") } } /** * Validates a value with regard to this [ColumnDef] return a flag indicating whether validation was passed. * * @param value The value that should be validated. * @return True if value passes validation, false otherwise. */ fun validate(value: Value<*>?) : Boolean { if (value != null) { if (!this.type.compatible(value)) { return false } val cast = this.type.cast(value) return when { cast is DoubleArrayValue && cast.size != this.size -> false cast is FloatArrayValue && cast.size != this.size -> false cast is LongArrayValue && cast.size != this.size -> false cast is IntArrayValue && cast.size != this.size -> false else -> true } } else return this.nullable } /** * Returns the default value for this [ColumnDef]. * * @return Default value for this [ColumnDef]. */ fun defaultValue(): Value<*>? = when { this.nullable -> null this.type is StringColumnType -> StringValue("") this.type is FloatColumnType -> FloatValue(0.0f) this.type is DoubleColumnType -> DoubleValue(0.0) this.type is IntColumnType -> IntValue(0) this.type is LongColumnType -> LongValue(0L) this.type is ShortColumnType -> ShortValue(0.toShort()) this.type is ByteColumnType -> ByteValue(0.toByte()) this.type is BooleanColumnType -> BooleanValue(false) this.type is DoubleArrayColumnType -> DoubleArrayValue(DoubleArray(this.size)) this.type is FloatArrayColumnType -> FloatArrayValue(FloatArray(this.size)) this.type is LongArrayColumnType -> LongArrayValue(LongArray(this.size)) this.type is IntArrayColumnType -> IntArrayValue(IntArray(this.size)) else -> throw RuntimeException("Default value for the specified type $type has not been specified yet!") } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ColumnDef<*> if (name != other.name) return false if (type != other.type) return false if (size != other.size) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + type.hashCode() result = 31 * result + size.hashCode() return result } override fun toString(): String = "$name(type=$type, size=$size, nullable=$nullable)" }
0
Kotlin
0
0
bc25f6be57b93f0658404025706204ff5f24f830
5,757
cottontaildb
MIT License
app/src/main/java/com/example/andriginting/footballmatch/view/detail/player/DetailPlayerContract.kt
andriiginting
160,222,285
false
null
package com.example.andriginting.footballmatch.view.detail.player import com.example.andriginting.footballmatch.model.player.PlayerModel interface DetailPlayerContract { interface View{ fun receivedData(data: PlayerModel) fun setToolbarTitle(title: String) } }
0
Kotlin
0
1
c227005cb563666d7358d71e6cf98a881dad2383
286
football-match
MIT License
app/src/main/java/com/example/hrautomation/presentation/view/product/ProductFragment.kt
SasikSiderking
547,823,297
false
{"Kotlin": 314104}
package com.example.hrautomation.presentation.view.product import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.hrautomation.R import com.example.hrautomation.app.App import com.example.hrautomation.databinding.FragmentProductBinding import com.example.hrautomation.presentation.base.delegates.BaseListItem import com.example.hrautomation.presentation.model.products.ProductCategoryItem import com.example.hrautomation.utils.ViewModelFactory import com.example.hrautomation.utils.ui.switcher.ContentLoadingSettings import com.example.hrautomation.utils.ui.switcher.ContentLoadingState import com.example.hrautomation.utils.ui.switcher.ContentLoadingStateSwitcher import com.example.hrautomation.utils.ui.switcher.base.SwitchAnimationParams import com.google.android.material.chip.Chip import com.google.android.material.chip.ChipGroup import javax.inject.Inject class ProductFragment : Fragment() { private var _binding: FragmentProductBinding? = null private val binding: FragmentProductBinding get() = _binding!! private lateinit var adapter: ProductAdapter @Inject lateinit var viewModelFactory: ViewModelFactory private val viewModel: ProductViewModel by viewModels { viewModelFactory } private val contentLoadingSwitcher: ContentLoadingStateSwitcher = ContentLoadingStateSwitcher() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (requireContext().applicationContext as App).appComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentProductBinding.inflate(inflater, container, false) initToolbar() initUi() binding.chipGroup.setOnCheckedStateChangeListener { group, checkedIds -> chooseCategory(group, checkedIds) } return binding.root } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun initToolbar() { (activity as? AppCompatActivity)?.supportActionBar?.let { it.elevation = 0F } } private fun initUi() { with(binding) { contentLoadingSwitcher.setup( ContentLoadingSettings( contentViews = listOf(coordinatorLayout), errorViews = listOf(reusableReload.reusableReload), loadingViews = listOf(reusableLoading.progressBar), initState = ContentLoadingState.LOADING ) ) adapter = ProductAdapter(OnProductClickListener { id: Long, name: String -> showOrderDialog(id, name) }) binding.productRecyclerview.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) binding.productRecyclerview.adapter = adapter reusableReload.reloadButton.setOnClickListener { viewModel.reload() contentLoadingSwitcher.switchState(ContentLoadingState.LOADING, SwitchAnimationParams(delay = 500L)) } productRecyclerview.addItemDecoration(DividerItemDecoration(context, RecyclerView.VERTICAL)) } viewModel.data.observe(viewLifecycleOwner, productObserver) viewModel.categories.observe(viewLifecycleOwner, categoriesObserver) viewModel.exception.observe(viewLifecycleOwner, exceptionObserver) viewModel.message.observe(viewLifecycleOwner, messageObserver) } private val productObserver = Observer<List<BaseListItem>> { newItems -> adapter.update(newItems) contentLoadingSwitcher.switchState(ContentLoadingState.CONTENT, SwitchAnimationParams(delay = 500L)) } private val categoriesObserver = Observer<List<ProductCategoryItem>> { newItems -> fillChipGroup(newItems) } private fun fillChipGroup(list: List<ProductCategoryItem>) { binding.chipGroup.removeAllViews() list.forEach { category -> val chip = Chip(context).apply { id = category.id.toInt() text = category.name setChipBackgroundColorResource(R.color.white) isClickable = true isCheckable = true } binding.chipGroup.addView(chip) } } private fun chooseCategory(group: ChipGroup, checkedIds: List<Int>) { var categoryId: Long? = null checkedIds.firstOrNull()?.let { checkedId -> val chip: Chip = group.findViewById(checkedId) categoryId = chip.id.toLong() } viewModel.loadProductsByCategory(categoryId) } private val exceptionObserver = Observer<Throwable?> { exception -> exception?.let { contentLoadingSwitcher.switchState(ContentLoadingState.ERROR, SwitchAnimationParams(delay = 500L)) } } private val messageObserver = Observer<Int?> { stringId -> stringId?.let { Toast.makeText(requireContext(), getString(stringId), Toast.LENGTH_SHORT).show() viewModel.clearMessageState() } } private fun showOrderDialog(id: Long, name: String) { val builder: AlertDialog.Builder = AlertDialog.Builder(context) builder.apply { setPositiveButton( getString(R.string.order_product_dialog_positive), DialogInterface.OnClickListener { _, _ -> viewModel.orderProduct(id) } ) setNegativeButton(getString(R.string.order_product_dialog_negative), DialogInterface.OnClickListener { dialog, _ -> dialog.cancel() } ) } builder .setMessage(getString(R.string.order_product_dialog_message, name)) .setTitle(getString(R.string.order_product_dialog_title)) builder.show() } }
9
Kotlin
0
0
71cd82f40ae70793cd75b6341536f13f79471dfc
6,505
HRautomation
MIT License
server/server-app/src/main/kotlin/projektor/route/TestRunSystemAttributesRoutes.kt
craigatk
226,096,594
false
null
package projektor.route import io.ktor.http.HttpStatusCode import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.util.* import projektor.server.api.PublicId import projektor.testrun.attributes.TestRunSystemAttributesService fun Route.testRunSystemAttributes(testRunSystemAttributesService: TestRunSystemAttributesService) { get("/run/{publicId}/attributes") { val publicId = call.parameters.getOrFail("publicId") val systemAttributes = testRunSystemAttributesService.fetchAttributes(PublicId(publicId)) systemAttributes?.let { call.respond(HttpStatusCode.OK, it) } ?: call.respond(HttpStatusCode.NotFound) } post("/run/{publicId}/attributes/pin") { val publicId = call.parameters.getOrFail("publicId") val rowsAffected = testRunSystemAttributesService.pin(PublicId(publicId)) if (rowsAffected > 0) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) } post("/run/{publicId}/attributes/unpin") { val publicId = call.parameters.getOrFail("publicId") val rowsAffected = testRunSystemAttributesService.unpin(PublicId(publicId)) if (rowsAffected > 0) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) } }
14
Kotlin
12
41
83ad62007dc8f70a7581387a4212f7096145c5f7
1,335
projektor
MIT License
src/test/resources/objectExpression/objectSuperType.kt
JetBrains
250,351,744
false
null
import java.awt.event.MouseAdapter import java.awt.event.MouseEvent <warning descr="SSR">fun a() = object : MouseAdapter() { }</warning> fun b() = object { }
9
Kotlin
2
17
40f5895867975ee38b60333033672b7957bfb491
159
intellij-structural-search-for-kotlin
Apache License 2.0
src/main/kotlin/com/disney/studios/titlemanager/repository/TitleRepository.kt
ulisesbocchio
119,489,222
false
null
package com.disney.studios.titlemanager.repository import com.disney.studios.titlemanager.document.Title import org.springframework.data.mongodb.repository.ReactiveMongoRepository import org.springframework.stereotype.Repository @Repository /** * Spring Data MongoDB Repository interface for [Title]. */ interface TitleRepository : ReactiveMongoRepository<Title, String>, TitleRepositoryCustom
0
Kotlin
0
2
39e6fb47ffbf5ca9867bea05b2904f69887cbc2d
397
titles-reference
MIT License
agent/src/main/kotlin/org/nessus/didcomm/service/CamelEndpointService.kt
tdiesler
578,916,709
false
null
/*- * #%L * Nessus DIDComm :: Services :: Agent * %% * Copyright (C) 2022 Nessus * %% * 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. * #L% */ package org.nessus.didcomm.agent import mu.KotlinLogging import org.apache.camel.CamelContext import org.apache.camel.Processor import org.apache.camel.builder.RouteBuilder import org.apache.camel.impl.DefaultCamelContext class NessusAgent { private val log = KotlinLogging.logger {} companion object { private val implementation = NessusAgent() fun getService() = implementation } fun startEndpoint(requestProcessor: Processor, agentPort : Int = 9030): CamelContext { log.info("Starting Nessus endpoint on: $agentPort") val camelctx: CamelContext = DefaultCamelContext() camelctx.addRoutes(object: RouteBuilder(camelctx) { override fun configure() { from("undertow:http://0.0.0.0:${agentPort}?matchOnUriPrefix=true") .log("Req: \${headers.CamelHttpMethod} \${headers.CamelHttpPath} \${body}") .process(requestProcessor) } }) camelctx.start() return camelctx } }
19
Kotlin
0
5
2680c7e2b1c1741bed55d5942707273321209ad3
1,693
nessus-didcomm
Apache License 2.0
app/src/main/java/com/ismailhakkiaydin/coinranking/ui/coin/detail/CoinDetailFragment.kt
ihaydinn
259,339,381
false
null
package com.ismailhakkiaydin.coinranking.ui.coin.detail import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import com.github.mikephil.charting.animation.Easing import com.github.mikephil.charting.components.Legend import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.BarEntry import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.ismailhakkiaydin.coinranking.R import com.ismailhakkiaydin.coinranking.base.BaseFragment import com.ismailhakkiaydin.coinranking.base.BaseVMFragment import com.ismailhakkiaydin.coinranking.databinding.FragmentCoinDetailBinding import com.ismailhakkiaydin.coinranking.model.coin.CoinResult import com.ismailhakkiaydin.coinranking.model.history.CoinHistoryResult import com.ismailhakkiaydin.coinranking.util.DateFormatter import com.ismailhakkiaydin.coinranking.util.convertFloat import kotlinx.android.synthetic.main.fragment_coin.* import kotlinx.android.synthetic.main.fragment_coin_detail.* import java.time.format.DateTimeFormatter class CoinDetailFragment : BaseFragment<FragmentCoinDetailBinding,CoinDetailViewModel>() { private var coinDetails: CoinResult.Data.Coin? = null private var isFav: Boolean? = null override fun getLayoutRes(): Int = R.layout.fragment_coin_detail override fun getViewModel(): Class<CoinDetailViewModel> = CoinDetailViewModel::class.java override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) arguments?.let { coinDetails = it?.getParcelable("coin_details") dataBinding.coinDetail = coinDetails checkFav() dataBinding.imgFavorite.setOnClickListener { favorite() } } return dataBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { var coinResult = arguments?.getParcelable<CoinResult.Data.Coin>("coin_details") viewModel.getAllCoinHisory(coinResult!!.coinId) viewModel.coinHistoryList.observe(viewLifecycleOwner, Observer { it?.let { val lineEntries = mutableListOf<Entry>() for((index, value) in it.withIndex()){ lineEntries.add(Entry(index.toFloat(), convertFloat(value.price))) } lineChart.xAxis.valueFormatter = DateFormatter(it) val lineDataSet = LineDataSet(lineEntries,"Price") lineChart.data = LineData(lineDataSet) lineDataSet.setDrawValues(false) lineDataSet.setDrawFilled(true) lineDataSet.lineWidth = 1f lineDataSet.fillColor = R.color.colorAccent lineDataSet.fillAlpha = R.color.colorChangeUp lineChart.xAxis.labelRotationAngle = 0f // lineChart.axisRight.isEnabled = false lineChart.setTouchEnabled(true) lineChart.setPinchZoom(true) lineChart.description.text = "Days" lineChart.setNoDataText("No Data Yet!") lineChart.animateX(2000, Easing.EaseInOutCirc) val markerView = CustomMarker(requireContext(), R.layout.marker_view) lineChart.marker = markerView lineChart.invalidate() } }) viewModel.loading.observe(viewLifecycleOwner, Observer { it?.let { if (it){ progressBarDetails.visibility = View.VISIBLE cardView.visibility = View.GONE lineChart.visibility = View.GONE }else{ progressBarDetails.visibility = View.GONE cardView.visibility = View.VISIBLE lineChart.visibility = View.VISIBLE } } }) } private fun favorite(){ if (isFav!!){ coinDetails?.let { viewModel.deleteCoin(it) } Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show() }else{ coinDetails?.let { viewModel.insertCoin(it) } Toast.makeText(context, "Added", Toast.LENGTH_SHORT).show() } } private fun checkFav(){ viewModel.getSingleCoin(coinDetails!!.coinId).observe(viewLifecycleOwner, Observer { if (it != null){ dataBinding.imgFavorite.setImageResource(R.drawable.ic_favorite_full) isFav = true }else{ dataBinding.imgFavorite.setImageResource(R.drawable.ic_favorite) isFav = false } }) } }
0
Kotlin
1
4
3219286a38a7840060fc78c6bb08c6b7dd241c2b
5,086
coin-ranking-app
MIT License
DiscordBot/src/main/kotlin/dev/fstudio/mc_discord_bot/diskord/command/list/ListMessage.kt
Kamillaova
463,396,605
false
{"Kotlin": 78372}
package dev.fstudio.mc_discord_bot.diskord.command.list import com.jessecorbett.diskord.api.channel.Embed import com.jessecorbett.diskord.api.channel.EmbedFooter import dev.fstudio.mc_discord_bot.allPlayersTitle import dev.fstudio.mc_discord_bot.api.mcworldstats.common.response.Player import dev.fstudio.mc_discord_bot.footerText import dev.fstudio.mc_discord_bot.utils.MicsUtil.convertToDead import dev.fstudio.mc_discord_bot.utils.MicsUtil.fixUnderline import dev.fstudio.mc_discord_bot.utils.MicsUtil.getRandomColor fun Embed.embedPlayerListMessage(data: List<Player>) { title = allPlayersTitle description = StringBuilder().apply { data.forEachIndexed { index, player -> append("**${index + 1}. **${player.name.fixUnderline().convertToDead(player.abandoned)}\n") } }.toString() color = getRandomColor() footer = EmbedFooter(footerText) }
0
Kotlin
0
1
a935ae2b1831949a347c954c70c3df6628d3dde5
892
Ellison
MIT License
cinescout/auth/trakt/domain/src/commonMain/kotlin/cinescout/auth/trakt/domain/usecase/NotifyTraktAppAuthorized.kt
4face-studi0
280,630,732
false
null
package cinescout.auth.trakt.domain.usecase import cinescout.auth.trakt.domain.TraktAuthRepository import cinescout.auth.trakt.domain.model.TraktAuthorizationCode import org.koin.core.annotation.Factory @Factory class NotifyTraktAppAuthorized( private val authRepository: TraktAuthRepository ) { suspend operator fun invoke(code: TraktAuthorizationCode) { authRepository.notifyAppAuthorized(code) } }
19
Kotlin
2
3
d64398507d60a20a445db1451bdd8be23d65c9aa
424
CineScout
Apache License 2.0
app/src/main/kotlin/sea/parser/expressions/AdditiveExpression.kt
DavidMacDonald11
585,657,942
false
{"Kotlin": 68605, "Shell": 3266, "Makefile": 254}
package sea.grammar import sea.parser.* import sea.grammar.MultiplicativeExpression class AdditiveExpression(left: Node, op: Token, right: Node) : BinaryOperation(left, op, right) { companion object : Node.CompanionObject { override fun construct(parser: Parser): Node { @Suppress("UNCHECKED_CAST") val cls = AdditiveExpression::class as BinOpClass val hasList = listOf("+", "-") return construct(parser, hasList, MultiplicativeExpression::construct, cls) } } override fun transpile(transpiler: Transpiler): TExpression { return transpiler.nodeContext(this) { val left = left.transpile(transpiler).arithmeticOp(transpiler) val right = right.transpile(transpiler).arithmeticOp(transpiler) val result = TExpression.resolveType(left, right) if(left.longValue != null && right.longValue != null) { if(op.has("+")) result.longValue = left.longValue!! + right.longValue!! else result.longValue = left.longValue!! - right.longValue!! } result.replace("$left ${op.string} $right") } } }
0
Kotlin
1
7
38a2337f0d983751642870102d0275077837e9ba
1,274
Sea-Compiler
MIT License
app/src/main/java/com/example/movieapp/core/network/api/apiTopHits.kt
NolifekNTB
751,407,208
false
{"Kotlin": 238529}
package com.example.movieapp.core.network.api import com.example.movieapp.core.network.models.shared.AnimeData import retrofit2.http.GET interface AnimeApiTopHits { @GET("top/anime") suspend fun getTopHits(): AnimeData }
0
Kotlin
0
0
8305f925e7f1a760c9a2b029cf3f5dd4f41cde2d
230
Movie-app
MIT License
src/main/kotlin/com/adamratzman/spotify/models/Playlist.kt
kptlronyttcna
206,928,095
true
{"Kotlin": 317955}
/* Spotify Web API - Kotlin Wrapper; MIT License, 2019; Original author: Adam Ratzman */ package com.adamratzman.spotify.models import com.adamratzman.spotify.SpotifyRestAction import com.adamratzman.spotify.endpoints.client.ClientPlaylistAPI import com.neovisionaries.i18n.CountryCode import com.squareup.moshi.Json /** * Simplified Playlist object that can be used to retrieve a full [Playlist] * * @property collaborative Returns true if context is not search and the owner allows other users to * modify the playlist. Otherwise returns false. * @property href A link to the Web API endpoint providing full details of the playlist. * @property id The Spotify ID for the playlist. * @property images Images for the playlist. The array may be empty or contain up to three images. * The images are returned by size in descending order. See Working with Playlists. * Note: If returned, the source URL for the image ( url ) is temporary and will expire in less than a day. * @property name The name of the playlist. * @property owner The user who owns the playlist * @property primaryColor Unknown. * @property public The playlist’s public/private status: true the playlist is public, false the * playlist is private, null the playlist status is not relevant. * @property tracks A collection containing a link ( href ) to the Web API endpoint where full details of the * playlist’s tracks can be retrieved, along with the total number of tracks in the playlist. * @property type The object type: “playlist” * @property snapshot The version identifier for the current playlist. Can be supplied in other * requests to target a specific playlist version */ data class SimplePlaylist( @Json(name = "external_urls") private val _externalUrls: Map<String, String>, @Json(name = "href") private val _href: String, @Json(name = "id") private val _id: String, @Json(name = "uri") private val _uri: String, val collaborative: Boolean, val images: List<SpotifyImage>, val name: String, val owner: SpotifyPublicUser, @Json(name = "primary_color") val primaryColor: String? = null, val public: Boolean? = null, @Json(name = "snapshot_id") private val _snapshotId: String, val tracks: PlaylistTrackInfo, val type: String ) : CoreObject(_href, _id, PlaylistURI(_uri), _externalUrls) { @Transient val snapshot: ClientPlaylistAPI.Snapshot = ClientPlaylistAPI.Snapshot(_snapshotId) /** * Converts this [SimplePlaylist] into a full [Playlist] object with the given * market * * @param market Provide this parameter if you want the list of returned items to be relevant to a particular country. */ fun toFullPlaylist(market: CountryCode? = null): SpotifyRestAction<Playlist?> = api.playlists.getPlaylist(id, market) } /** * Represents a Spotify track inside a [Playlist] * * @property primaryColor Unknown. Undocumented field * @property addedAt The date and time the track was added. Note that some very old playlists may return null in this field. * @property addedBy The Spotify user who added the track. Note that some very old playlists may return null in this field. * @property isLocal Whether this track is a local file or not. * @property track Information about the track. */ data class PlaylistTrack( @Json(name = "primary_color") val primaryColor: String? = null, @Json(name = "added_at") val addedAt: String?, @Json(name = "added_by") val addedBy: SpotifyPublicUser?, @Json(name = "is_local") val isLocal: Boolean?, val track: Track, @Json(name = "video_thumbnail") val videoThumbnail: VideoThumbnail? = null ) /** * Represents a Playlist on Spotify * * @property collaborative Returns true if context is not search and the owner allows other users to modify the playlist. * Otherwise returns false. * @property description The playlist description. Only returned for modified, verified playlists, otherwise null. * @property followers * @property href A link to the Web API endpoint providing full details of the playlist. * @property id The Spotify ID for the playlist. * @property primaryColor Unknown. * @property images Images for the playlist. The array may be empty or contain up to three images. * The images are returned by size in descending order.Note: If returned, the source URL for the * image ( url ) is temporary and will expire in less than a day. * @property name The name of the playlist. * @property owner The user who owns the playlist * @property public The playlist’s public/private status: true the playlist is public, false the playlist is private, * null the playlist status is not relevant * @property snapshot The version identifier for the current playlist. Can be supplied in other requests to target * a specific playlist version * @property tracks Information about the tracks of the playlist. * @property type The object type: “playlist” */ data class Playlist( @Json(name = "external_urls") private val _externalUrls: Map<String, String>, @Json(name = "href") private val _href: String, @Json(name = "id") private val _id: String, @Json(name = "uri") private val _uri: String, val collaborative: Boolean, val description: String, val followers: Followers, @Json(name = "primary_color") val primaryColor: String? = null, val images: List<SpotifyImage>, val name: String, val owner: SpotifyPublicUser, val public: Boolean? = null, @Json(name = "snapshot_id") private val _snapshotId: String, val tracks: PagingObject<PlaylistTrack>, val type: String ) : CoreObject(_href, _id, PlaylistURI(_uri), _externalUrls) { @Transient val snapshot: ClientPlaylistAPI.Snapshot = ClientPlaylistAPI.Snapshot(_snapshotId) } /** * A collection containing a link ( href ) to the Web API endpoint where full details of the playlist’s tracks * can be retrieved, along with the total number of tracks in the playlist. * * @property href link to the Web API endpoint where full details of the playlist’s tracks * can be retrieved * @property total the total number of tracks in the playlist. */ data class PlaylistTrackInfo( val href: String, val total: Int ) data class VideoThumbnail(val url: String?)
0
null
0
0
e239e725b438880949635d76633cc23065d5ee82
6,263
spotify-web-api-kotlin
MIT License
app/src/main/java/com/example/df8c4968a760dfc86702c40ea88faf48/MainActivity.kt
enesduhanbulut
607,634,788
false
null
package com.example.df8c4968a760dfc86702c40ea88faf48 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.df8c4968a760dfc86702c40ea88faf48.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
0
Kotlin
0
0
f4dca65fa05ed56bbaba2d0c2308e9f296aca6a1
379
df8c4968a760dfc86702c40ea88faf48
MIT License
paymentsheet/src/main/java/com/stripe/android/paymentsheet/forms/PaymentMethodRequirements.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet.forms import android.os.Parcelable import kotlinx.parcelize.Parcelize internal sealed interface Requirement : Parcelable internal sealed interface PIRequirement : Requirement internal sealed interface SIRequirement : Requirement /** * This requirement is dependent on the configuration passed by the app to the SDK. */ @Parcelize internal object Delayed : PIRequirement, SIRequirement /** * The Payment Method requires a shipping address in the Payment Intent. * The fields required are name, address line 1, country, and postal code. */ @Parcelize internal object ShippingAddress : PIRequirement @Parcelize internal data class PaymentMethodRequirements( /** * These are the requirements for using a PaymentIntent. * - Only [PIRequirement]s are allowed in this set. * - If this is null, PaymentIntents (even if SFU is set) are not supported by this LPM. */ val piRequirements: Set<PIRequirement>?, /** * These are the requirements for using a SetupIntent. * - Only [SIRequirement]s are allowed in this set. * - If this is null SetupIntents and PaymentIntents with SFU set are not * supported by this LPM. If SetupIntents are supported, but there are * no additional requirements this must be an emptySet. * - In order to make sure the PM can be used when attached to a customer it * must include the requirements of the saved payment method. For instance, * Bancontact is not delayed, but when saved it is represented as a SEPA paymnent * method which is delayed. So there must be Delay support in order to meet * the requiremetns of this PM. (There was a consideration of adding a SaveType * that in cases where SI or PIw/SFU it would also check the requirements of * the SaveType - not sure if the SaveType pi and/or si requirements should be checked). */ val siRequirements: Set<SIRequirement>?, /** * This indicates if the payment method can be confirmed when attached to a customer * and only the Payment Method id is available. * - Null means that it is not supported, or that it is attached as a different type * - false means that it is supported by the payment method, but not currently enabled * (likely because of a lack of mandate support) * - true means that a PM of this type attached to a customer can be confirmed */ val confirmPMFromCustomer: Boolean?, ) : Parcelable internal val CardRequirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = emptySet(), confirmPMFromCustomer = true ) internal val BancontactRequirement = PaymentMethodRequirements( piRequirements = emptySet(), /** * Currently we will not support this PaymentMethod for use with PI w/SFU, * or SI until there is a way of retrieving valid mandates associated with a customer PM. * * The reason we are excluding it is because after PI w/SFU set or PI * is used, the payment method appears as a SEPA payment method attached * to a customer. Without this block the SEPA payment method would * show in PaymentSheet. If the user used this save payment method * we would have no way to know if the existing mandate was valid or how * to request the user to re-accept the mandate. * * SEPA Debit does support PI w/SFU and SI (both with and without a customer), * and it is Delayed in this configuration. */ siRequirements = null, /** * This PM cannot be attached to a customer, it should be noted that it * will be attached as a SEPA Debit payment method and have the requirements * of that PaymentMethod, but for now SEPA is not supported either so we will * call it false. */ confirmPMFromCustomer = false ) internal val SofortRequirement = PaymentMethodRequirements( piRequirements = setOf(Delayed), /** * Currently we will not support this PaymentMethod for use with PI w/SFU, * or SI until there is a way of retrieving valid mandates associated with a customer PM. * * The reason we are excluding it is because after PI w/SFU set or PI * is used, the payment method appears as a SEPA payment method attached * to a customer. Without this block the SEPA payment method would * show in PaymentSheet. If the user used this save payment method * we would have no way to know if the existing mandate was valid or how * to request the user to re-accept the mandate. * * SEPA Debit does support PI w/SFU and SI (both with and without a customer), * and it is Delayed in this configuration. */ siRequirements = null, /** * This PM cannot be attached to a customer, it should be noted that it * will be attached as a SEPA Debit payment method and have the requirements * of that PaymentMethod, but for now SEPA is not supported either so we will * call it false. */ confirmPMFromCustomer = false ) internal val IdealRequirement = PaymentMethodRequirements( piRequirements = emptySet(), /** * Currently we will not support this PaymentMethod for use with PI w/SFU, * or SI until there is a way of retrieving valid mandates associated with a customer PM. * * The reason we are excluding it is because after PI w/SFU set or PI * is used, the payment method appears as a SEPA payment method attached * to a customer. Without this block the SEPA payment method would * show in PaymentSheet. If the user used this save payment method * we would have no way to know if the existing mandate was valid or how * to request the user to re-accept the mandate. * * SEPA Debit does support PI w/SFU and SI (both with and without a customer), * and it is Delayed in this configuration. */ siRequirements = null, /** * This PM cannot be attached to a customer, it should be noted that it * will be attached as a SEPA Debit payment method and have the requirements * of that PaymentMethod, but for now SEPA is not supported either so we will * call it false. */ confirmPMFromCustomer = false ) internal val SepaDebitRequirement = PaymentMethodRequirements( piRequirements = setOf(Delayed), /** * Currently we will not support this PaymentMethod for use with PI w/SFU, * or SI until there is a way of retrieving valid mandates associated with a customer PM. * * The reason we are excluding it is because after PI w/SFU set or PI * is used, the payment method appears as a SEPA payment method attached * to a customer. Without this block the SEPA payment method would * show in PaymentSheet. If the user used this save payment method * we would have no way to know if the existing mandate was valid or how * to request the user to re-accept the mandate. * * SEPA Debit does support PI w/SFU and SI (both with and without a customer), * and it is Delayed in this configuration. */ siRequirements = null, /** * This PM is blocked for use from a customer PM. Once it is possible to retrieve a * mandate from a customer PM for use on confirm the SDK will be able to support this * scenario. * * Here we explain the details * - if PI w/SFU set or SI with a customer, or * - if PI w/SFU set or SI with/out a customer and later attached when used with * a webhook * (Note: from the client there is no way to detect if a PI or SI is associated with a customer) * * then, this payment method would be attached to the customer as a SEPA payment method. * (Note: Bancontact, iDEAL, and Sofort require authentication, but SEPA does not. * also Bancontact, iDEAL are not delayed, but Sofort and SEPA are delayed.) * * The SEPA payment method requires a mandate when confirmed. Currently there is no * way with just a client_secret and public key to get a valid mandate associated with * a customers payment method that can be used on confirmation. * * Even with mandate support, in order to make sure that any payment method added can * also be used when attached to a customer, this LPM will require * [PaymentSheet.Configuration].allowsDelayedPaymentMethods support as indicated in * the configuration. */ confirmPMFromCustomer = false ) internal val EpsRequirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = null, // this is not supported by this payment method confirmPMFromCustomer = null ) internal val P24Requirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = null, // this is not supported by this payment method /** * This cannot be saved to a customer object. */ confirmPMFromCustomer = null ) internal val GiropayRequirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = null, // this is not supported by this payment method confirmPMFromCustomer = null ) /** * This defines the requirements for usage as a Payment Method. */ internal val AfterpayClearpayRequirement = PaymentMethodRequirements( piRequirements = setOf(ShippingAddress), /** * SetupIntents are not supported by this payment method, in addition, * setup intents do not have shipping information */ siRequirements = null, confirmPMFromCustomer = null ) /** * This defines the requirements for usage as a Payment Method. */ internal val KlarnaRequirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = null, confirmPMFromCustomer = null ) /** * This defines the requirements for usage as a Payment Method. */ internal val PaypalRequirement = PaymentMethodRequirements( piRequirements = emptySet(), /** * SetupIntents are not supported by this payment method. Currently, for paypal (and others see * oof #5) customers are not able to set up saved payment methods for reuse. The API errors if * confirming PI+SFU or SI with these methods. */ siRequirements = null, confirmPMFromCustomer = null ) /** * This defines the requirements for usage as a Payment Method. */ internal val AffirmRequirement = PaymentMethodRequirements( piRequirements = setOf(ShippingAddress), siRequirements = null, confirmPMFromCustomer = null ) /** * This defines the requirements for usage as a Payment Method. */ internal val AuBecsDebitRequirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = emptySet(), confirmPMFromCustomer = null )
92
null
606
935
bec4fc5f45b5401a98a310f7ebe5d383693936ea
10,772
stripe-android
MIT License
app/src/main/java/edu/nitt/delta/orientation22/compose/screens/LeaderBoardScreen.kt
delta
549,654,697
false
null
package edu.nitt.delta.orientation22.compose.screens import android.util.Log import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import edu.nitt.delta.orientation22.models.leaderboard.LeaderboardData import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import edu.nitt.delta.orientation22.R import edu.nitt.delta.orientation22.compose.CustomItem import edu.nitt.delta.orientation22.compose.MarqueeText import edu.nitt.delta.orientation22.compose.avatarList import edu.nitt.delta.orientation22.models.Person import edu.nitt.delta.orientation22.ui.theme.* @Composable fun LeaderBoardScreen( modifier: Modifier = Modifier, leaderBoardData: List<LeaderboardData>, painter: Painter,contentDescription: String ){ val fontFamily= FontFamily( Font(R.font.montserrat_regular) ) val configuration= LocalConfiguration.current val screenHeight=configuration.screenHeightDp val screenWidth=configuration.screenWidthDp Box(modifier.fillMaxSize()) { Image(painter = painter, contentDescription = contentDescription,modifier=Modifier.fillMaxSize(), contentScale = ContentScale.Crop) Column(modifier = Modifier .fillMaxSize() .background( color = background, ), horizontalAlignment = Alignment.CenterHorizontally) { Text(text = "LEADERBOARD", style = TextStyle(fontSize = 32.sp, fontFamily = fontFamily,fontWeight = FontWeight(400), color = colour_Leaderboard, shadow = Shadow(color = shadow2,offset= Offset(0f,12f), blurRadius = 3f ) ), modifier=Modifier.padding(top=(screenHeight/20).dp, bottom = 20.dp)) Spacer(modifier=Modifier.height((screenHeight/70).dp)) Text(text = "AR HUNT",fontSize = 32.sp, fontFamily = fontFamily,fontWeight = FontWeight(400), color = colour_AR_Hunt) Spacer(modifier=Modifier.height((screenHeight/80).dp)) Box( modifier = Modifier .fillMaxWidth(0.85f) .height((0.5).dp) .background( color = Color.White ) ) Spacer(modifier=Modifier.height((screenHeight/70).dp)) Row( modifier = modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, ) { when (leaderBoardData.size) { 1 -> { Log.d("HI", avatarList[leaderBoardData[0].avatar].toString()) First(name = leaderBoardData[0].teamName, avatar = avatarList[leaderBoardData[0].avatar]?: avatarList[1]!! ) } 2 -> { Second(name = leaderBoardData[1].teamName, screenHeight = screenHeight, avatar = avatarList[leaderBoardData[1].avatar]?: avatarList[1]!!) First(name = leaderBoardData[0].teamName, avatar = avatarList[leaderBoardData[0].avatar]?: avatarList[1]!!) Box(modifier = Modifier.fillMaxWidth(0.5f)) } else -> { Second(name = leaderBoardData[1].teamName, screenHeight = screenHeight, avatar = avatarList[leaderBoardData[1].avatar]?: avatarList[1]!!) First(name = leaderBoardData[0].teamName, avatar = avatarList[leaderBoardData[0].avatar]?: avatarList[1]!!) Third(name = leaderBoardData[2].teamName, screenHeight = screenHeight, avatar = avatarList[leaderBoardData[2].avatar]?: avatarList[1]!!) } } } Spacer(modifier=Modifier.height((screenHeight/45).dp)) LazyColumn(contentPadding = PaddingValues(start = (screenWidth/10).dp, end =(screenWidth/10).dp, bottom = 4.dp ), verticalArrangement = Arrangement.spacedBy((screenHeight/27).dp), modifier = Modifier .fillMaxHeight() .padding(bottom = (screenWidth / 3.5).dp)){ itemsIndexed(items=leaderBoardData){index,person-> CustomItem(person = Person(position = index+1, name = person.teamName, points = person.score, avatar = avatarList[leaderBoardData[index].avatar]?: avatarList[1]!!)) } } } } } @Preview(showBackground = true) @Composable fun LeaderBoardScreenPreview() { // LeaderBoardScreen(Modifier,painterResource(id = R.drawable.background_image),"LeaderBoard") } @Composable fun First(name: String, avatar: Int) { Column( horizontalAlignment = Alignment.CenterHorizontally, ) { AvatarBig(avatar) Box ( modifier = Modifier.fillMaxWidth(0.3f) ) { MarqueeText( text = name, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth(), color = Color.White, fontWeight = FontWeight(400) ) } } } @Composable fun Second(name: String, screenHeight: Int, avatar: Int) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(top = (screenHeight / 15).dp) ) { AvatarSmall(avatar, R.drawable.second_place, color = white) Box( modifier = Modifier.fillMaxWidth(0.25f) ) { MarqueeText( text = name, textAlign = TextAlign.Center, color = Color.White, fontWeight = FontWeight(400) ) } } } @Composable fun Third(name: String, screenHeight: Int, avatar: Int) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(top = (screenHeight / 15).dp) ) { AvatarSmall(avatar, R.drawable.third_place, color = orange) Box( modifier = Modifier.fillMaxWidth(0.25f) ) { MarqueeText( text = name, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth(), color = Color.White, fontWeight = FontWeight(400) ) } } } @Composable fun AvatarSmall ( avatar_id: Int, position_id: Int, color: Color, ){ val configuration= LocalConfiguration.current val screenWidth=configuration.screenWidthDp Box( modifier = Modifier.size(height = (screenWidth/3.8).dp, width = ((screenWidth/4.5)).dp) ){ Box( modifier = Modifier.padding(bottom = (screenWidth/20).dp) ) { AvatarImage( image_id = avatar_id, color = color, size_value = (screenWidth / 4.5) ) } Image(painter = painterResource(id = position_id), contentDescription ="Second place profile", modifier= Modifier .size((screenWidth / 10).dp) .align(Alignment.BottomCenter) , contentScale = ContentScale.Fit,) } } @Composable fun AvatarBig ( avatar_id: Int, ){ val configuration= LocalConfiguration.current val screenWidth=configuration.screenWidthDp Box( modifier = Modifier.size(height = (screenWidth/2.1).dp, width = ((screenWidth/3.5)).dp) ){ Box( modifier = Modifier.padding(bottom = (screenWidth/20).dp, top = (screenWidth/6.5).dp) ) { AvatarImage( image_id = avatar_id, color = lightYellow, size_value = (screenWidth / 3.5) ) } Image(painter = painterResource(id = R.drawable.crown), contentDescription ="crown", modifier= Modifier .size((screenWidth / 5).dp) .align(Alignment.TopCenter) , contentScale = ContentScale.Fit) Image(painter = painterResource(id = R.drawable.first_place), contentDescription ="Second place profile", modifier= Modifier .size((screenWidth / 10).dp) .align(Alignment.BottomCenter) , contentScale = ContentScale.Fit,) } } @Composable fun AvatarImage(image_id:Int, color: Color,size_value:Double, ){ Image(painter = painterResource(id = image_id), contentDescription ="Avatar with border", modifier= Modifier .size(size_value.dp) .clip(CircleShape) .border(4.dp, color, CircleShape) , contentScale = ContentScale.Fit) }
0
Kotlin
0
0
73352a78e852f4eaf490f9ec3da0797b87fbb2d2
9,513
orientation-android-22
MIT License
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/CheckboxTreeFixture.kt
rikinpatoliya
137,878,248
true
null
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.fixtures import com.intellij.testGuiFramework.driver.CheckboxTreeDriver import com.intellij.testGuiFramework.fixtures.extended.ExtendedTreeFixture import com.intellij.ui.CheckboxTree import org.fest.swing.core.Robot class CheckboxTreeFixture(robot: Robot, checkboxTree: CheckboxTree) : ExtendedTreeFixture(robot, checkboxTree) { init { this.replaceDriverWith(CheckboxTreeDriver(robot)) } fun clickCheckbox(vararg pathStrings: String) { (this.driver() as CheckboxTreeDriver).clickCheckbox(target() as CheckboxTree, pathStrings.toList()) } fun getCheckboxComponent(vararg pathStrings: String) = (this.driver() as CheckboxTreeDriver).getCheckboxComponent( target() as CheckboxTree, pathStrings.toList()) fun setCheckboxValue(value: Boolean, vararg pathStrings: String) { val checkbox = getCheckboxComponent(*pathStrings) println("setCheckboxValue for ${pathStrings.joinToString()}: state = ${checkbox?.isSelected}") if (checkbox != null && checkbox.isSelected != value) { clickCheckbox(*pathStrings) } } /** * Sometimes one click doesn't work - e.g. it can be swallowed by scrolling * Then the second click must help. * */ fun ensureCheckboxValue(value: Boolean, vararg pathString: String){ setCheckboxValue(value, *pathString) setCheckboxValue(value, *pathString) } fun check(vararg pathStrings: String) = ensureCheckboxValue(true, *pathStrings) fun uncheck(vararg pathStrings: String) = ensureCheckboxValue(false, *pathStrings) }
0
null
0
0
c42be18fd98d48d860f1f8452d9a763510705414
2,151
intellij-community
Apache License 2.0
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExternalSettingsImporter.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.project import com.intellij.execution.BeforeRunTask import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.model.project.settings.ConfigurationData import com.intellij.openapi.externalSystem.service.execution.ExternalSystemBeforeRunTask import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl import com.intellij.openapi.externalSystem.service.project.manage.ExternalSystemTaskActivator import com.intellij.openapi.externalSystem.service.project.settings.BeforeRunTaskImporter import com.intellij.openapi.externalSystem.service.project.settings.ConfigurationHandler import com.intellij.openapi.project.Project import com.intellij.util.ObjectUtils.consumeIfCast import org.jetbrains.plugins.gradle.execution.GradleBeforeRunTaskProvider import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.settings.TestRunner.* import org.jetbrains.plugins.gradle.util.GradleConstants class GradleBeforeRunTaskImporter: BeforeRunTaskImporter { override fun process(project: Project, modelsProvider: IdeModifiableModelsProvider, runConfiguration: RunConfiguration, beforeRunTasks: MutableList<BeforeRunTask<*>>, cfg: MutableMap<String, Any>): MutableList<BeforeRunTask<*>> { val taskProvider = BeforeRunTaskProvider.getProvider(project, GradleBeforeRunTaskProvider.ID) ?: return beforeRunTasks val task = taskProvider.createTask(runConfiguration) ?: return beforeRunTasks task.taskExecutionSettings.apply { consumeIfCast(cfg["taskName"], String::class.java) { taskNames = listOf(it) } consumeIfCast(cfg["projectPath"], String::class.java) { externalProjectPath = it } } task.isEnabled = true val taskExists = beforeRunTasks.filterIsInstance<ExternalSystemBeforeRunTask>() .any { it.taskExecutionSettings.taskNames == task.taskExecutionSettings.taskNames && it.taskExecutionSettings.externalProjectPath == task.taskExecutionSettings.externalProjectPath } if (!taskExists) { beforeRunTasks.add(task) } return beforeRunTasks } override fun canImport(typeName: String): Boolean = "gradleTask" == typeName } class GradleTaskTriggersImporter : ConfigurationHandler { override fun apply(project: Project, modelsProvider: IdeModifiableModelsProvider, configuration: ConfigurationData) { val obj = configuration.find("taskTriggers") as? Map<*, *> ?: return val taskTriggerConfig = obj as Map<String, Collection<*>> val activator = ExternalProjectsManagerImpl.getInstance(project).taskActivator taskTriggerConfig.forEach { phaseName, tasks -> val phase = PHASE_MAP[phaseName] ?: return@forEach (tasks as Collection<Map<*, *>>).forEach { taskInfo -> val projectPath = taskInfo["projectPath"] val taskPath = taskInfo["taskPath"] if (projectPath is String && taskPath is String) { val newEntry = ExternalSystemTaskActivator.TaskActivationEntry(GradleConstants.SYSTEM_ID, phase, projectPath, taskPath) activator.removeTask(newEntry) activator.addTask(newEntry) } } } } companion object { private val PHASE_MAP = mapOf("beforeSync" to ExternalSystemTaskActivator.Phase.BEFORE_SYNC, "afterSync" to ExternalSystemTaskActivator.Phase.AFTER_SYNC, "beforeBuild" to ExternalSystemTaskActivator.Phase.BEFORE_COMPILE, "afterBuild" to ExternalSystemTaskActivator.Phase.AFTER_COMPILE, "beforeRebuild" to ExternalSystemTaskActivator.Phase.BEFORE_REBUILD, "afterRebuild" to ExternalSystemTaskActivator.Phase.AFTER_REBUILD) } } class ActionDelegateConfigImporter: ConfigurationHandler { override fun apply(project: Project, projectData: ProjectData?, modelsProvider: IdeModifiableModelsProvider, configuration: ConfigurationData) { val config = configuration.find("delegateActions") as? Map<String, *> ?: return val projectPath = projectData?.linkedExternalProjectPath ?: return val projectSettings = GradleSettings.getInstance(project).getLinkedProjectSettings(projectPath) ?: return consumeIfCast(config["delegateBuildRunToGradle"], java.lang.Boolean::class.java) { projectSettings.delegatedBuild = it.booleanValue() } consumeIfCast(config["testRunner"], String::class.java) { projectSettings.testRunner = (TEST_RUNNER_MAP[it] ?: return@consumeIfCast) } } companion object { private val TEST_RUNNER_MAP = mapOf( "PLATFORM" to PLATFORM, "GRADLE" to GRADLE, "CHOOSE_PER_TEST" to CHOOSE_PER_TEST ) } }
284
null
5162
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
5,553
intellij-community
Apache License 2.0
coredomain/src/main/java/com/jbr/coredomain/artistdetails/ArtistDetailsLoader.kt
jrmybrault
210,299,381
false
null
package com.jbr.coredomain.artistdetails import androidx.lifecycle.LiveData interface ArtistDetailsLoader { val artist: LiveData<DetailedArtist> suspend fun loadArtist(identifier: String) }
0
Kotlin
0
0
ad06f792538867a732bd79fae74849f5130addce
202
aSharp-library
MIT License
src/main/java/com/oveln/ovbookannouncements/listener/onPlayerChat.kt
Oveln
389,541,767
false
null
package com.oveln.ovbookannouncements.listener import com.oveln.ovbookannouncements.data.Lang import com.oveln.ovbookannouncements.data.verifier import com.oveln.ovbookannouncements.utils.CharUtils.colorful import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.AsyncPlayerChatEvent class onPlayerChat :Listener { @EventHandler fun onListener(event: AsyncPlayerChatEvent):Boolean { if (verifier.code.containsKey(event.player.uniqueId)) { event.isCancelled = true if (event.message == verifier.code[event.player.uniqueId]) { verifier.code.remove(event.player.uniqueId) verifier.verified.add(event.player.uniqueId) event.player.sendMessage(Lang.lang.getString("SuccessMessage").colorful()) } else { event.player.sendMessage(Lang.lang.getString("FailureMessage").colorful()) } } return true } }
0
Kotlin
0
0
930a3d38a2fa5d6dfd7a6d7d11ce45570cc43a27
987
OvBookAnnouncements
Apache License 2.0
app/src/main/kotlin/com/sanmer/geomag/model/data/Record.kt
SanmerApps
583,580,288
false
{"Kotlin": 257095}
package com.sanmer.geomag.model.data import com.sanmer.geomag.GeomagExt data class Record( val model: GeomagExt.Models, val time: DateTime, val position: Position, val values: MagneticFieldExt ) { companion object { fun empty() = Record( model = GeomagExt.Models.IGRF, time = DateTime.now(), position = Position.empty(), values = MagneticFieldExt.empty() ) } }
1
Kotlin
2
25
60f4b7eaacf0d72545f6bb9046352ffb76ac4c3a
451
Geomag
Apache License 2.0
brain/src/main/kotlin/fr/sdis64/brain/indicators/IndicatorController.kt
ArchangelX360
705,188,698
false
{"Kotlin": 1253257, "JavaScript": 1614, "Dockerfile": 1112, "HTML": 496}
package fr.sdis64.brain.indicators import fr.sdis64.api.indicators.ManualIndicatorCategory import fr.sdis64.api.indicators.ManualIndicatorLevel import fr.sdis64.api.indicators.ManualIndicatorType import fr.sdis64.api.indicators.WeatherIndicator import fr.sdis64.brain.utilities.entities.withIdOf import fr.sdis64.brain.utilities.mapToSet import fr.sdis64.brain.utilities.orNotFound import fr.sdis64.brain.utilities.toDTO import fr.sdis64.brain.utilities.toEntity import jakarta.validation.Valid import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import fr.sdis64.api.indicators.GriffonIndicator as GriffonIndicatorDto @RestController @RequestMapping("/indicators/weather") class WeatherIndicatorController( @Autowired private val weatherService: WeatherService, ) { @GetMapping suspend fun getWeatherIndicators(): Set<WeatherIndicator> = weatherService.getIndicators() } @RestController @RequestMapping("/indicators/griffon") class GriffonIndicatorController( @Autowired private val griffonService: GriffonService, ) { @GetMapping suspend fun getGriffonIndicator(): GriffonIndicatorDto = griffonService.getGriffonIndicator().toDTO() } @RestController @RequestMapping("/indicators/manual/levels") class ManualIndicatorLevelController( @Autowired private val levelRepository: ManualIndicatorLevelRepository, @Autowired private val categoryRepository: ManualIndicatorCategoryRepository, ) { @GetMapping fun findAllLevels( @RequestParam(required = false) active: Boolean?, @RequestParam(required = false) type: ManualIndicatorType?, ): Set<ManualIndicatorLevel> { val entities = when (type) { null -> when (active) { null -> levelRepository.findAll() else -> levelRepository.findAllByActive(active) } else -> when (active) { null -> levelRepository.findAllByCategoryType(type) else -> levelRepository.findAllByActiveAndCategoryType(active, type) } } return entities.mapToSet { it.toDTO() } } @GetMapping(value = ["/{id}"]) fun findLevel(@PathVariable(value = "id") id: Long): ManualIndicatorLevel = levelRepository.findById(id).map { it.toDTO() }.orNotFound() @PostMapping fun saveLevel(@Valid @RequestBody manualIndicatorLevel: ManualIndicatorLevel): ManualIndicatorLevel { val manualIndicatorLevel1 = manualIndicatorLevel.toEntity() val manualIndicatorCategoryWithId = categoryRepository.save(manualIndicatorLevel1.category) return levelRepository.save( manualIndicatorLevel1 .copy(category = manualIndicatorCategoryWithId) .withIdOf(manualIndicatorLevel1) ).toDTO() } @DeleteMapping(value = ["/{id}"]) fun deleteLevel(@PathVariable id: Long): ResponseEntity<Unit> { levelRepository.deleteById(id) return ResponseEntity.noContent().build() } } @RestController @RequestMapping("/indicators/manual/categories") class ManualIndicatorCategoryController( @Autowired private val categoryRepository: ManualIndicatorCategoryRepository, ) { @GetMapping(value = ["/{id}"]) fun findCategory(@PathVariable id: Long): ManualIndicatorCategory = categoryRepository.findById(id).map { it.toDTO() }.orNotFound() @PostMapping fun saveCategory(@Valid @RequestBody manualIndicatorCategory: ManualIndicatorCategory): ManualIndicatorCategory = categoryRepository.save(manualIndicatorCategory.toEntity()).toDTO() @DeleteMapping(value = ["/{id}"]) fun deleteCategory(@PathVariable id: Long): ResponseEntity<Unit> { categoryRepository.deleteById(id) return ResponseEntity.noContent().build() } @GetMapping fun findAllCategories(): Set<ManualIndicatorCategory> = categoryRepository.findAll().mapToSet { it.toDTO() } }
3
Kotlin
0
1
9fe4205152eeab21c421b299b64cfcded900ac1f
4,030
sdis64-ctac
MIT License
src/main/kotlin/com/jakewharton/uispy/ui.kt
JakeWharton
470,313,483
false
{"Kotlin": 25064, "Dockerfile": 1742}
package com.jakewharton.uispy import kotlinx.serialization.Serializable @Serializable data class ProductsContainer( val products: List<Product>, ) @Serializable data class Product( val id: Long, val handle: String, val title: String, val variants: List<Variant> = emptyList(), ) { @Serializable data class Variant( val id: Long, val title: String, val available: Boolean = false, ) }
5
Kotlin
3
43
dd43ef3a3f957eefbd12348dfdc2cd00112aa207
401
ui-spy
Apache License 2.0
notification/src/main/java/com/prmto/notification/Notifier.kt
tolgaprm
541,709,201
false
{"Kotlin": 540597}
package com.prmto.mova_movieapp.notification import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build import androidx.annotation.RequiresApi abstract class Notifier( private val notificationManager: NotificationManager ) { abstract val notificationChannelId: String abstract val notificationChannelName: String abstract val notificationId: Int fun showNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = createNotificationChannel() notificationManager.createNotificationChannel(channel) } val notification = buildNotification() notificationManager.notify( notificationId, notification ) } @RequiresApi(Build.VERSION_CODES.O) open fun createNotificationChannel( importance: Int = NotificationManager.IMPORTANCE_DEFAULT ): NotificationChannel { return NotificationChannel( notificationChannelId, notificationChannelName, importance ) } abstract fun buildNotification(): Notification protected abstract fun getNotificationTitle(): String protected abstract fun getNotificationMessage(): String }
0
Kotlin
4
85
d9365e5339cb5daa231a8fe77c7376ab828d289b
1,322
Mova-MovieApp
Apache License 2.0
src/main/kotlin/no/nav/reka/river/model/Data.kt
alpet
657,993,647
false
{"Kotlin": 227850}
package no.nav.reka.river.model import com.fasterxml.jackson.databind.JsonNode import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.RapidsConnection import no.nav.helse.rapids_rivers.River import no.nav.reka.river.* import no.nav.reka.river.InternalBehov import no.nav.reka.river.InternalEvent class Data(val event: MessageType.Event, private val jsonMessage: JsonMessage) : Message,TxMessage { init { packetValidator.validate(jsonMessage) jsonMessage.demandValue(Key.EVENT_NAME.str(),event.value) } companion object { val packetValidator = River.PacketValidation { it.demandKey(Key.EVENT_NAME.str()) it.rejectKey(Key.BEHOV.str()) it.demandKey(Key.DATA.str()) it.rejectKey(Key.FAIL.str()) it.interestedIn(Key.UUID.str()) } fun create(event: MessageType.Event, map: Map<IDataFelt, Any> = emptyMap() ) : Data { return Data(event, JsonMessage.newMessage(event.value, mapOf(Key.DATA.str() to "") + map.mapKeys { it.key.str })) } fun create(jsonMessage: JsonMessage) : Data { return Data(InternalEvent(jsonMessage[Key.EVENT_NAME.str()].asText()), jsonMessage) } } fun createBehov(behov: MessageType.Behov,map: Map<IDataFelt, Any>): Behov { return Behov(event, behov, JsonMessage.newMessage(event.value,mapOf(Key.BEHOV.str() to behov.value) + mapOfNotNull(Key.UUID.str() to uuid()) + map.mapKeys { it.key.str })) } override operator fun get(key: IKey): JsonNode = jsonMessage[key.str] override operator fun set(key: IKey, value: Any) { jsonMessage[key.str] = value } override fun uuid() = jsonMessage[Key.UUID.str()].asText() override fun toJsonMessage(): JsonMessage { return jsonMessage } }
0
Kotlin
0
0
10b272d9b0b96fac21aaba4cb7c9a18dd9f497ba
1,835
reka
MIT License
DrawsTreeFocus/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* // ktlint-disable no-wildcard-imports import javax.swing.* // ktlint-disable no-wildcard-imports private var fbaCheck: JCheckBox? = null private var dfiCheck: JCheckBox? = null fun makeUI(): Component { val tree = JTree() fbaCheck = JCheckBox(TreeDraws.DRAWS_FOCUS_BORDER_AROUND_ICON.toString()).also { it.isSelected = UIManager.getBoolean(TreeDraws.DRAWS_FOCUS_BORDER_AROUND_ICON.toString()) it.addActionListener { e -> val b = (e.source as? JCheckBox)?.isSelected == true UIManager.put(TreeDraws.DRAWS_FOCUS_BORDER_AROUND_ICON.toString(), b) SwingUtilities.updateComponentTreeUI(tree) } } dfiCheck = JCheckBox(TreeDraws.DRAW_DASHED_FOCUS_INDICATOR.toString()).also { it.isSelected = UIManager.getBoolean(TreeDraws.DRAW_DASHED_FOCUS_INDICATOR.toString()) it.addActionListener { e -> val b = (e.source as? JCheckBox)?.isSelected == true UIManager.put(TreeDraws.DRAW_DASHED_FOCUS_INDICATOR.toString(), b) SwingUtilities.updateComponentTreeUI(tree) } } val np = JPanel(GridLayout(2, 1)) np.add(fbaCheck) np.add(dfiCheck) val mb = JMenuBar() mb.add(LookAndFeelUtil.createLookAndFeelMenu()) EventQueue.invokeLater { np.rootPane.jMenuBar = mb } val p = object : JPanel(BorderLayout()) { override fun updateUI() { super.updateUI() fbaCheck?.isSelected = UIManager.getBoolean(TreeDraws.DRAWS_FOCUS_BORDER_AROUND_ICON.toString()) dfiCheck?.isSelected = UIManager.getBoolean(TreeDraws.DRAW_DASHED_FOCUS_INDICATOR.toString()) } } p.add(np, BorderLayout.NORTH) p.add(JScrollPane(tree)) p.preferredSize = Dimension(320, 240) return p } private enum class TreeDraws(private val key: String) { DRAWS_FOCUS_BORDER_AROUND_ICON("Tree.drawsFocusBorderAroundIcon"), DRAW_DASHED_FOCUS_INDICATOR("Tree.drawDashedFocusIndicator"); override fun toString() = key } private object LookAndFeelUtil { private var lookAndFeel = UIManager.getLookAndFeel().javaClass.name fun createLookAndFeelMenu() = JMenu("LookAndFeel").also { val lafRadioGroup = ButtonGroup() for (lafInfo in UIManager.getInstalledLookAndFeels()) { it.add(createLookAndFeelItem(lafInfo.name, lafInfo.className, lafRadioGroup)) } } private fun createLookAndFeelItem( lafName: String, lafClassName: String, lafGroup: ButtonGroup ): JMenuItem { val lafItem = JRadioButtonMenuItem(lafName, lafClassName == lookAndFeel) lafItem.actionCommand = lafClassName lafItem.hideActionText = true lafItem.addActionListener { e -> val m = lafGroup.selection runCatching { setLookAndFeel(m.actionCommand) }.onFailure { UIManager.getLookAndFeel().provideErrorFeedback(e.source as? Component) } } lafGroup.add(lafItem) return lafItem } @Throws( ClassNotFoundException::class, InstantiationException::class, IllegalAccessException::class, UnsupportedLookAndFeelException::class ) private fun setLookAndFeel(lookAndFeel: String) { val oldLookAndFeel = LookAndFeelUtil.lookAndFeel if (oldLookAndFeel != lookAndFeel) { UIManager.setLookAndFeel(lookAndFeel) LookAndFeelUtil.lookAndFeel = lookAndFeel updateLookAndFeel() } } private fun updateLookAndFeel() { for (window in Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window) } } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
null
3
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
3,840
kotlin-swing-tips
MIT License
solar/src/main/java/com/chiksmedina/solar/outline/arrowsaction/SquareTopUp.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.outline.arrowsaction 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.chiksmedina.solar.outline.ArrowsActionGroup val ArrowsActionGroup.SquareTopUp: ImageVector get() { if (_squareTopUp != null) { return _squareTopUp!! } _squareTopUp = Builder( name = "SquareTopUp", 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(12.0f, 1.25f) horizontalLineTo(11.9426f) curveTo(9.6342f, 1.25f, 7.8252f, 1.25f, 6.4137f, 1.4397f) curveTo(4.969f, 1.634f, 3.8289f, 2.0393f, 2.9341f, 2.9341f) curveTo(2.0393f, 3.8289f, 1.634f, 4.969f, 1.4397f, 6.4137f) curveTo(1.25f, 7.8252f, 1.25f, 9.6342f, 1.25f, 11.9426f) verticalLineTo(12.0574f) curveTo(1.25f, 14.3658f, 1.25f, 16.1748f, 1.4397f, 17.5863f) curveTo(1.634f, 19.031f, 2.0393f, 20.1711f, 2.9341f, 21.0659f) curveTo(3.8289f, 21.9607f, 4.969f, 22.366f, 6.4137f, 22.5603f) curveTo(7.8252f, 22.75f, 9.6342f, 22.75f, 11.9426f, 22.75f) horizontalLineTo(12.0574f) curveTo(14.3658f, 22.75f, 16.1748f, 22.75f, 17.5863f, 22.5603f) curveTo(19.031f, 22.366f, 20.1711f, 21.9607f, 21.0659f, 21.0659f) curveTo(21.9607f, 20.1711f, 22.366f, 19.031f, 22.5603f, 17.5863f) curveTo(22.75f, 16.1748f, 22.75f, 14.3658f, 22.75f, 12.0574f) verticalLineTo(12.0f) curveTo(22.75f, 11.5858f, 22.4142f, 11.25f, 22.0f, 11.25f) curveTo(21.5858f, 11.25f, 21.25f, 11.5858f, 21.25f, 12.0f) curveTo(21.25f, 14.3782f, 21.2484f, 16.0864f, 21.0736f, 17.3864f) curveTo(20.9018f, 18.6648f, 20.5749f, 19.4355f, 20.0052f, 20.0052f) curveTo(19.4355f, 20.5749f, 18.6648f, 20.9018f, 17.3864f, 21.0736f) curveTo(16.0864f, 21.2484f, 14.3782f, 21.25f, 12.0f, 21.25f) curveTo(9.6218f, 21.25f, 7.9136f, 21.2484f, 6.6136f, 21.0736f) curveTo(5.3352f, 20.9018f, 4.5644f, 20.5749f, 3.9948f, 20.0052f) curveTo(3.4251f, 19.4355f, 3.0982f, 18.6648f, 2.9264f, 17.3864f) curveTo(2.7516f, 16.0864f, 2.75f, 14.3782f, 2.75f, 12.0f) curveTo(2.75f, 9.6218f, 2.7516f, 7.9136f, 2.9264f, 6.6136f) curveTo(3.0982f, 5.3352f, 3.4251f, 4.5644f, 3.9948f, 3.9948f) curveTo(4.5644f, 3.4251f, 5.3352f, 3.0982f, 6.6136f, 2.9264f) curveTo(7.9136f, 2.7516f, 9.6218f, 2.75f, 12.0f, 2.75f) curveTo(12.4142f, 2.75f, 12.75f, 2.4142f, 12.75f, 2.0f) curveTo(12.75f, 1.5858f, 12.4142f, 1.25f, 12.0f, 1.25f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(21.5303f, 3.5303f) curveTo(21.8232f, 3.2374f, 21.8232f, 2.7626f, 21.5303f, 2.4697f) curveTo(21.2374f, 2.1768f, 20.7626f, 2.1768f, 20.4697f, 2.4697f) lineTo(12.75f, 10.1893f) verticalLineTo(6.6563f) curveTo(12.75f, 6.242f, 12.4142f, 5.9063f, 12.0f, 5.9063f) curveTo(11.5858f, 5.9063f, 11.25f, 6.242f, 11.25f, 6.6563f) verticalLineTo(12.0f) curveTo(11.25f, 12.4142f, 11.5858f, 12.75f, 12.0f, 12.75f) horizontalLineTo(17.3438f) curveTo(17.758f, 12.75f, 18.0938f, 12.4142f, 18.0938f, 12.0f) curveTo(18.0938f, 11.5858f, 17.758f, 11.25f, 17.3438f, 11.25f) horizontalLineTo(13.8107f) lineTo(21.5303f, 3.5303f) close() } } .build() return _squareTopUp!! } private var _squareTopUp: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
4,821
SolarIconSetAndroid
MIT License
app/src/main/java/com/example/fitness_app/profile/FragmentHome.kt
HauntedMilkshake
698,074,119
false
{"Kotlin": 18759}
package com.example.fitness_app.profile import android.os.Bundle import android.util.Log import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.fitness_app.R import com.example.fitness_app.databinding.FragmentHomeBinding import com.example.fitness_app.showBottomNav import com.google.android.material.appbar.AppBarLayout class FragmentHome : Fragment() { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private var allowBackPressed: Boolean = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requireActivity().showBottomNav() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) findNavController().popBackStack(findNavController().currentDestination!!.id, false) //TODO fix it so we can actually pop the backstack once we are logged // binding.apply { // topBar.apply { // addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener() { _, verticalOffset -> // profileText.setTextSize(TypedValue.COMPLEX_UNIT_SP, resources.getDimension(R.dimen.original_text_size) + ( (resources.getDimension(R.dimen.enlarged_text_size) - resources.getDimension(R.dimen.original_text_size) ) * -verticalOffset / totalScrollRange.toFloat())) // elevation = if(verticalOffset == 0){ // 4f // }else{ // 0f // } // }) // } // } // requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback) } override fun onResume() { super.onResume() allowBackPressed = true } }
0
Kotlin
0
1
d6b4b437f082996fccf971ad4d9992ea67739a07
2,270
fitness_app
MIT License
core/src/commonMain/kotlin/it/krzeminski/fsynth/synthesis/caching/bucketing/BucketedTrack.kt
fsynthlib
136,238,161
false
null
package it.krzeminski.fsynth.synthesis.caching.bucketing import it.krzeminski.fsynth.types.PositionedBoundedWaveform data class BucketedTrack( /** * 0th element of this list contains track segments that exist in the song in the time range * [0 s; [bucketSizeInSeconds]), 1st element: [[bucketSizeInSeconds], 2*[bucketSizeInSeconds]), and so on. * * In order for this bucketing strategy to make sense, this list must have random access in O(1), e.g. be an * [ArrayList]. [List] is used here only to improve immutability ([ArrayList] is mutable). */ val buckets: List<TrackBucket>, val bucketSizeInSeconds: Float, val volume: Float ) typealias TrackBucket = List<PositionedBoundedWaveform>
18
Kotlin
1
11
1f138bf5c5d46a80b23eca8bde589da1b865662a
737
fsynth
MIT License
app/src/main/kotlin/vergecurrency/vergewallet/view/ui/activity/SplashActivity.kt
coalacorey
240,464,098
true
{"Kotlin": 258191, "Java": 3992}
package vergecurrency.vergewallet.view.ui.activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.widget.Toast import vergecurrency.vergewallet.R import vergecurrency.vergewallet.service.model.PreferencesManager import vergecurrency.vergewallet.service.model.network.layers.TorManager import vergecurrency.vergewallet.view.base.BaseActivity import vergecurrency.vergewallet.view.ui.activity.firstlaunch.FirstLaunchActivity import vergecurrency.vergewallet.wallet.WalletManager class SplashActivity : BaseActivity() { //DbOpenHelper dbOpenHelper; //private AbstractDaoSession daoSession; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //init db //dbOpenHelper = new DbOpenHelper(this,"verge.db",1); //Database db = dbOpenHelper.getWritableDb(); //daoSession = new AbstractDaoMaster; setContentView(R.layout.activity_splash) //Just to have the splash screen going briefly Handler().postDelayed({ this.startApplication() }, 500) } private fun startApplication() { try { PreferencesManager.initEncryptedPreferences(this) //TESTING only PreferencesManager.usingTor = false if (PreferencesManager.usingTor) { TorManager.startTor(this) } } catch (e: Exception) { e.printStackTrace() } if (PreferencesManager.isFirstLaunch) { startActivity(Intent(applicationContext, FirstLaunchActivity::class.java)) finish() } else { try { //init took place in VergeWalletApplication WalletManager.startWallet() } catch (e: Exception) { Toast.makeText(applicationContext, "Something went wrong", Toast.LENGTH_SHORT).show() } startActivity(Intent(applicationContext, WalletActivity::class.java)) finish() } } override fun onBackPressed() {} }
0
null
0
0
a75b7e21134151bc66d13d66f4d35160cd5d8d87
2,084
vDroid
MIT License
kactoos-common/src/test/kotlin/nnl/rocks/kactoos/text/RotatedTextTest.kt
neonailol
117,650,092
false
null
package nnl.rocks.kactoos.text import nnl.rocks.kactoos.test.AssertTextsEquals import kotlin.test.Test class RotatedTextTest { @Test fun rotateRightText() { AssertTextsEquals( RotatedText(TextOf { "Hello!" }, 2), TextOf { "o!Hell" }, "Can't rotate text to right" ) } @Test fun rotateLeftText() { AssertTextsEquals( RotatedText(TextOf { "Hi!" }, - 1), TextOf { "i!H" }, "Can't rotate text to left" ) } @Test fun noRotateWhenShiftZero() { AssertTextsEquals( RotatedText(TextOf { "Cactoos!" }, 0), TextOf { "Cactoos!" }, "Rotate text shift zero" ) } @Test fun noRotateWhenShiftModZero() { AssertTextsEquals( RotatedText(TextOf { "Cactoos!" }, "Cactoos!".length), TextOf { "Cactoos!" }, "Rotate text shift mod zero" ) } @Test fun noRotateWhenEmpty() { AssertTextsEquals( RotatedText(TextOf { "" }, 2), TextOf { "" }, "Rotate text when empty" ) } }
0
Kotlin
1
19
ce10c0bc7e6e65076b8ace90770b9f7648facf4a
1,171
kactoos
MIT License
example/src/main/kotlin/name/kocian/api/testing/CountriesStep.kt
misa
332,186,659
false
null
package name.kocian.api.testing import io.cucumber.java8.En import name.kocian.api.testing.HttpMethod.GET import org.junit.Assert.assertEquals private const val HOST = "https://restcountries.eu/rest/v2/" class CountriesStep : En { var countriesFound: Int? = 0 var countryName: String = "" init { When<String>("I search for {string}") { searchText -> val result = Request(GET, HOST + "name/$searchText") .execute() countriesFound = result.body?.arraySize countryName = result.valueOf(1, "name") as String } Then<Int>("I find {int} result") { searchResultsCount -> assertEquals(searchResultsCount, countriesFound) } Then<String>("Name is {string}") { expectedName -> assertEquals(expectedName, countryName) } } }
0
Kotlin
0
1
dfb0170c068bdf39368363914d02d2ec501b2746
859
api-testing
Apache License 2.0
src/commonMain/kotlin/com/zhangke/activitypub/api/PushRepo.kt
0xZhangKe
594,285,909
false
{"Kotlin": 186330}
package com.zhangke.activitypub.api import com.zhangke.activitypub.ActivityPubClient import com.zhangke.activitypub.entities.SubscribePushRequestEntity import com.zhangke.activitypub.entities.WebPushSubscriptionEntity import io.ktor.client.call.body import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.post import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.contentType import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put class PushRepo(private val client: ActivityPubClient) { private val subscriptionUrl = "${client.baseUrl}api/v1/push/subscription" suspend fun subscribePush(request: SubscribePushRequestEntity): Result<WebPushSubscriptionEntity> { return runCatching { client.httpClient.post(subscriptionUrl) { contentType(ContentType.Application.Json) setBody(request) }.body() } } suspend fun getSubscription(): Result<WebPushSubscriptionEntity> { return runCatching { client.httpClient.get(subscriptionUrl).body() } } suspend fun updateSubscription( mention: Boolean? = null, status: Boolean? = null, reblog: Boolean? = null, follow: Boolean? = null, followRequest: Boolean? = null, favourite: Boolean? = null, poll: Boolean? = null, update: Boolean? = null, policy: String? = null, ): Result<WebPushSubscriptionEntity> { return runCatching { client.httpClient.put(subscriptionUrl) { contentType(ContentType.Application.Json) val jsonBody = buildJsonObject { val data = buildJsonObject { val alert = buildJsonObject { putIfNotNull("mention", mention) putIfNotNull("status", status) putIfNotNull("reblog", reblog) putIfNotNull("follow", follow) putIfNotNull("follow_request", followRequest) putIfNotNull("favourite", favourite) putIfNotNull("poll", poll) putIfNotNull("update", update) } put("alert", alert) } put("data", data) if (policy != null) { put("policy", policy) } } setBody(jsonBody) }.body() } } private fun JsonObjectBuilder.putIfNotNull(key: String, value: Boolean?) { if (value != null) put(key, value) } suspend fun removeSubscription(): Result<WebPushSubscriptionEntity> { return runCatching { client.httpClient.delete(subscriptionUrl).body() } } }
0
Kotlin
0
3
2719aa357158289f38717057affe37a1d298b499
3,069
ActivityPub-Kotlin
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/submission/data/tekhistory/TEKHistoryStorage.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.submission.data.tekhistory import android.database.sqlite.SQLiteConstraintException import androidx.room.withTransaction import com.google.android.gms.nearby.exposurenotification.TemporaryExposureKey import de.rki.coronawarnapp.submission.data.tekhistory.internal.TEKEntryDao import de.rki.coronawarnapp.submission.data.tekhistory.internal.TEKHistoryDatabase import de.rki.coronawarnapp.submission.data.tekhistory.internal.toPersistedTEK import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import okio.ByteString.Companion.toByteString import org.joda.time.Instant import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class TEKHistoryStorage @Inject constructor( private val tekHistoryDatabaseFactory: TEKHistoryDatabase.Factory ) { private val database by lazy { tekHistoryDatabaseFactory.create() } private val tekHistoryTables by lazy { database.tekHistory() } suspend fun storeTEKData(data: TEKBatch) = database.withTransaction { data.keys.forEach { val id = it.keyData.toByteString().base64() val newEntry = TEKEntryDao( id = id, batchId = data.batchId, obtainedAt = data.obtainedAt, persistedTEK = it.toPersistedTEK() ) Timber.tag(TAG).v("Inserting TEK: %s", newEntry) try { tekHistoryTables.insertEntry(newEntry) } catch (e: SQLiteConstraintException) { Timber.i("TEK is already stored: %s", it) } } } val tekData: Flow<List<TEKBatch>> by lazy { tekHistoryTables.allEntries().map { tekDaos -> val batches = mutableMapOf<String, List<TEKEntryDao>>() tekDaos.forEach { tekDao -> batches[tekDao.batchId] = batches.getOrPut(tekDao.batchId) { emptyList() }.plus(tekDao) } batches.values.map { batchTEKs -> TEKBatch( batchId = batchTEKs.first().batchId, obtainedAt = batchTEKs.first().obtainedAt, keys = batchTEKs.map { it.persistedTEK.toTemporaryExposureKey() } ) }.toList() } } suspend fun clear() { Timber.w("clear() - Clearing all stored temporary exposure keys.") database.clearAllTables() } data class TEKBatch( val obtainedAt: Instant, val batchId: String, val keys: List<TemporaryExposureKey> ) companion object { private const val TAG = "TEKHistoryStorage" } }
6
null
516
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
2,647
cwa-app-android
Apache License 2.0
library/src/main/java/com/drakeet/multitype/OneTypeToMoreBinderMultiType.kt
chenfei0928
130,954,695
false
{"Kotlin": 1048340, "Java": 254586}
/** * 实现一实体类型对应多binder注册的扩展函数 * * @author ChenFei(<EMAIL>) * @date 2019-11-19 18:02 */ package com.drakeet.multitype import io.github.chenfei0928.util.Log private const val TAG = "KW_MultiType" /** * 注册一个类型的一type对多binder的映射关系,并且使用map字典[viewTypeRecord]来保存实例与binder类的映射。 * * 考虑到binder类定义时会使用抽象类隔离ui逻辑与点击事件,[viewTypeRecord]的binder类定义到[binders]的实现 * 不允许出现任何一定义对多实现的关系。 * 即在[viewTypeRecord]中所出现的各个值(类对象)之间不允许出现任何继承关系,也不允许出现一个类对象在[binders] * 中有多个实现提供,否则会在使用该类对象在[binders]中查找该类对象实现时出现找到的并不是其最终实现类的情况。 * * [viewTypeRecord]的map通常会使用依赖于对象hash的map实现,此时要确保[T]的类没有重写[Any.hashCode]方法, * 以避免列表出现重复内容数据时hash冲突(重复),而覆盖了之前实例的binder映射关系。 * 并要求在某项被记录其binder之后,不允许修改其实例属性,否则可能会导致其hash变化,影响查找其值。 * 或可以直接使用[androidx.collection.SystemIdentityArrayMap]实现的map, * 其会使用JVM提供的[Object.hashCode]默认实现,可避免由于对象内容相同导致的hash碰撞。 * * @param clazz binder要渲染的bean的类型 * @param binders 实现该类型布局绑定器的实例 * @param viewTypeRecord 要显示的实例与该实例所使用的布局绑定器映射关系。 */ @Suppress("unused") fun <T> MultiTypeAdapter.registerWithTypeRecordClassMap( clazz: Class<T>, binders: Array<ItemViewDelegate<T, *>>, viewTypeRecord: Map<T, Class<out ItemViewDelegate<T, *>>> ) { registerWithTypeRecord(clazz, binders) { item -> viewTypeRecord[item] } } /** * 注册一个类型的一type对多binder的映射关系,并且使用map字典[viewTypeRecord]来保存实例与binder类的映射。 * * 考虑到binder类定义时会使用抽象类隔离ui逻辑与点击事件,[viewTypeRecord]的binder类定义到[binders]的实现 * 不允许出现任何一定义对多实现的关系。 * 即在[viewTypeRecord]中所出现的各个值(类对象)之间不允许出现任何继承关系,也不允许出现一个类对象在[binders] * 中有多个实现提供,否则会在使用该类对象在[binders]中查找该类对象实现时出现找到的并不是其最终实现类的情况。 * * [viewTypeRecord]的map通常会使用依赖于对象hash的map实现,此时要确保[T]的类没有重写[Any.hashCode]方法, * 以避免列表出现重复内容数据时hash冲突(重复),而覆盖了之前实例的binder映射关系。 * 并要求在某项被记录其binder之后,不允许修改其实例属性,否则可能会导致其hash变化,影响查找其值。 * 或可以直接使用[androidx.collection.SystemIdentityArrayMap]实现的map, * 其会使用JVM提供的[Object.hashCode]默认实现,可避免由于对象内容相同导致的hash碰撞。 * * @param binders 实现该类型布局绑定器的实例 * @param viewTypeRecord 要显示的实例与该实例所使用的布局绑定器映射关系。 */ fun <T> MultiTypeAdapter.registerWithTypeRecorderMap( clazz: Class<T>, binders: Array<ItemViewDelegate<T, *>>, viewTypeRecord: Map<in T, ViewTypeProvider> ) { registerWithTypeRecord(clazz, binders) { item -> viewTypeRecord[item]?.binderClazz } } /** * 注册一个类型的一type对多binder的映射关系,并且通过回调选择其binder类映射。 * * 考虑到binder类定义时会使用抽象类隔离ui逻辑与点击事件,[viewTypeRecorder]的binder类定义到[binders]的实现 * 不允许出现任何一定义对多实现的关系。 * 即在[viewTypeRecorder]中所出现的各个值(类对象)之间不允许出现任何继承关系,也不允许出现一个类对象在[binders] * 中有多个实现提供,否则会在使用该类对象在[binders]中查找该类对象实现时出现找到的并不是其最终实现类的情况。 * * @param binders 实现该类型布局绑定器的实例 * @param viewTypeRecorder 提供要显示的实例与该实例所使用的布局绑定器映射关系。 */ private inline fun <T> MultiTypeAdapter.registerWithTypeRecord( clazz: Class<T>, binders: Array<ItemViewDelegate<T, *>>, crossinline viewTypeRecorder: (T) -> Class<out ItemViewDelegate<*, *>>? ) { registerWithLinker(clazz, binders) linker@{ localBinders, _, item -> // 获取该item所使用的binder类 val binderClazz = viewTypeRecorder(item) if (binderClazz == null) { Log.w(TAG, "registerWithTypeRecordClassMap: item not found binderClass.\n$item") return@linker 0 } // 查找第几个是该binder类的实例 val index = localBinders.indexOfFirst { binderClazz.isInstance(it) } return@linker if (index != -1) { index } else { Log.w(TAG, buildString { append("registerWithTypeRecordClassMap: ") append("item's binder instance not found by binderClass.") appendLine() append(item) }) 0 } } } /** * 注册一个类型的一type对多binder的映射关系,并使用linker来进行分配管理 */ inline fun <reified T> MultiTypeAdapter.registerWithLinker( binders: Array<ItemViewDelegate<T, *>>, crossinline linker: BindersLinker<T> ) { registerWithLinker(T::class.java, binders, linker) } /** * 注册一个类型的一type对多binder的映射关系,并使用linker来进行分配管理 */ inline fun <T> MultiTypeAdapter.registerWithLinker( clazz: Class<T>, binders: Array<ItemViewDelegate<T, *>>, crossinline linker: BindersLinker<T> ) { register(clazz) .to(*binders) .withLinker(object : Linker<T> { override fun index(position: Int, item: T): Int { return linker(binders, position, item) } }) } /** * 传入binders,并返回指定的item所使用的binder在binders中对应的下标 * [KotlinClassLinker] */ typealias BindersLinker<T> = (binders: Array<ItemViewDelegate<T, *>>, position: Int, item: T) -> Int
1
Kotlin
0
8
bbe587216a2450deb19af90ea4d7d24d23443dd1
4,465
Util
MIT License
test/src/me/anno/tests/image/HugeImageTest.kt
AntonioNoack
456,513,348
false
null
package me.anno.tests.image import me.anno.Engine import me.anno.gpu.GFX import me.anno.gpu.hidden.HiddenOpenGLContext import me.anno.gpu.texture.TextureCache import me.anno.utils.OS.downloads import me.anno.utils.Sleep.waitUntilDefined import kotlin.concurrent.thread fun main() { @Suppress("SpellCheckingInspection") val source = downloads.getChild("Abbeanum_new.glb/textures/0.jpg") HiddenOpenGLContext.createOpenGL() thread { val tex = waitUntilDefined(true) { TextureCache[source, false] } println(tex) Engine.requestShutdown() } GFX.workGPUTasksUntilShutdown() }
0
null
3
9
566e183d43bff96ee3006fecf0142e6d20828857
638
RemsEngine
Apache License 2.0
test/src/me/anno/tests/image/HugeImageTest.kt
AntonioNoack
456,513,348
false
null
package me.anno.tests.image import me.anno.Engine import me.anno.gpu.GFX import me.anno.gpu.hidden.HiddenOpenGLContext import me.anno.gpu.texture.TextureCache import me.anno.utils.OS.downloads import me.anno.utils.Sleep.waitUntilDefined import kotlin.concurrent.thread fun main() { @Suppress("SpellCheckingInspection") val source = downloads.getChild("Abbeanum_new.glb/textures/0.jpg") HiddenOpenGLContext.createOpenGL() thread { val tex = waitUntilDefined(true) { TextureCache[source, false] } println(tex) Engine.requestShutdown() } GFX.workGPUTasksUntilShutdown() }
0
null
3
9
566e183d43bff96ee3006fecf0142e6d20828857
638
RemsEngine
Apache License 2.0
SavedDataApplication/app/src/main/java/co/edu/aulamatriz/saveddataapplication/FileInternalActivity.kt
arthas1888
144,399,674
false
null
package co.edu.aulamatriz.saveddataapplication import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_file_internal.* import java.io.* class FileInternalActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_file_internal) crearArchivo() leerArchivo() } private fun leerArchivo() { val inStream: FileInputStream = openFileInput("test.txt") if (inStream != null) { val stringToReturn = inStream.bufferedReader() .use(BufferedReader::readText) textView2.setText(stringToReturn) } } private fun crearArchivo() { val oStream: FileOutputStream = openFileOutput("test.txt", Context.MODE_PRIVATE) val writer : OutputStreamWriter = OutputStreamWriter(oStream) writer.write("esto es una prueba") writer.flush() writer.close() } }
0
Kotlin
0
0
bf1898f8d5f600817ae56b5e0aa5ab256227445d
1,165
Android-Kotlin
Apache License 2.0