path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/ninja/luke/mobi/journey2/app/AppJourney.kt | luke-vietnam | 497,926,585 | false | {"Kotlin": 84219} | package ninja.luke.mobi.journey2.app
import ninja.luke.mobi.journey2.scope.journey.J2JourneyFragment
class AppJourney : J2JourneyFragment<AppRoute>(
AppSdk,
R.layout.journey_app
) | 0 | Kotlin | 1 | 7 | 5956213e91c72e44406a1c65ccae53ffe890bf8e | 189 | journey2-concept | MIT License |
src/me/anno/ui/input/components/ColorPicker.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.ui.input.components
import me.anno.gpu.Cursor
import me.anno.gpu.drawing.DrawRectangles
import me.anno.gpu.framebuffer.Framebuffer
import me.anno.gpu.texture.Texture2D
import me.anno.image.Image
import me.anno.input.Input
import me.anno.input.Key
import me.anno.maths.Maths
import me.anno.maths.Maths.unmix
import me.anno.ui.Style
import me.anno.ui.base.ImagePanel
import me.anno.ui.base.components.StretchModes
import me.anno.utils.Color.toHexColor
import me.anno.utils.structures.tuples.IntPair
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class ColorPicker(
val gpuData: Framebuffer?,
val gpuTexture: Texture2D,
val cpuData: Image,
val ownsGPUData: Boolean,
val flipTexture: Boolean,
style: Style
) : ImagePanel(style) {
// todo bug: when zoomed in (after window size change), the color preview is incorrect... why?
init {
// padding helps nobody, but overflow should help to find pixels within the center better :)
stretchMode = StretchModes.OVERFLOW
flipY = !flipTexture
}
override fun onUpdate() {
invalidateDrawing()
}
fun getMouseCoordinates(): IntPair {
val window = window!!
var x01 = unmix(lix.toFloat(), (lix + liw).toFloat(), window.mouseX)
var y01 = unmix(liy.toFloat(), (liy + lih).toFloat(), window.mouseY)
if (flipX) x01 = 1f - x01
if (flipY) y01 = 1f - y01
var x0w = x01 * cpuData.width
var y0h = y01 * cpuData.height
if (!x0w.isFinite()) x0w = 0f
if (!y0h.isFinite()) y0h = 0f
val mouseX = Maths.clamp(x0w.toInt(), 0, cpuData.width - 1)
val mouseY = Maths.clamp(y0h.toInt(), 0, cpuData.height - 1)
return IntPair(mouseX, mouseY)
}
var pixelCount = 9 // should be odd
var pixelScale = 6
var pixelSpacing = 1
var generalPadding = 2
override fun onDraw(x0: Int, y0: Int, x1: Int, y1: Int) {
super.onDraw(x0, y0, x1, y1)
// only show the lens, when it makes sense
val red = 0xffff shl 16
if (pixelScale > abs(lih) / max(1, gpuTexture.height)) {
val width = pixelCount * (pixelScale + pixelSpacing) - pixelSpacing
val totalWidth = width + generalPadding * 2
val (mouseX, mouseY) = getMouseCoordinates()
val window = window!!
// draw rect there, where it isn't in the way
val x3 = window.mouseXi - totalWidth / 2
val y3 = window.mouseYi - totalWidth / 2
val color = cpuData.getRGB(mouseX, mouseY)
// show zoomed-in view with maybe 5x5 pixels
DrawRectangles.drawRect(x3, y3, width + generalPadding * 4, width + generalPadding * 4, color)
DrawRectangles.drawRect(x3 + generalPadding * 2, y3 + generalPadding * 2, width, width, backgroundColor)
DrawRectangles.drawRect(
x3 + generalPadding * 2 + (pixelCount / 2) * (pixelScale + pixelSpacing) - pixelSpacing,
y3 + generalPadding * 2 + (pixelCount / 2) * (pixelScale + pixelSpacing) - pixelSpacing,
pixelScale + pixelSpacing * 2,
pixelScale + pixelSpacing * 2,
red
)
for (yi in 0 until pixelCount) {
val y4 = y3 + generalPadding * 2 + yi * (pixelScale + pixelSpacing)
for (xi in 0 until pixelCount) {
val x4 = x3 + generalPadding * 2 + xi * (pixelScale + pixelSpacing)
val mx = mouseX + xi - pixelCount / 2
val my = mouseY + yi - pixelCount / 2
val x = Maths.clamp(mx, max(0, x0), min(x1, cpuData.width) - 1)
val y = Maths.clamp(my, max(0, y0), min(y1, cpuData.height) - 1)
DrawRectangles.drawRect(x4, y4, pixelScale, pixelScale, cpuData.getRGB(x, y))
}
}
} else {
// show red border around pixel at cursor
var (mouseX, mouseY) = getMouseCoordinates()
if (flipX) mouseX = gpuTexture.width - 1 - mouseX
if (flipY) mouseY = gpuTexture.height - 1 - mouseY
val x2 = lix + mouseX * liw / gpuTexture.width
val y2 = liy + mouseY * lih / gpuTexture.height
val x3 = lix + (mouseX + 1) * liw / gpuTexture.width
val y3 = liy + (mouseY + 1) * lih / gpuTexture.height
DrawRectangles.drawBorder(min(x2, x3), min(y2, y3), abs(x3 - x2), abs(y3 - y2), red, 2)
}
}
fun sign(i: Int) = if (i < 0) -1 else +1
override fun onMouseClicked(x: Float, y: Float, button: Key, long: Boolean) {
// get pixel color
val (mouseX, mouseY) = getMouseCoordinates()
val color = cpuData.getRGB(mouseX, mouseY)
// place color into this view
callback(color)
// place color into clipboard
Input.setClipboardContent(color.toHexColor())
// hide window
windowStack.remove(window!!)
if (ownsGPUData) {
gpuData?.destroy()
gpuTexture.destroy()
}
}
var callback: (Int) -> Unit = {}
override fun getCursor() = Cursor.hand
override fun getTexture() = gpuTexture
} | 0 | Kotlin | 3 | 9 | 566e183d43bff96ee3006fecf0142e6d20828857 | 5,249 | RemsEngine | Apache License 2.0 |
app/src/main/java/com/arsylk/mammonsmite/presentation/dialog/result/file/ResultFileItem.kt | Arsylk | 175,204,028 | false | null | package com.arsylk.mammonsmite.presentation.dialog.result.file
import com.arsylk.mammonsmite.domain.files.IFile
import com.arsylk.mammonsmite.model.file.FileType
data class ResultFileItem(
val label: String,
val enabled: Boolean,
val type: FileType,
val file: IFile,
) | 3 | null | 10 | 34 | 2ec0056ea61d3d170ac4ee22a96198d58f6214e2 | 286 | destiny-child-tools-kr-apk | MIT License |
multisrc/overrides/madara/mangasehri/src/MangaSehri.kt | kevin01523 | 612,636,298 | false | {"Kotlin": 5305448} | package eu.kanade.tachiyomi.extension.tr.mangasehri
import eu.kanade.tachiyomi.multisrc.madara.Madara
import java.text.SimpleDateFormat
import java.util.Locale
class MangaSehri : Madara(
"Manga Şehri",
"https://manga-sehri.com",
"tr",
SimpleDateFormat("dd/MM/yyy", Locale("tr")),
) {
override val useNewChapterEndpoint = false
override fun searchPage(page: Int): String = if (page == 1) "" else "page/$page/"
}
| 9 | Kotlin | 99 | 9 | 8ca7f06a4fdfbfdd66520a4798c8636274263428 | 438 | tachiyomi-extensions | Apache License 2.0 |
src/test/kotlin/org/opensearch/indexmanagement/indexstatemanagement/transport/action/indexpolicy/IndexPolicyRequestTests.kt | opensearch-project | 354,094,562 | false | null | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.indexmanagement.indexstatemanagement.transport.action.indexpolicy
import org.opensearch.action.support.WriteRequest
import org.opensearch.common.io.stream.BytesStreamOutput
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.indexmanagement.indexstatemanagement.ISMActionsParser
import org.opensearch.indexmanagement.indexstatemanagement.action.AllocationAction
import org.opensearch.indexmanagement.indexstatemanagement.action.DeleteAction
import org.opensearch.indexmanagement.indexstatemanagement.action.IndexPriorityAction
import org.opensearch.indexmanagement.indexstatemanagement.extension.SampleCustomActionParser
import org.opensearch.indexmanagement.indexstatemanagement.model.Policy
import org.opensearch.indexmanagement.indexstatemanagement.model.State
import org.opensearch.indexmanagement.indexstatemanagement.randomErrorNotification
import org.opensearch.indexmanagement.opensearchapi.convertToMap
import org.opensearch.test.OpenSearchTestCase
import java.time.Instant
import java.time.temporal.ChronoUnit
class IndexPolicyRequestTests : OpenSearchTestCase() {
fun `test index policy request index priority action`() {
val policyID = "policyID"
val action = IndexPriorityAction(50, 0)
val states = listOf(State(name = "SetPriorityState", actions = listOf(action), transitions = listOf()))
val policy = Policy(
id = policyID,
description = "description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
val seqNo: Long = 123
val primaryTerm: Long = 456
val refreshPolicy = WriteRequest.RefreshPolicy.NONE
val req = IndexPolicyRequest(policyID, policy, seqNo, primaryTerm, refreshPolicy)
val out = BytesStreamOutput()
req.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newReq = IndexPolicyRequest(sin)
assertEquals(policyID, newReq.policyID)
assertEquals(policy.convertToMap(), newReq.policy.convertToMap())
assertEquals(seqNo, newReq.seqNo)
assertEquals(primaryTerm, newReq.primaryTerm)
}
fun `test index policy request allocation action`() {
val policyID = "policyID"
val action = AllocationAction(require = mapOf("box_type" to "hot"), exclude = emptyMap(), include = emptyMap(), index = 0)
val states = listOf(State("Allocate", listOf(action), listOf()))
val policy = Policy(
id = policyID,
description = "description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
val seqNo: Long = 123
val primaryTerm: Long = 456
val refreshPolicy = WriteRequest.RefreshPolicy.NONE
val req = IndexPolicyRequest(policyID, policy, seqNo, primaryTerm, refreshPolicy)
val out = BytesStreamOutput()
req.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newReq = IndexPolicyRequest(sin)
assertEquals(policyID, newReq.policyID)
assertEquals(policy.convertToMap(), newReq.policy.convertToMap())
assertEquals(seqNo, newReq.seqNo)
assertEquals(primaryTerm, newReq.primaryTerm)
}
fun `test index policy request delete action`() {
val policyID = "policyID"
val action = DeleteAction(index = 0)
val states = listOf(State("Delete", listOf(action), listOf()))
val policy = Policy(
id = policyID,
description = "description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
val seqNo: Long = 123
val primaryTerm: Long = 456
val refreshPolicy = WriteRequest.RefreshPolicy.NONE
val req = IndexPolicyRequest(policyID, policy, seqNo, primaryTerm, refreshPolicy)
val out = BytesStreamOutput()
req.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newReq = IndexPolicyRequest(sin)
assertEquals(policyID, newReq.policyID)
assertEquals(policy.convertToMap(), newReq.policy.convertToMap())
assertEquals(seqNo, newReq.seqNo)
assertEquals(primaryTerm, newReq.primaryTerm)
}
fun `test index policy request custom action`() {
val customActionParser = SampleCustomActionParser()
val extensionName = "testExtension"
ISMActionsParser.instance.addParser(customActionParser, extensionName)
val policyID = "policyID"
val action = SampleCustomActionParser.SampleCustomAction(someInt = randomInt(), index = 0)
val states = listOf(State("MyState", listOf(action), listOf()))
val policy = Policy(
id = policyID,
description = "description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
val seqNo: Long = 123
val primaryTerm: Long = 456
val refreshPolicy = WriteRequest.RefreshPolicy.NONE
val req = IndexPolicyRequest(policyID, policy, seqNo, primaryTerm, refreshPolicy)
val out = BytesStreamOutput()
req.writeTo(out)
val sin = StreamInput.wrap(out.bytes().toBytesRef().bytes)
val newReq = IndexPolicyRequest(sin)
assertEquals(policyID, newReq.policyID)
assertEquals(policy.convertToMap(), newReq.policy.convertToMap())
assertEquals(seqNo, newReq.seqNo)
assertEquals(primaryTerm, newReq.primaryTerm)
ISMActionsParser.instance.parsers.removeIf { it.getActionType() == SampleCustomActionParser.SampleCustomAction.name }
}
}
| 145 | null | 78 | 53 | 4adc99edbcc68bf8197ffad82d611a76451481c4 | 6,383 | index-management | Apache License 2.0 |
buildSrc/src/main/kotlin/ConfigData.kt | Montfel | 537,669,918 | false | {"Kotlin": 27272} | object ConfigData {
const val compileSdkVersion = 34
const val targetSdkVersion = 34
const val minSdkVersion = 21
const val majorVersion = 1
const val minorVersion = 0
const val patchVersion = 0
const val versionName = "$majorVersion.$minorVersion.$patchVersion"
const val versionCode = 1
}
| 4 | Kotlin | 0 | 1 | b395fcd2ba4b1bf37703009569640567d4fbc38d | 323 | gamer-guide | MIT License |
db-async-common/src/test/java/com/github/jasync/sql/db/pool/PartitionedAsyncObjectPoolSpec.kt | mirromutth | 176,066,212 | false | null | package com.github.jasync.sql.db.pool
import com.github.jasync.sql.db.util.FP
import com.github.jasync.sql.db.util.Try
import com.github.jasync.sql.db.util.flatMapAsync
import com.github.jasync.sql.db.util.mapAsync
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.kotlin.await
import org.awaitility.kotlin.matches
import org.awaitility.kotlin.untilCallTo
import org.junit.After
import org.junit.Test
class PartitionedAsyncObjectPoolSpec {
private val config = PoolConfiguration(100, Long.MAX_VALUE, 100)
private val factory = ForTestingObjectFactory()
private var tested =
ActorBasedObjectPool(
factory,
config,
testItemsPeriodically = false)
private val pool = tested
private val maxObjects = config.maxObjects
// val maxIdle = config.maxIdle / 2
private val maxQueueSize = config.maxQueueSize
private class ForTestingObjectFactory :
ObjectFactory<MyPooledObject> {
val reject = HashSet<MyPooledObject>()
var failCreate = false
val current = AtomicInteger(0)
val createdObjects = mutableListOf<MyPooledObject>()
override fun create(): CompletableFuture<MyPooledObject> =
if (failCreate) {
FP.failed(IllegalStateException("failed to create item (it is intentional)"))
} else {
val created = MyPooledObject(current.incrementAndGet())
createdObjects.add(created)
FP.successful(created)
}
override fun destroy(item: MyPooledObject) {
}
override fun validate(item: MyPooledObject): Try<MyPooledObject> {
if (reject.contains(item)) {
throw IllegalStateException("validate failed for the test (it is intentional)")
}
return Try.just(item)
}
}
private val takenObjects = mutableListOf<MyPooledObject>()
private val queuedObjects = mutableListOf<CompletableFuture<MyPooledObject>>()
private fun takeAndWait(objects: Int) {
for (it in 1..objects) {
takenObjects += pool.take().get()
}
}
private fun takeQueued(objects: Int) {
takeNoWait(objects)
await.untilCallTo { pool.waitingForItem.size } matches { it == objects }
}
private fun takeNoWait(objects: Int) {
for (it in 1..objects) {
queuedObjects += pool.take()
}
}
@After
fun closePool() {
tested.close().get()
}
@Test
fun `pool contents - before exceed maxObjects - take one element`() {
takeAndWait(1)
assertThat(pool.usedItems.size).isEqualTo(1)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
private fun verifyException(
exType: Class<out java.lang.Exception>,
causeType: Class<out java.lang.Exception>? = null,
body: () -> Unit
) {
try {
body()
throw Exception("${exType.simpleName}->${causeType?.simpleName} was not thrown")
} catch (e: Exception) {
e.printStackTrace()
assertThat(e::class.java).isEqualTo(exType)
var cause = e.cause
while (cause?.cause != null) {
cause = cause.cause
}
causeType?.let { assertThat(cause!!::class.java).isEqualTo(it) }
}
}
@Test
fun `pool contents - before exceed maxObjects - take one element and return it invalid`() {
takeAndWait(1)
factory.reject += MyPooledObject(1)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(1)).get()
}
assertThat(pool.usedItems.size).isEqualTo(0)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - before exceed maxObjects - take one failed element`() {
factory.failCreate = true
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
takeAndWait(1)
}
assertThat(pool.usedItems.size).isEqualTo(0)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - before exceed maxObjects - take maxObjects`() {
takeAndWait(maxObjects)
assertThat(pool.usedItems.size).isEqualTo(maxObjects)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - before exceed maxObjects - take maxObjects - 1 and take one failed`() {
takeAndWait(maxObjects - 1)
factory.failCreate = true
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
takeAndWait(1)
}
assertThat(pool.usedItems.size).isEqualTo(maxObjects - 1)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - before exceed maxObjects - "take maxObjects and receive one back"`() {
takeAndWait(maxObjects)
pool.giveBack(MyPooledObject(1)).get()
assertThat(pool.usedItems.size).isEqualTo(maxObjects - 1)
assertThat(pool.waitingForItem.size).isEqualTo(0)
await.untilCallTo { pool.availableItems.size } matches { it == 1 }
}
@Test
fun `pool contents - before exceed maxObjects - "take maxObjects and receive one invalid back"`() {
takeAndWait(maxObjects)
factory.reject += MyPooledObject(1)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(1)).get()
}
assertThat(pool.usedItems.size).isEqualTo(maxObjects - 1)
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "one take queued"`() {
takeAndWait(maxObjects)
takeQueued(1)
assertThat(pool.usedItems.size).isEqualTo(maxObjects)
assertThat(pool.waitingForItem.size).isEqualTo(1)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "one take queued and receive one item back"`() {
takeAndWait(maxObjects)
val taking = pool.take()
pool.giveBack(MyPooledObject(1)).get()
assertThat(taking.get()).isEqualTo(1.toPoolObject)
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
private val Int.toPoolObject: MyPooledObject
get() = MyPooledObject(this)
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "one take queued and receive one invalid item back"`() {
takeAndWait(maxObjects)
pool.take()
factory.reject += MyPooledObject(1)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(1)).get()
}
await.untilCallTo { pool.usedItems.size }.matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "maxQueueSize takes queued"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
assertThat(pool.usedItems.size).isEqualTo(maxObjects)
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "maxQueueSize takes queued and receive one back"`() {
takeAndWait(maxObjects)
val taking = pool.take()
takeNoWait(maxQueueSize - 1)
pool.giveBack(MyPooledObject(10)).get()
assertThat((taking).get()).isEqualTo(10.toPoolObject)
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize - 1)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, before exceed maxQueueSize - "maxQueueSize takes queued and receive one invalid back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
factory.reject += MyPooledObject(11)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(11)).get()
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize - 1)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "start to reject takes"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
verifyException(ExecutionException::class.java, PoolExhaustedException::class.java) {
(pool.take().get())
}
assertThat(pool.usedItems.size).isEqualTo(maxObjects)
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive an object back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
(pool.giveBack(MyPooledObject(1))).get()
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize - 1)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive an invalid object back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
factory.reject += MyPooledObject(1)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(1)).get()
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(maxQueueSize - 1)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive maxQueueSize objects back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
for (i in 1..maxObjects) {
(pool.giveBack(MyPooledObject(1))).get()
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive maxQueueSize invalid objects back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
for (i in 1..maxObjects) {
factory.reject += MyPooledObject(i)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
pool.giveBack(MyPooledObject(i)).get()
}
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(0)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive maxQueueSize + 1 object back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
for (i in 1..maxObjects) {
(pool.giveBack(MyPooledObject(i))).get()
}
(pool.giveBack(MyPooledObject(1))).get()
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects - 1 }
assertThat(pool.waitingForItem.size).isEqualTo(0)
assertThat(pool.availableItems.size).isEqualTo(1)
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "receive maxQueueSize + 1 invalid object back"`() {
takeAndWait(maxObjects)
takeQueued(maxQueueSize)
for (i in 1..maxObjects) {
(pool.giveBack(MyPooledObject(i))).get()
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects }
await.untilCallTo { pool.waitingForItem.size } matches { it == 0 }
await.untilCallTo { pool.availableItems.size } matches { it == 0 }
factory.reject += MyPooledObject(1)
verifyException(ExecutionException::class.java, IllegalStateException::class.java) {
(pool.giveBack(MyPooledObject(1)).get())
}
await.untilCallTo { pool.usedItems.size } matches { it == maxObjects - 1 }
await.untilCallTo { pool.waitingForItem.size } matches { it == 0 }
await.untilCallTo { pool.availableItems.size } matches { it == 0 }
}
@Test
fun `pool contents - after exceed maxObjects, after exceed maxQueueSize - "gives back the connection to the original pool"`() {
val executor = Executors.newFixedThreadPool(20)
val takes =
(0 until 30).map { _ ->
CompletableFuture.completedFuture(Unit).flatMapAsync(executor) { pool.take() }
}
val futureOfAll =
CompletableFuture.allOf(*takes.toTypedArray())
.mapAsync(executor) { _ -> takes.map { it.get() } }
val takesAndReturns =
futureOfAll.flatMapAsync(executor) { items ->
CompletableFuture.allOf(* items.map { pool.giveBack(it) }.toTypedArray())
}
takesAndReturns.get()
executor.shutdown()
assertThat(pool.usedItems.size).isEqualTo(0)
assertThat(pool.waitingForItem.size).isEqualTo(0)
await.untilCallTo { pool.availableItems.size } matches { it == 30 }
}
}
private data class MyPooledObject(val i: Int) : PooledObject {
override val creationTime: Long get() = 1
override val id: String get() = "$i"
}
| 9 | null | 136 | 2 | 76854b2df7ba39c4843d8c372343403721c4c8b7 | 14,818 | jasync-sql | Apache License 2.0 |
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/lifetime/KotlinReadActionConfinementLifetimeToken.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.platform.lifetime
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import org.jetbrains.kotlin.analysis.api.lifetime.KaLifetimeToken
import org.jetbrains.kotlin.analysis.api.platform.KaCachedService
import org.jetbrains.kotlin.analysis.api.platform.permissions.KaAnalysisPermissionChecker
import kotlin.reflect.KClass
public class KotlinReadActionConfinementLifetimeToken(
project: Project,
private val modificationTracker: ModificationTracker,
) : KaLifetimeToken() {
private val onCreatedTimeStamp = modificationTracker.modificationCount
// We cache several services to avoid repeated `getService` calls in validity assertions.
@KaCachedService
private val permissionChecker = KaAnalysisPermissionChecker.getInstance(project)
@KaCachedService
private val lifetimeTracker = KaLifetimeTracker.getInstance(project)
override fun isValid(): Boolean {
return onCreatedTimeStamp == modificationTracker.modificationCount
}
override fun getInvalidationReason(): String {
if (onCreatedTimeStamp != modificationTracker.modificationCount) return "PSI has changed since creation."
error("Cannot get an invalidation reason for a valid lifetime token.")
}
override fun isAccessible(): Boolean {
if (!ApplicationManager.getApplication().isReadAccessAllowed) return false
if (!permissionChecker.isAnalysisAllowed()) return false
return lifetimeTracker.currentToken == this
}
override fun getInaccessibilityReason(): String {
if (!ApplicationManager.getApplication().isReadAccessAllowed) return "Called outside a read action."
if (!permissionChecker.isAnalysisAllowed()) return permissionChecker.getRejectionReason()
val currentToken = lifetimeTracker.currentToken
if (currentToken == null) return "Called outside an `analyze` context."
if (currentToken != this) return "Using a lifetime owner from an old `analyze` context."
error("Cannot get an inaccessibility reason for a lifetime token when it's accessible.")
}
}
public class KotlinReadActionConfinementLifetimeTokenFactory : KotlinLifetimeTokenFactory {
override val identifier: KClass<out KaLifetimeToken> = KotlinReadActionConfinementLifetimeToken::class
override fun create(project: Project, modificationTracker: ModificationTracker): KaLifetimeToken =
KotlinReadActionConfinementLifetimeToken(project, modificationTracker)
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 2,819 | kotlin | Apache License 2.0 |
protocol/src/main/kotlin/org/jetbrains/bsp/protocol/utils/BazelBuildServerCapabilitiesTypeAdapter.kt | JetBrains | 826,262,028 | false | null | package org.jetbrains.bsp.utils
import ch.epfl.scala.bsp4j.BuildServerCapabilities
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import org.jetbrains.bsp.BazelBuildServerCapabilities
public class BazelBuildServerCapabilitiesTypeAdapter : TypeAdapter<BuildServerCapabilities>() {
private companion object {
private val gson = Gson()
}
override fun write(writer: JsonWriter, capabilities: BuildServerCapabilities) {
if (capabilities is BazelBuildServerCapabilities) {
gson.toJson(capabilities, BazelBuildServerCapabilities::class.java, writer)
} else {
gson.toJson(capabilities, BuildServerCapabilities::class.java, writer)
}
}
override fun read(reader: JsonReader): BazelBuildServerCapabilities =
gson.fromJson(reader, BazelBuildServerCapabilities::class.java)
}
| 2 | null | 9 | 45 | 1d79484cfdf8fc31d3a4b214655e857214071723 | 907 | hirschgarten | Apache License 2.0 |
app/src/main/java/com/exmple/baseprojectmvp/mvp/contract/fragment/ICategoryContract.kt | weileng11 | 189,573,322 | false | null | package com.exmple.baseprojectmvp.mvp.contract.fragment
import com.exmple.corelib.mvp.IListView
import com.exmple.corelib.mvp.IModel
import com.exmple.corelib.mvp.IPresenter
import com.exmple.corelib.mvp.IView
import com.hazz.kotlinmvp.mvp.model.bean.CategoryBean
import com.hazz.kotlinmvp.mvp.model.bean.HomeBean
import io.reactivex.Observable
/**
* @author: ${bruce}
* @project: KotlinMvpExample-master
* @package: com.exmple.baseprojectmvp.mvp.contract.fragment
* @description:
* @date: 2019/6/5
* @time: 14:40
*/
interface ICategoryContract {
interface View : IView<Presenter> {
/**
* 显示分类的信息
*/
fun showCategory(categoryList: ArrayList<CategoryBean>)
/**
* 显示错误信息
*/
fun showError(errorMsg: String)
}
interface Presenter : IPresenter<View, Model> {
/**
* 获取分类的信息
*/
fun getCategoryData()
}
interface Model : IModel {
/**
* 获取首页精选数据
*/
fun getCategoryData() : Observable<ArrayList<CategoryBean>>
}
} | 0 | Kotlin | 0 | 0 | 584174718759919a6ddf31589a3e056c6990ddac | 1,077 | KotlinMvpExample-master | Apache License 2.0 |
graphql-dgs-client/src/main/kotlin/com/netflix/graphql/dgs/client/MonoGraphQLClient.kt | Netflix | 317,375,887 | false | null | /*
* Copyright 2022 Netflix, 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.netflix.graphql.dgs.client
import com.fasterxml.jackson.databind.ObjectMapper
import org.intellij.lang.annotations.Language
import org.springframework.http.HttpHeaders
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import java.util.function.Consumer
/**
* GraphQL client interface for reactive clients.
*/
interface MonoGraphQLClient {
/**
* A reactive call to execute a query and parse its result.
* Don't forget to subscribe() to actually send the query!
* @param query The query string. Note that you can use [code generation](https://netflix.github.io/dgs/generating-code-from-schema/#generating-query-apis-for-external-services) for a type safe query!
* @return A [Mono] of [GraphQLResponse] parses the response and gives easy access to data and errors.
*/
fun reactiveExecuteQuery(
@Language("graphql") query: String
): Mono<GraphQLResponse>
/**
* A reactive call to execute a query and parse its result.
* Don't forget to subscribe() to actually send the query!
* @param query The query string. Note that you can use [code generation](https://netflix.github.io/dgs/generating-code-from-schema/#generating-query-apis-for-external-services) for a type safe query!
* @param variables A map of input variables
* @return A [Mono] of [GraphQLResponse] parses the response and gives easy access to data and errors.
*/
fun reactiveExecuteQuery(
@Language("graphql") query: String,
variables: Map<String, Any>
): Mono<GraphQLResponse>
/**
* A reactive call to execute a query and parse its result.
* Don't forget to subscribe() to actually send the query!
* @param query The query string. Note that you can use [code generation](https://netflix.github.io/dgs/generating-code-from-schema/#generating-query-apis-for-external-services) for a type safe query!
* @param variables A map of input variables
* @param operationName Name of the operation
* @return A [Mono] of [GraphQLResponse] parses the response and gives easy access to data and errors.
*/
fun reactiveExecuteQuery(
@Language("graphql") query: String,
variables: Map<String, Any>,
operationName: String?
): Mono<GraphQLResponse>
@Deprecated(
"The RequestExecutor should be provided while creating the implementation. Use CustomGraphQLClient/CustomMonoGraphQLClient instead.",
ReplaceWith("Example: new CustomGraphQLClient(url, requestExecutor);")
)
fun reactiveExecuteQuery(
@Language("graphql") query: String,
variables: Map<String, Any>,
requestExecutor: MonoRequestExecutor
): Mono<GraphQLResponse> = throw UnsupportedOperationException()
@Deprecated(
"The RequestExecutor should be provided while creating the implementation. Use CustomGraphQLClient/CustomMonoGraphQLClient instead.",
ReplaceWith("Example: new CustomGraphQLClient(url, requestExecutor);")
)
fun reactiveExecuteQuery(
@Language("graphql") query: String,
variables: Map<String, Any>,
operationName: String?,
requestExecutor: MonoRequestExecutor
): Mono<GraphQLResponse> = throw UnsupportedOperationException()
companion object {
@JvmStatic
fun createCustomReactive(
@Language("url") url: String,
requestExecutor: MonoRequestExecutor
) = CustomMonoGraphQLClient(url, requestExecutor)
@JvmStatic
fun createWithWebClient(webClient: WebClient) = WebClientGraphQLClient(webClient)
@JvmStatic
fun createWithWebClient(webClient: WebClient, objectMapper: ObjectMapper) = WebClientGraphQLClient(webClient, objectMapper)
@JvmStatic
fun createWithWebClient(
webClient: WebClient,
headersConsumer: Consumer<HttpHeaders>
) = WebClientGraphQLClient(webClient, headersConsumer)
}
}
| 92 | null | 289 | 3,037 | bd2d0c524e70a9d1d625d518a94926c7b53a7e7c | 4,599 | dgs-framework | Apache License 2.0 |
app/src/main/java/com/zll/kotlin/extension/LogExtension.kt | neverwoodsS | 70,549,350 | false | null | package com.zll.kotlin.extension
import android.util.Log
import com.zll.kotlin.extension.debug
import java.util.concurrent.locks.Lock
/**
* Created by zhangll on 16/9/26.
*/
inline fun <reified T> T.log(log: Any) {
debug {
Log.i(T::class.simpleName, log.toString())
}
}
inline fun <reified T> T.warn(log: Any) {
debug {
Log.w(T::class.simpleName, log.toString())
}
}
inline fun <reified T> T.error(log: Any) {
debug {
Log.e(T::class.simpleName, log.toString())
}
} | 1 | null | 1 | 5 | 7550670488ca2c7711322dbe75e062b4be4fd4e5 | 518 | KotlinCommon | MIT License |
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/ConversationType.kt | slackapi | 62,449,869 | false | {"Java": 6165956, "Kotlin": 361122, "Shell": 7287, "Batchfile": 3120, "Dockerfile": 249} | package com.slack.api.model.kotlin_extension.block.element
enum class ConversationType {
/**
* A private message conversation directly between two people.
*/
IM {
override val value = "im"
},
/**
* A private message conversation created explicitly with a group of people.
*/
MULTIPARTY_IM {
override val value = "mpim"
},
/**
* A private slack channel.
*/
PRIVATE {
override val value = "private"
},
/**
* A public slack channel.
*/
PUBLIC {
override val value = "public"
};
abstract val value: String
} | 22 | Java | 214 | 577 | 52b04eb7ec1e97832d333e4ee96b7032b0203764 | 632 | java-slack-sdk | MIT License |
src/main/kotlin/io/kjson/yaml/YAML.kt | pwall567 | 405,294,122 | false | {"Kotlin": 150176} | /*
* @(#) YAML.kt
*
* kjson-yaml Kotlin YAML processor
* Copyright (c) 2020, 2021, 2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.kjson.yaml
import java.io.File
import java.io.InputStream
import java.io.Reader
import java.nio.charset.Charset
import io.kjson.yaml.parser.Parser
/**
* YAML library - a set of YAML parsing functions. The functions in this object delegate to the [Parser] class.
*
* @author <NAME>
*/
object YAML {
@Suppress("ConstPropertyName")
const val tagPrefix = "tag:yaml.org,2002:"
@Suppress("ConstPropertyName")
const val nullTag = "tag:yaml.org,2002:null"
@Suppress("ConstPropertyName")
const val mapTag = "tag:yaml.org,2002:map"
@Suppress("ConstPropertyName")
const val seqTag = "tag:yaml.org,2002:seq"
@Suppress("ConstPropertyName")
const val strTag = "tag:yaml.org,2002:str"
@Suppress("ConstPropertyName")
const val intTag = "tag:yaml.org,2002:int"
@Suppress("ConstPropertyName")
const val floatTag = "tag:yaml.org,2002:float"
@Suppress("ConstPropertyName")
const val boolTag = "tag:yaml.org,2002:bool"
val parser = Parser()
/**
* Parse a [File] as YAML.
*
* @param file the input [File]
* @param charset the [Charset], or `null` to specify that the charset is to be determined dynamically
* @return a [YAMLDocument]
*/
fun parse(file: File, charset: Charset? = null): YAMLDocument = parser.parse(file, charset)
/**
* Parse an [InputStream] as YAML.
*
* @param inputStream the input [InputStream]
* @param charset the [Charset], or `null` to specify that the charset is to be determined dynamically
* @return a [YAMLDocument]
*/
fun parse(inputStream: InputStream, charset: Charset? = null): YAMLDocument = parser.parse(inputStream, charset)
/**
* Parse a [Reader] as YAML.
*
* @param reader the input [Reader]
* @return a [YAMLDocument]
*/
fun parse(reader: Reader): YAMLDocument = parser.parse(reader)
/**
* Parse a [File] as a multi-document YAML stream.
*
* @param file the input [File]
* @param charset the [Charset], or `null` to specify that the charset is to be determined dynamically
* @return a [List] of [YAMLDocument]s
*/
fun parseStream(file: File, charset: Charset? = null): List<YAMLDocument> = parser.parseStream(file, charset)
/**
* Parse an [InputStream] as a multi-document YAML stream.
*
* @param inputStream the input [InputStream]
* @param charset the [Charset], or `null` to specify that the charset is to be determined dynamically
* @return a [List] of [YAMLDocument]s
*/
fun parseStream(inputStream: InputStream, charset: Charset? = null): List<YAMLDocument> =
parser.parseStream(inputStream, charset)
/**
* Parse a [Reader] as a multi-document YAML stream.
*
* @param reader the input [Reader]
* @return a [List] of [YAMLDocument]s
*/
fun parseStream(reader: Reader): List<YAMLDocument> = parser.parseStream(reader)
}
| 0 | Kotlin | 0 | 3 | 5f51c4baca32f7820b8d642d88af164802e2fe4d | 4,284 | kjson-yaml | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/ui/note/BadgeCompose.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.note
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MilitaryTech
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.R
import com.vitorpamplona.amethyst.ui.screen.BadgeCard
import com.vitorpamplona.amethyst.ui.screen.loggedIn.AccountViewModel
import com.vitorpamplona.amethyst.ui.theme.newItemBackgroundColor
import com.vitorpamplona.amethyst.ui.theme.placeholderText
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BadgeCompose(likeSetCard: BadgeCard, isInnerNote: Boolean = false, routeForLastRead: String, showHidden: Boolean = false, accountViewModel: AccountViewModel, nav: (String) -> Unit) {
val noteState by likeSetCard.note.live().metadata.observeAsState()
val note = noteState?.note
val context = LocalContext.current.applicationContext
val popupExpanded = remember { mutableStateOf(false) }
val enablePopup = remember {
{ popupExpanded.value = true }
}
val scope = rememberCoroutineScope()
if (note == null) {
BlankNote(Modifier, isInnerNote)
} else {
val defaultBackgroundColor = MaterialTheme.colorScheme.background
val backgroundColor = remember { mutableStateOf<Color>(defaultBackgroundColor) }
val newItemColor = MaterialTheme.colorScheme.newItemBackgroundColor
LaunchedEffect(key1 = likeSetCard) {
accountViewModel.loadAndMarkAsRead(routeForLastRead, likeSetCard.createdAt()) { isNew ->
val newBackgroundColor = if (isNew) {
newItemColor.compositeOver(defaultBackgroundColor)
} else {
defaultBackgroundColor
}
if (backgroundColor.value != newBackgroundColor) {
backgroundColor.value = newBackgroundColor
}
}
}
Column(
modifier = Modifier
.background(backgroundColor.value)
.combinedClickable(
onClick = {
scope.launch {
routeFor(
note,
accountViewModel.userProfile()
)?.let { nav(it) }
}
},
onLongClick = enablePopup
)
) {
Row(
modifier = Modifier
.padding(
start = if (!isInnerNote) 12.dp else 0.dp,
end = if (!isInnerNote) 12.dp else 0.dp,
top = 10.dp
)
) {
// Draws the like picture outside the boosted card.
if (!isInnerNote) {
Box(
modifier = Modifier
.width(55.dp)
.padding(0.dp)
) {
Icon(
imageVector = Icons.Default.MilitaryTech,
null,
modifier = Modifier
.size(25.dp)
.align(Alignment.TopEnd),
tint = MaterialTheme.colorScheme.primary
)
}
}
Column(modifier = Modifier.padding(start = if (!isInnerNote) 10.dp else 0.dp)) {
Row() {
Text(
stringResource(R.string.new_badge_award_notif),
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(bottom = 5.dp)
.weight(1f)
)
Text(
timeAgo(note.createdAt(), context = context),
color = MaterialTheme.colorScheme.placeholderText,
maxLines = 1
)
IconButton(
modifier = Modifier.then(Modifier.size(24.dp)),
onClick = enablePopup
) {
Icon(
imageVector = Icons.Default.MoreVert,
null,
modifier = Modifier.size(15.dp),
tint = MaterialTheme.colorScheme.placeholderText
)
NoteDropDownMenu(note, popupExpanded, accountViewModel)
}
}
note.replyTo?.firstOrNull()?.let {
NoteCompose(
baseNote = it,
routeForLastRead = null,
isBoostedNote = true,
showHidden = showHidden,
parentBackgroundColor = backgroundColor,
accountViewModel = accountViewModel,
nav = nav
)
}
Divider(
modifier = Modifier.padding(top = 10.dp),
thickness = 0.25.dp
)
}
}
}
}
}
| 157 | null | 141 | 981 | 2de3d19a34b97c012e39b203070d9c1c0b1f0520 | 6,915 | amethyst | MIT License |
app/src/main/java/com/example/roomdb/db/LocationDao.kt | bveenvliet | 374,549,383 | false | null | package com.example.roomdb.db
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
@Dao
interface LocationDao {
@Query("SELECT * FROM location")
fun getAll(): List<Location>
@Query("SELECT * FROM location WHERE id IN (:ids)")
fun getAll(ids: IntArray): List<Location>
@Query("SELECT * FROM location WHERE label LIKE :label")
fun getAll(label: String): List<Location>
@Insert
fun insertAll(vararg locations: Location)
@Delete
fun delete(location: Location)
} | 0 | Kotlin | 0 | 0 | ba2cab0d2ef0fee69d0f9befb27dd933832de03a | 559 | RoomDb | Apache License 2.0 |
token-client-core/src/main/kotlin/no/nav/security/token/support/client/core/OAuth2GrantType.kt | navikt | 124,397,000 | false | {"Kotlin": 363248} | package no.nav.security.token.support.client.core
import com.nimbusds.oauth2.sdk.GrantType
import kotlin.DeprecationLevel.WARNING
@Deprecated("Use GrantType from nimbus instead", ReplaceWith("GrantType"), WARNING)
data class OAuth2GrantType(val value : String) {
companion object {
@JvmField
@Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.JWT_BEARER"), WARNING)
val JWT_BEARER = GrantType(GrantType.JWT_BEARER.value)
@JvmField
@Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.CLIENT_CREDENTIALS"), WARNING)
val CLIENT_CREDENTIALS = GrantType(GrantType.CLIENT_CREDENTIALS.value)
@JvmField
@Deprecated("Use com.nimbusds.oauth2.sdk.GrantType instead", ReplaceWith("GrantType.TOKEN_EXCHANGE"), WARNING)
val TOKEN_EXCHANGE = GrantType(GrantType.TOKEN_EXCHANGE.value)
}
} | 8 | Kotlin | 7 | 15 | ce4dae36cfdd452cfbbe5477657bd2ea0ff1f346 | 916 | token-support | MIT License |
src/main/kotlin/me/yunleah/plugin/coldestiny/ColdEstiny.kt | Yunleah | 664,422,335 | false | null | package me.yunleah.plugin.coldestiny
import taboolib.common.platform.Plugin
import taboolib.module.configuration.Config
import taboolib.module.configuration.ConfigFile
import taboolib.platform.BukkitPlugin
object ColdEstiny : Plugin() {
const val KEY = "§3Cold§bEstiny"
val plugin by lazy { BukkitPlugin.getInstance() }
@Config("setting.yml", true)
lateinit var setting: ConfigFile
} | 0 | null | 0 | 2 | 45140895612ae0270911d108cc4394d0dce052b1 | 405 | ColdEstiny | MIT License |
core/network/src/main/java/com/danielefavaro/githubapiplayground/core/network/di/NetworkModule.kt | dfavaro | 645,763,005 | false | null | package com.danielefavaro.githubapiplayground.core.network.di
import android.content.Context
import com.danielefavaro.githubapiplayground.core.network.helper.ConnectivityManager
import com.danielefavaro.githubapiplayground.core.network.source.EnvironmentConfig
import com.danielefavaro.githubapiplayground.core.network.source.EnvironmentConfigImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import java.util.concurrent.TimeUnit
import javax.inject.Qualifier
import javax.inject.Singleton
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Qualifier
annotation class ApiAuthInterceptor
@Qualifier
annotation class ApiVersionInterceptor
@Qualifier
annotation class LoggingInterceptor
private const val BEARER_TOKEN_HEADER = "Authorization"
private const val API_VERSION_HEADER = "X-GitHub-Api-Version"
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideConnectivityManager(@ApplicationContext context: Context) = ConnectivityManager(
context = context
)
@Singleton
@Provides
fun provideEnvironmentConfig(@ApplicationContext context: Context): EnvironmentConfig =
EnvironmentConfigImpl(
context = context
)
@LoggingInterceptor
@Singleton
@Provides
fun provideLoggingInterceptor(environmentConfig: EnvironmentConfig): Interceptor =
HttpLoggingInterceptor().setLevel(environmentConfig.logLevel)
@ApiAuthInterceptor
@Singleton
@Provides
fun provideApiAuthInterceptor(environmentConfig: EnvironmentConfig): Interceptor =
Interceptor { chain ->
val request = chain.request()
.newBuilder()
.header(BEARER_TOKEN_HEADER, "Bearer ${environmentConfig.apiKey}")
.build()
chain.proceed(request)
}
@ApiVersionInterceptor
@Singleton
@Provides
fun provideApiVersionInterceptor(environmentConfig: EnvironmentConfig): Interceptor =
Interceptor { chain ->
val request = chain.request()
.newBuilder()
.header(API_VERSION_HEADER, environmentConfig.apiVersion)
.build()
chain.proceed(request)
}
@Singleton
@Provides
fun provideAuthOkHttpClient(
@ApiAuthInterceptor apiAuthInterceptor: Interceptor,
@ApiVersionInterceptor apiVersionInterceptor: Interceptor,
@LoggingInterceptor loggingInterceptor: Interceptor
): OkHttpClient = OkHttpClient.Builder().apply {
addInterceptor(apiAuthInterceptor)
addInterceptor(apiVersionInterceptor)
addInterceptor(loggingInterceptor)
readTimeout(30, TimeUnit.SECONDS)
writeTimeout(30, TimeUnit.SECONDS)
connectTimeout(30, TimeUnit.SECONDS)
}.build()
@Singleton
@Provides
fun provideRetrofitClient(
environmentConfig: EnvironmentConfig,
okHttpClient: OkHttpClient
): Retrofit = Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(environmentConfig.url)
.build()
}
| 0 | Kotlin | 0 | 0 | f11180d90e161d22eb50d08cc2d0624fe7a0c8da | 3,405 | github-api-playground-android | MIT License |
app/src/main/java/com/n27/elections/presentation/adapters/ElectionCardAdapter.kt | Narsuf | 52,900,182 | false | {"Kotlin": 246421} | package com.n27.elections.presentation.adapters
import DarkMode
import PieChart
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.compose.ui.platform.ComposeView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.n27.core.domain.election.models.Election
import com.n27.core.extensions.getPieChartData
import com.n27.core.extensions.isDarkModeEnabled
import com.n27.elections.R
typealias OnElectionClicked = (congressElection: Election, senateElection: Election) -> Unit
class ElectionCardAdapter(
internal val onElectionClicked: OnElectionClicked
) : RecyclerView.Adapter<ElectionCardAdapter.MyViewHolder>() {
internal var congressElections = listOf<Election>()
internal var senateElections = listOf<Election>()
class MyViewHolder(val card: CardView) : RecyclerView.ViewHolder(card)
fun updateItems(newCongressElections: List<Election>, newSenateElections: List<Election>) {
val diffCallback = ElectionsDiff(congressElections, newCongressElections)
val diffResult = DiffUtil.calculateDiff(diffCallback)
congressElections = newCongressElections
senateElections = newSenateElections
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val card = LayoutInflater.from(parent.context)
.inflate(R.layout.card_general_elections, parent, false) as CardView
return MyViewHolder(card)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val congressElection = congressElections[position]
val senateElection = senateElections[position]
val card = holder.card
card.findViewById<TextView>(R.id.year_card_general_elections).text = congressElection.date
card.setOnClickListener { onElectionClicked(congressElection, senateElection) }
(card.findViewById(R.id.pie_chart_card_general_elections) as ComposeView).setContent {
PieChart(
congressElection.results.getPieChartData(),
DarkMode(card.context.isDarkModeEnabled(), isLighterShade = true)
)
}
}
override fun getItemCount() = congressElections.size
}
| 0 | Kotlin | 0 | 2 | 73959e069dcd7166b9095f0b94cc3d0c42873c77 | 2,368 | Elections | Apache License 2.0 |
migrated-projects/KaMPKit/shared/test/co/touchlab/kampkit/SqlDelightTest.kt | JetBrains | 709,379,874 | false | null | package co.touchlab.kampkit
import co.touchlab.kampkit.db.Breed
import co.touchlab.kermit.Logger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class SqlDelightTest {
private lateinit var dbHelper: DatabaseHelper
private suspend fun DatabaseHelper.insertBreed(name: String) {
insertBreeds(listOf(Breed(id = 1, name = name, favorite = 0L)))
}
@BeforeTest
fun setup() = runTest {
dbHelper = DatabaseHelper(
testDbConnection(),
Logger,
Dispatchers.Default
)
dbHelper.deleteAll()
dbHelper.insertBreed("Beagle")
}
@Test
fun `Select All Items Success`() = runTest {
val breeds = dbHelper.selectAllItems().first()
assertNotNull(
breeds.find { it.name == "Beagle" },
"Could not retrieve Breed"
)
}
@Test
fun `Select Item by Id Success`() = runTest {
val breeds = dbHelper.selectAllItems().first()
val firstBreed = breeds.first()
assertNotNull(
dbHelper.selectById(firstBreed.id),
"Could not retrieve Breed by Id"
)
}
@Test
fun `Update Favorite Success`() = runTest {
val breeds = dbHelper.selectAllItems().first()
val firstBreed = breeds.first()
dbHelper.updateFavorite(firstBreed.id, true)
val newBreed = dbHelper.selectById(firstBreed.id).first().first()
assertNotNull(
newBreed,
"Could not retrieve Breed by Id"
)
assertTrue(
newBreed.isFavorited(),
"Favorite Did Not Save"
)
}
@Test
fun `Delete All Success`() = runTest {
dbHelper.insertBreed("Poodle")
dbHelper.insertBreed("Schnauzer")
assertTrue(dbHelper.selectAllItems().first().isNotEmpty())
dbHelper.deleteAll()
assertTrue(
dbHelper.selectAllItems().first().count() == 0,
"Delete All did not work"
)
}
}
| 7 | null | 4 | 988 | 6a2c7f0b86b36c85e9034f3de9bfe416516b323b | 2,216 | amper | Apache License 2.0 |
bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/SitePersistenceService.kt | eclipse-tractusx | 526,621,398 | false | null | /*******************************************************************************
* Copyright (c) 2021,2023 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.eclipse.tractusx.bpdm.gate.service
import org.eclipse.tractusx.bpdm.common.exception.BpdmNotFoundException
import org.eclipse.tractusx.bpdm.common.model.OutputInputEnum
import org.eclipse.tractusx.bpdm.common.util.replace
import org.eclipse.tractusx.bpdm.gate.api.model.LsaType
import org.eclipse.tractusx.bpdm.gate.api.model.request.SiteGateInputRequest
import org.eclipse.tractusx.bpdm.gate.api.model.request.SiteGateOutputRequest
import org.eclipse.tractusx.bpdm.gate.entity.*
import org.eclipse.tractusx.bpdm.gate.repository.ChangelogRepository
import org.eclipse.tractusx.bpdm.gate.repository.GateAddressRepository
import org.eclipse.tractusx.bpdm.gate.repository.LegalEntityRepository
import org.eclipse.tractusx.bpdm.gate.repository.SiteRepository
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
@Service
class SitePersistenceService(
private val siteRepository: SiteRepository,
private val legalEntityRepository: LegalEntityRepository,
private val addressRepository: GateAddressRepository,
private val changelogRepository: ChangelogRepository
) {
@Transactional
fun persistSitesBP(sites: Collection<SiteGateInputRequest>, datatype: OutputInputEnum) {
//Finds Site in DB
val siteRecord = siteRepository.findByExternalIdIn(sites.map { it.externalId })
sites.forEach { site ->
val legalEntityRecord = getLegalEntityRecord(site.legalEntityExternalId, datatype)
val fullSite = site.toSiteGate(legalEntityRecord, datatype)
siteRecord.find { it.externalId == site.externalId && it.dataType == datatype }?.let { existingSite ->
val logisticAddressRecord = getAddressRecord(getMainAddressForSiteExternalId(site.externalId), datatype)
updateAddress(logisticAddressRecord, fullSite.mainAddress)
updateSite(existingSite, site, legalEntityRecord)
siteRepository.save(existingSite)
saveChangelog(site.externalId, datatype)
} ?: run {
siteRepository.save(fullSite)
saveChangelog(site.externalId, datatype)
}
}
}
//Creates Changelog For both Site and Logistic Address when they are created or updated
private fun saveChangelog(externalId: String, outputInputEnum: OutputInputEnum) {
changelogRepository.save(ChangelogEntry(getMainAddressForSiteExternalId(externalId), LsaType.ADDRESS, outputInputEnum))
changelogRepository.save(ChangelogEntry(externalId, LsaType.SITE, outputInputEnum))
}
private fun getAddressRecord(externalId: String, datatype: OutputInputEnum): LogisticAddress {
return addressRepository.findByExternalIdAndDataType(externalId, datatype)
?: throw BpdmNotFoundException("Business Partner", "Error")
}
private fun getLegalEntityRecord(externalId: String, datatype: OutputInputEnum): LegalEntity {
return legalEntityRepository.findByExternalIdAndDataType(externalId, datatype)
?: throw BpdmNotFoundException("Business Partner", externalId)
}
private fun updateSite(site: Site, updatedSite: SiteGateInputRequest, legalEntityRecord: LegalEntity) {
site.externalId = updatedSite.externalId
site.legalEntity = legalEntityRecord
site.states.replace(updatedSite.site.states.map { toEntityAddress(it, site) })
site.nameParts.replace(updatedSite.site.nameParts.map { toNameParts(it, null, site, null) })
site.roles.replace(updatedSite.site.roles.distinct().map { toRoles(it, null, site, null) })
}
private fun updateAddress(address: LogisticAddress, changeAddress: LogisticAddress) {
address.externalId = changeAddress.externalId
address.legalEntity = changeAddress.legalEntity
address.physicalPostalAddress = changeAddress.physicalPostalAddress
address.alternativePostalAddress = changeAddress.alternativePostalAddress
address.states.replace(changeAddress.states.map { toEntityAddress(it, address) })
address.nameParts.replace(changeAddress.nameParts.map { toNameParts(it.namePart, address, null, null) })
address.roles.replace(changeAddress.roles.distinct().map { toRoles(it.roleName, null, null, address) })
}
fun toEntityAddress(dto: AddressState, address: LogisticAddress): AddressState {
return AddressState(dto.description, dto.validFrom, dto.validTo, dto.type, address)
}
@Transactional
fun persistSitesOutputBP(sites: Collection<SiteGateOutputRequest>, datatype: OutputInputEnum) {
//Finds Site in DB
val siteRecord = siteRepository.findByExternalIdIn(sites.map { it.externalId })
sites.forEach { site ->
val legalEntityRecord = getLegalEntityRecord(site.legalEntityExternalId, datatype)
val fullSite = site.toSiteGate(legalEntityRecord, datatype)
siteRecord.find { it.externalId == site.externalId && it.dataType == datatype }?.let { existingSite ->
val logisticAddressRecord = getAddressRecord(getMainAddressForSiteExternalId(site.externalId), datatype)
updateAddress(logisticAddressRecord, fullSite.mainAddress)
updateSiteOutput(existingSite, site, legalEntityRecord)
siteRepository.save(existingSite)
saveChangelog(site.externalId, datatype)
} ?: run {
if (siteRecord.find { it.externalId == fullSite.externalId && it.dataType == OutputInputEnum.Input } == null) {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Input Site doesn't exist")
} else {
siteRepository.save(fullSite)
saveChangelog(site.externalId, datatype)
}
}
}
}
private fun updateSiteOutput(site: Site, updatedSite: SiteGateOutputRequest, legalEntityRecord: LegalEntity) {
site.bpn = updatedSite.bpn
site.externalId = updatedSite.externalId
site.legalEntity = legalEntityRecord
site.states.replace(updatedSite.site.states.map { toEntityAddress(it, site) })
site.nameParts.replace(updatedSite.site.nameParts.map { toNameParts(it, null, site, null) })
site.roles.replace(updatedSite.site.roles.distinct().map { toRoles(it, null, site, null) })
}
} | 44 | null | 9 | 5 | 88b7972b1e08d1498a40d048168a32bc13fcbe5a | 7,443 | bpdm | Apache License 2.0 |
app/src/main/java/com/github/programmerr47/flickrawesomeclient/util/common.kt | programmerr47 | 147,911,795 | false | null | package com.github.programmerr47.flickrawesomeclient.util
import android.content.res.TypedArray
inline fun <T: TypedArray> T.use(block: T.() -> Unit) {
try {
block()
} finally {
recycle()
}
} | 7 | Kotlin | 2 | 12 | 33650da75f5bc1bf5ef27192f92349293c049329 | 221 | flickr-test-app | MIT License |
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/OptionalSemicolon.kt | yongzx | 103,536,932 | true | {"Gradle": 13, "YAML": 14, "Markdown": 5, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "XML": 4, "Groovy": 1, "Kotlin": 267, "Java": 1, "Java Properties": 1} | package io.gitlab.arturbosch.detekt.formatting
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.TokenRule
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
/**
* @author <NAME>
*/
class OptionalSemicolon(config: Config = Config.empty) : TokenRule(config) {
override val issue = Issue(javaClass.simpleName, Severity.Style, "", Debt.FIVE_MINS)
override fun visitSemicolon(leaf: LeafPsiElement) {
if (leaf.isNotPartOfEnum() && leaf.isNotPartOfString()) {
val nextLeaf = leaf.nextLeaf()
if (nextLeaf.isSemicolonOrEOF() || nextTokenHasSpaces(nextLeaf)) {
report(CodeSmell(issue, Entity.from(leaf)))
withAutoCorrect { leaf.delete() }
}
}
}
override fun visitDoubleSemicolon(leaf: LeafPsiElement) {
if (leaf.isNotPartOfEnum() && leaf.isNotPartOfString()) {
report(CodeSmell(issue, Entity.from(leaf)))
withAutoCorrect {
deleteOneOrTwoSemicolons(leaf)
}
}
}
private fun deleteOneOrTwoSemicolons(node: LeafPsiElement) {
val nextLeaf = node.nextLeaf()
if (nextLeaf.isSemicolonOrEOF() || nextTokenHasSpaces(nextLeaf)) {
node.delete()
} else {
node.replaceWithText(";")
}
}
private fun nextTokenHasSpaces(leaf: PsiElement?) = leaf is PsiWhiteSpace &&
(leaf.isNewLine() || leaf.nextLeaf().isSemicolonOrEOF())
private fun PsiElement?.isSemicolonOrEOF() = this == null || isSemicolon() || isDoubleSemicolon()
}
| 0 | Kotlin | 2 | 0 | 95857d9d64888a42d8bf6ade0e5eb5adcc28a32c | 1,830 | detekt-old | Apache License 2.0 |
app/src/main/java/com/example/bmicalculator/WelcomeActivity.kt | math-nazario | 796,425,347 | false | {"Kotlin": 6083} | package com.example.bmicalculator
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class WelcomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_welcome)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val btnStart: Button = findViewById(R.id.btnStart)
btnStart.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
} | 0 | Kotlin | 0 | 0 | 3c4e91177d436233c66ea7835267532c5495241e | 1,048 | bmiCalculator | MIT License |
src/test/kotlin/g3201_3300/s3255_find_the_power_of_k_size_subarrays_ii/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g3201_3300.s3254_find_the_power_of_k_size_subarrays_i
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun resultsArray() {
assertThat(
Solution().resultsArray(intArrayOf(1, 2, 3, 4, 3, 2, 5), 3),
equalTo(intArrayOf(3, 4, -1, -1, -1))
)
}
@Test
fun resultsArray2() {
assertThat(
Solution().resultsArray(intArrayOf(2, 2, 2, 2, 2), 4),
equalTo(intArrayOf(-1, -1))
)
}
@Test
fun resultsArray3() {
assertThat(
Solution().resultsArray(intArrayOf(3, 2, 3, 2, 3, 2), 2),
equalTo(intArrayOf(-1, 3, -1, 3, -1))
)
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 783 | LeetCode-in-Kotlin | MIT License |
client/src/commonTest/kotlin/documentation/methods/apikey/DocDeleteAPIKey.kt | algolia | 153,273,215 | false | null | package documentation.methods.apikey
import com.algolia.search.model.APIKey
import documentation.client
import kotlinx.coroutines.test.runTest
import kotlin.test.Ignore
import kotlin.test.Test
@Ignore
internal class DocDeleteAPIKey {
// suspend fun ClientSearch.deleteAPIKey(
// #{apiKey}: __APIKey__,
// requestOptions: __RequestOptions?__ = null
// ): DeletionAPIKey
//
// data class APIKeyParams(
// val [ACLs](#method-param-acl): __List<ACL>?__ = null,
// val [indices](#method-param-indexes): __List<IndexName>?__ = null,
// val #{description}: __String?__ = null,
// val #{maxHitsPerQuery}: __Int?__ = null,
// val #{maxQueriesPerIPPerHour}: __Int?__ = null,
// val #{validity}: __Long?__ = null,
// val [query](#method-param-queryparameters): __Query?__ = null,
// val #{referers}: __List<String>?__ = null
// )
@Test
fun snippet1() {
runTest {
client.deleteAPIKey(APIKey("f420238212c54dcfad07ea0aa6d5c45f"))
}
}
}
| 8 | null | 23 | 59 | 21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4 | 1,048 | algoliasearch-client-kotlin | MIT License |
components/flow/flow-service/src/main/kotlin/net/corda/flow/pipeline/runner/impl/RemoteToLocalContextMapper.kt | corda | 346,070,752 | false | null | package net.corda.flow.pipeline.runner.impl
import net.corda.data.KeyValuePairList
import net.corda.flow.utils.KeyValueStore
import net.corda.flow.utils.toMap
/**
* Map context properties sent from an initiating remote party into context properties presented to initiated user code.
* Whilst context is propagated down the chain of flows, it can be tweaked across the initiating/initiated flow
* boundaries by Corda. The context presented to user code in an initiated flow does not need to be an exact replica of
* context from the initiating party. On top of this, the local session passed to initiated flows contains context
* relating only to the counterparty which initiated it and not the "main" context of the executing flow.
*
* @param remoteUserContextProperties User context properties from the remote initiating party
* @param remotePlatformContextProperties Platform context properties from the remote initiating party
* @return Context properties translated to a local context
*/
fun remoteToLocalContextMapper(
remoteUserContextProperties: KeyValuePairList,
remotePlatformContextProperties: KeyValuePairList,
localCounterpartyContext: Map<String, String>
): LocalContext {
// replace 'corda.' with 'corda.initiator.'
val initiatorPlatformContextProperties = renameInitiatorProps(remotePlatformContextProperties, localCounterpartyContext)
return LocalContext(
userProperties = renameInitiatorProps(remoteUserContextProperties, emptyMap()),
platformProperties = initiatorPlatformContextProperties,
counterpartySessionProperties = initiatorPlatformContextProperties.toMap()
)
}
/**
* Rename the properties sent from the initiating remote party to include the 'initiator' identifier.
* This will only rename one level deep.
* e.g. we wont see corda.initiator.initiator
*
* @param keyValuePairList A KVP List that will have the keys renamed.
* @return The newly re-keyed KVP List
*/
@Suppress("NestedBlockDepth")
fun renameInitiatorProps(keyValuePairList: KeyValuePairList, localCounterpartyContext: Map<String, String>)
= KeyValueStore().apply {
keyValuePairList.items.forEach { kvp ->
if (!kvp.key.startsWith("corda.initiator")) {
if (kvp.key.startsWith("corda.")) {
this[kvp.key.replace("corda.", "corda.initiator.")] = kvp.value
} else {
this[kvp.key] = kvp.value
}
}
}
// local values should override conflicting things coming over the wire
localCounterpartyContext.forEach{ (k, v) -> this[k] = v}
}.avro
/**
* User and platform properties live in the domain of the checkpoint, hence they must be modelled by avro types.
* Session properties are passed to initiated flows and always live on the stack, so must be managed as Kotlin types
* that can be kryo serialized.
*/
data class LocalContext(
val userProperties: KeyValuePairList,
val platformProperties: KeyValuePairList,
val counterpartySessionProperties: Map<String, String>
)
| 120 | null | 13 | 39 | 9790d4f101f2fd8aecc9d083f8a61c21efe089e7 | 3,039 | corda-runtime-os | Apache License 2.0 |
app/src/main/java/top/roy1994/bilimusic/data/objects/sheet/SheetEntity.kt | MoveCloudROY | 583,275,245 | false | {"Kotlin": 217608} | package top.roy1994.bilimusic.data.objects.sheet
import androidx.compose.ui.graphics.painter.Painter
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import java.io.FileDescriptor
@Entity
data class SheetEntity (
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "sheet_id")
val sheet_id: Int = 0,
@ColumnInfo(name = "sheet_name")
val sheet_name: String,
@ColumnInfo(name = "sheet_description")
val sheet_description: String = " ",
) {
@Ignore
var cover: Painter? = null
companion object {
fun GetDefault(): SheetEntity {
return SheetEntity(
sheet_id = 0,
sheet_name = " ",
sheet_description = " ",
)
}
}
} | 1 | Kotlin | 1 | 5 | dc60ebde773a810c646328f17b21fa3d71ac1f23 | 813 | BiliMusic | MIT License |
app/src/main/java/com/example/gymlog/ui/form/ExerciseForm.kt | LucasMelll0 | 635,043,401 | false | {"Kotlin": 350707} | package com.example.gymlog.ui.form
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.core.text.isDigitsOnly
import com.example.gymlog.R
import com.example.gymlog.extensions.isZeroOrEmpty
import com.example.gymlog.model.Exercise
import com.example.gymlog.ui.components.DefaultOutlinedTextField
import com.example.gymlog.ui.components.FilterChipSelectionList
import com.example.gymlog.ui.theme.GymLogTheme
import com.example.gymlog.utils.TrainingTypes
@Composable
fun ExerciseForm(
onDismiss: () -> Unit,
onExit: () -> Unit,
onConfirm: (Exercise) -> Unit,
modifier: Modifier = Modifier,
exerciseToEdit: Exercise? = null
) {
val context = LocalContext.current
val filtersIsEmptyMessage = stringResource(id = R.string.exercise_form_filters_is_empty_toast_message)
var title by rememberSaveable { mutableStateOf("") }
var series: String by rememberSaveable { mutableStateOf("") }
var repetitions: String by rememberSaveable { mutableStateOf("") }
var observations: String by rememberSaveable { mutableStateOf("") }
val filters = remember { mutableStateListOf<String>() }
var titleHasError by remember { mutableStateOf(false) }
var seriesHasError by remember { mutableStateOf(false) }
var repetitionsHasError by remember { mutableStateOf(false) }
exerciseToEdit?.let {
title = it.title
series = it.series.toString()
repetitions = it.repetitions.toString()
observations = it.observations
filters.clear()
filters.addAll(it.filters)
}
Dialog(
onDismissRequest = { onDismiss() }, properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false,
usePlatformDefaultWidth = false
)
) {
Card(
shape = RoundedCornerShape(10.dp),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
modifier = modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(dimensionResource(id = R.dimen.default_padding))
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.default_padding))
.verticalScroll(rememberScrollState())
) {
Text(
text = stringResource(id = R.string.exercise_form_title),
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(vertical = dimensionResource(id = R.dimen.default_padding))
)
DefaultOutlinedTextField(
value = title,
onValueChange = { newTitle -> title = newTitle },
label = {
Text(
text = stringResource(id = R.string.exercise_name_label)
)
},
modifier = Modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.default_padding)),
isError = titleHasError,
errorMessage = stringResource(id = R.string.common_text_field_error_message),
charLimit = 30,
keyboardOptions = KeyboardOptions.Default.copy(capitalization = KeyboardCapitalization.Sentences)
)
Row(
horizontalArrangement = Arrangement.SpaceAround,
) {
DefaultOutlinedTextField(
value = series,
onValueChange = {
if (it.isDigitsOnly()) {
series = it
}
},
label = {
Text(stringResource(id = R.string.exercise_series_label))
},
modifier = Modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.default_padding))
.weight(1f),
isError = seriesHasError,
errorMessage = stringResource(id = R.string.series_text_field_error_message),
charLimit = 3,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
DefaultOutlinedTextField(
value = repetitions,
onValueChange = {
if (it.isDigitsOnly()) {
repetitions = it
}
},
label = {
Text(text = stringResource(id = R.string.exercise_repetitions_label))
},
modifier = Modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.default_padding))
.weight(1f),
isError = repetitionsHasError,
errorMessage = stringResource(id = R.string.repetitions_text_field_error_message),
charLimit = 3,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
}
DefaultOutlinedTextField(
value = observations,
onValueChange = { observations = it },
label = {
Text(text = stringResource(id = R.string.exercise_form_observations_place_holder))
},
modifier = Modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.default_padding)),
charLimit = 200
)
FilterChipSelectionList(
modifier = Modifier.padding(vertical = dimensionResource(id = R.dimen.default_padding)),
selectedList = filters,
filterList = TrainingTypes.values()
.map { stringResource(id = it.stringRes()) },
onClick = { selected ->
filters.find { it == selected }?.let {
filters.remove(selected)
} ?: run {
filters.add(selected)
}
},
description = "Marque as partes do corpo que esse exercício abrange"
)
Row(horizontalArrangement = Arrangement.SpaceBetween) {
Button(
onClick = { onExit() },
Modifier
.fillMaxWidth()
.padding(
dimensionResource(
id = R.dimen.default_padding
)
)
.weight(1f)
) {
Text(text = stringResource(id = R.string.common_cancel))
}
Button(
onClick = {
titleHasError = title.isEmpty()
seriesHasError = series.isZeroOrEmpty()
repetitionsHasError = repetitions.isZeroOrEmpty()
if (filters.isEmpty()) {
Toast.makeText(
context,
filtersIsEmptyMessage,
Toast.LENGTH_LONG
).show()
} else {
if (!titleHasError &&
!seriesHasError &&
!repetitionsHasError
) {
val exercise = Exercise(
title = title,
series = series.toInt(),
repetitions = repetitions.toInt(),
observations = observations,
filters = filters
)
onConfirm(exercise)
}
}
},
Modifier
.fillMaxWidth()
.padding(
dimensionResource(
id = R.dimen.default_padding
)
)
.weight(1.3f)
) {
Text(text = stringResource(id = R.string.common_confirm))
}
}
}
}
}
}
@Preview(name = "Night Mode", uiMode = UI_MODE_NIGHT_YES, showSystemUi = true)
@Preview()
@Composable
private fun ExerciseFormPreview() {
var showDialog by remember { mutableStateOf(true) }
GymLogTheme {
if (showDialog) {
ExerciseForm(onDismiss = { showDialog = false },
onExit = { showDialog = false },
onConfirm = {
showDialog = false
Log.i("Test", "ExerciseFormPreview: $it")
})
}
}
} | 0 | Kotlin | 0 | 1 | 7ab200245fbd83e1401c338ee81216e07d8e206f | 11,471 | GymLog | Apache License 2.0 |
core/src/main/java/com/github/stephenvinouze/materialnumberpickercore/MaterialNumberPicker.kt | StephenVinouze | 104,866,857 | false | null | package com.github.stephenvinouze.materialnumberpickercore
import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import android.support.v4.content.res.ResourcesCompat
import android.text.InputType
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.EditText
import android.widget.NumberPicker
/**
* Created by stephenvinouze on 25/09/2017.
*/
class MaterialNumberPicker : NumberPicker {
companion object {
private const val DEFAULT_VALUE = 1
private const val MAX_VALUE = 10
private const val DEFAULT_SEPARATOR_COLOR = Color.TRANSPARENT
private const val DEFAULT_TEXT_COLOR = Color.BLACK
private const val DEFAULT_TEXT_SIZE = 40
private const val DEFAULT_TEXT_STYLE = Typeface.NORMAL
private const val DEFAULT_EDITABLE = false
private const val DEFAULT_WRAPPED = false
}
var separatorColor: Int = Color.TRANSPARENT
set(value) {
field = value
divider?.colorFilter = PorterDuffColorFilter(separatorColor, PorterDuff.Mode.SRC_IN)
}
var textColor: Int = DEFAULT_TEXT_COLOR
set(value) {
field = value
updateTextAttributes()
}
var textStyle: Int = DEFAULT_TEXT_STYLE
set(value) {
field = value
updateTextAttributes()
}
var textSize: Int = DEFAULT_TEXT_SIZE
set(value) {
field = value
updateTextAttributes()
}
var editable: Boolean = DEFAULT_EDITABLE
set(value) {
field = value
descendantFocusability = if (value) ViewGroup.FOCUS_AFTER_DESCENDANTS else ViewGroup.FOCUS_BLOCK_DESCENDANTS
}
var fontName: String? = null
set(value) {
field = value
updateTextAttributes()
}
var fontFamily: Int? = null
set(value) {
field = value
updateTextAttributes()
}
private val inputEditText: EditText? by lazy {
try {
val f = NumberPicker::class.java.getDeclaredField("mInputText")
f.isAccessible = true
f.get(this) as EditText
} catch (e: Exception) {
null
}
}
private val wheelPaint: Paint? by lazy {
try {
val selectorWheelPaintField = NumberPicker::class.java.getDeclaredField("mSelectorWheelPaint")
selectorWheelPaintField.isAccessible = true
selectorWheelPaintField.get(this) as Paint
} catch (e: Exception) {
null
}
}
private val divider: Drawable? by lazy {
val dividerField = NumberPicker::class.java.declaredFields.firstOrNull { it.name == "mSelectionDivider" }
dividerField?.let {
try {
it.isAccessible = true
it.get(this) as Drawable
} catch (e: Exception) {
null
}
}
}
@JvmOverloads
constructor(context: Context,
minValue: Int = DEFAULT_VALUE,
maxValue: Int = MAX_VALUE,
value: Int = DEFAULT_VALUE,
separatorColor: Int = DEFAULT_SEPARATOR_COLOR,
textColor: Int = DEFAULT_TEXT_COLOR,
textSize: Int = DEFAULT_TEXT_SIZE,
textStyle: Int = DEFAULT_TEXT_STYLE,
editable: Boolean = DEFAULT_EDITABLE,
wrapped: Boolean = DEFAULT_WRAPPED,
fontName: String? = null,
fontFamily: Int? = null,
formatter: Formatter? = null
) : super(context) {
this.minValue = minValue
this.maxValue = maxValue
this.value = value
this.separatorColor = separatorColor
this.textColor = textColor
this.textSize = textSize
this.textStyle = textStyle
this.fontName = fontName
this.fontFamily = fontFamily
this.editable = editable
this.wrapSelectorWheel = wrapped
setFormatter(formatter)
disableFocusability()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.MaterialNumberPicker, 0, 0)
minValue = a.getInteger(R.styleable.MaterialNumberPicker_mnpMinValue, DEFAULT_VALUE)
maxValue = a.getInteger(R.styleable.MaterialNumberPicker_mnpMaxValue, MAX_VALUE)
value = a.getInteger(R.styleable.MaterialNumberPicker_mnpValue, DEFAULT_VALUE)
separatorColor = a.getColor(R.styleable.MaterialNumberPicker_mnpSeparatorColor, DEFAULT_SEPARATOR_COLOR)
textColor = a.getColor(R.styleable.MaterialNumberPicker_mnpTextColor, DEFAULT_TEXT_COLOR)
textSize = a.getDimensionPixelSize(R.styleable.MaterialNumberPicker_mnpTextSize, DEFAULT_TEXT_SIZE)
textStyle = a.getInt(R.styleable.MaterialNumberPicker_mnpTextColor, DEFAULT_TEXT_STYLE)
editable = a.getBoolean(R.styleable.MaterialNumberPicker_mnpEditable, DEFAULT_EDITABLE)
wrapSelectorWheel = a.getBoolean(R.styleable.MaterialNumberPicker_mnpWrapped, DEFAULT_WRAPPED)
fontName = a.getString(R.styleable.MaterialNumberPicker_mnpFontName)
fontFamily = a.getResourceId(R.styleable.MaterialNumberPicker_mnpFontFamily, 0)
a.recycle()
disableFocusability()
}
/**
* Disable focusability of edit text embedded inside the number picker
* We also override the edit text filter private attribute by using reflection as the formatter is still buggy while attempting to display the default value
* This is still an open Google @see <a href="https://code.google.com/p/android/issues/detail?id=35482#c9">issue</a> from 2012
*/
private fun disableFocusability() {
inputEditText?.filters = arrayOfNulls(0)
}
/**
* Uses reflection to access text size private attribute for both wheel and edit text inside the number picker.
*/
private fun updateTextAttributes() {
val typeface = when {
fontFamily != null && fontFamily != 0 -> try {
ResourcesCompat.getFont(context, fontFamily!!)
} catch (e: Throwable) {
null
}
fontName != null -> Typeface.createFromAsset(context.assets, "fonts/$fontName")
else -> Typeface.create(Typeface.DEFAULT, textStyle)
}
wheelPaint?.let { paint ->
paint.color = textColor
paint.textSize = textSize.toFloat()
paint.typeface = typeface
val childEditText = (0 until childCount).map { getChildAt(it) as? EditText }.firstOrNull()
childEditText?.let {
it.setTextColor(textColor)
it.setTextSize(TypedValue.COMPLEX_UNIT_SP, pixelsToSp(context, textSize.toFloat()))
it.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_NORMAL
it.typeface = typeface
invalidate()
}
}
}
private fun pixelsToSp(context: Context, px: Float): Float =
px / context.resources.displayMetrics.scaledDensity
} | 8 | null | 20 | 129 | 2f1fb560f7881007acc6ab1ee519e2a25814ae26 | 7,263 | MaterialNumberPicker | Apache License 2.0 |
src/main/kotlin/nstda/hii/webservice/app/webresponsefilter/SuccessToCreatedResponse.kt | hii-in-th | 262,977,721 | false | null | /*
* Copyright (c) 2019 NSTDA
* National Science and Technology Development Agency, Thailand
*
* 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 hii.thing.api.config.responsefilter
import javax.annotation.Priority
import javax.ws.rs.HttpMethod
import javax.ws.rs.Priorities
import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerResponseContext
import javax.ws.rs.container.ContainerResponseFilter
import javax.ws.rs.ext.Provider
/**
* หาก client POST เข้ามาแล้วสำเร็จ ให้ส่งกลับเป็น 201
*/
@Suppress("UNUSED_VARIABLE")
@Priority(Priorities.HEADER_DECORATOR)
@Provider
class SuccessToCreatedResponse : ContainerResponseFilter {
override fun filter(
requestContext: ContainerRequestContext,
responseContext: ContainerResponseContext
) {
val isPost = requestContext.method == HttpMethod.POST
if (isPost && responseContext.status == 200) {
responseContext.status = 201
}
}
}
| 0 | Kotlin | 0 | 0 | 1178c5934b5694c2e5ccd4b303be34e23e1be017 | 1,499 | thing-api | MIT License |
chrome/index.chrome.fileBrowserHandler.module_chrome.kt | yokiano | 376,563,863 | false | null | @file:JsQualifier("chrome.fileBrowserHandler")
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
package chrome.fileBrowserHandler
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
import chrome.events.Event
external interface SelectionParams {
var allowedFileExtensions: Array<String>?
get() = definedExternally
set(value) = definedExternally
var suggestedName: String
}
external interface SelectionResult {
var entry: Any?
get() = definedExternally
set(value) = definedExternally
var success: Boolean
}
external interface FileHandlerExecuteEventDetails {
var tab_id: Number?
get() = definedExternally
set(value) = definedExternally
var entries: Array<Any>
}
external interface FileBrowserHandlerExecuteEvent : Event<(id: String, details: FileHandlerExecuteEventDetails) -> Unit>
external fun selectFile(selectionParams: SelectionParams, callback: (result: SelectionResult) -> Unit)
external var onExecute: FileBrowserHandlerExecuteEvent | 1 | Kotlin | 0 | 1 | 3be9b231f1c883d205ac9567465a342176a3d895 | 1,375 | chrome-extension-kt-types | MIT License |
src/main/kotlin/com/github/artem1458/dicatplugin/utils/addIfNotNull.kt | artem1458 | 502,715,386 | false | {"Kotlin": 60014} | package com.github.artem1458.dicatplugin.utils
fun <T> MutableCollection<T>.addIfNotNull(e: T?) {
e?.let(::add)
}
| 0 | Kotlin | 0 | 0 | 1a1f2d094e046a60d71644c6c3ef5a6479c54178 | 117 | di-cat-intellij-plugin | Apache License 2.0 |
Echo/src/main/java/com/redelf/commons/interprocess/echo/EchoInterprocessProcessor.kt | red-elf | 731,934,432 | false | {"Kotlin": 894931, "Java": 41189, "Shell": 3294} | package com.redelf.commons.interprocess.echo
import android.content.Context
import android.content.Intent
import com.redelf.commons.extensions.toast
import com.redelf.commons.interprocess.InterprocessData
import com.redelf.commons.interprocess.InterprocessProcessor
import com.redelf.commons.logging.Console
class EchoInterprocessProcessor(private val ctx: Context) : InterprocessProcessor() {
companion object {
const val ACTION_ECHO = "com.redelf.commons.interprocess.echo"
const val ACTION_HELLO = "com.redelf.commons.interprocess.echo.hello"
const val ACTION_ECHO_RESPONSE = "com.redelf.commons.interprocess.echo.response"
}
private val echo = "Echo"
private val tag = "IPC :: Processor :: $echo ::"
init {
Console.log("$tag Created")
}
override fun onData(data: InterprocessData) {
Console.log("$tag Received data: $data")
val function = data.function
when (function) {
ACTION_HELLO -> hello()
ACTION_ECHO -> echo(data.content ?: "")
}
}
private fun hello() {
val msg = "Hello from the Echo IPC"
Console.log("$tag $msg")
ctx.toast(msg)
}
private fun echo(message: String) {
Console.log("$tag Request :: $message")
val responseIntent = Intent(ACTION_ECHO_RESPONSE)
responseIntent.putExtra(InterprocessData.BUNDLE_KEY, "$echo = $message")
ctx.applicationContext.sendBroadcast(responseIntent)
Console.log("$tag Response :: $message")
}
} | 0 | Kotlin | 1 | 0 | a9caa4bd72523a5514d6c4275d4c919befe5642a | 1,560 | Android-Toolkit | Apache License 2.0 |
src/main/kotlin/com/workos/mfa/models/VerifyFactorResponse.kt | workos | 419,780,611 | false | null | package com.workos.mfa.models
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Represents a [VerifyFactorResponse] in both successfull and error responses.
*/
@Deprecated("Please use `verifyChallenge` instead")
data class VerifyFactorResponse
@JsonCreator constructor(
@JvmField
@JsonProperty("challenge")
val challenge: Challenge,
@JvmField
@JsonProperty("valid")
val valid: Boolean
)
| 2 | null | 6 | 9 | 8be0571a48e643cea2f0c783ddb4c5fa79be1ed5 | 466 | workos-kotlin | MIT License |
compiler/testData/codegen/box/intrinsics/kt12125.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND_FIR: JVM_IR
fun test(i: Int): Int {
return i
}
fun box(): String {
var b = Byte.MAX_VALUE
b++
var result = test(b.toInt())
if (result != Byte.MIN_VALUE.toInt()) return "fail 1: $result"
var s = Short.MIN_VALUE
s--
result = test(s.toInt())
if (result != Short.MAX_VALUE.toInt()) return "fail 2: $result"
return "OK"
} | 179 | null | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 377 | kotlin | Apache License 2.0 |
serialization/core/src/main/kotlin/io/github/airflux/serialization/core/Deserialization.kt | airflux | 336,002,943 | false | {"Kotlin": 916634} | /*
* Copyright 2021-2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.airflux.serialization.core
import io.github.airflux.serialization.core.context.JsContext
import io.github.airflux.serialization.core.location.JsLocation
import io.github.airflux.serialization.core.reader.JsReader
import io.github.airflux.serialization.core.reader.env.JsReaderEnv
import io.github.airflux.serialization.core.reader.result.JsReaderResult
import io.github.airflux.serialization.core.value.JsValue
public fun <EB, O, T : Any> JsValue.deserialization(
env: JsReaderEnv<EB, O>,
context: JsContext,
reader: JsReader<EB, O, T>
): JsReaderResult<T> =
reader.read(env, context, JsLocation, this)
| 0 | Kotlin | 3 | 4 | f80bf604fbfe10ed8c2667abe31d9af06f794fb4 | 1,238 | airflux-serialization | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/balance/BalanceSortType.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.modules.balance
import io.horizontalsystems.bankwallet.R
sealed class BalanceSortType {
object Name : BalanceSortType()
object Value : BalanceSortType()
object PercentGrowth : BalanceSortType()
fun getTitleRes(): Int = when (this) {
Value -> R.string.Balance_Sort_Balance
Name -> R.string.Balance_Sort_Az
PercentGrowth -> R.string.Balance_Sort_24hPriceChange
}
fun getAsString(): String = when (this) {
Value -> "value"
Name -> "name"
PercentGrowth -> "percent_growth"
}
companion object {
fun getTypeFromString(value: String): BalanceSortType = when (value) {
"value" -> Value
"percent_growth" -> PercentGrowth
else -> Name
}
}
}
| 168 | null | 364 | 895 | 218cd81423c570cdd92b1d5161a600d07c35c232 | 812 | unstoppable-wallet-android | MIT License |
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/resolution/SelectResolver.kt | abin107 | 61,786,310 | true | {"Kotlin": 276398, "Java": 157867, "ANTLR": 18607, "Shell": 1376} | /*
* Copyright (C) 2016 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 com.squareup.sqldelight.resolution
import com.squareup.sqldelight.SqliteParser
import com.squareup.sqldelight.SqlitePluginException
import com.squareup.sqldelight.types.Value
import com.squareup.sqldelight.validation.SelectOrValuesValidator
import com.squareup.sqldelight.validation.SelectStmtValidator
internal fun Resolver.resolve(selectStmt: SqliteParser.Select_stmtContext): Resolution {
val resolver = if (selectStmt.with_clause() != null) {
try {
withResolver(selectStmt.with_clause())
} catch (e: SqlitePluginException) {
return Resolution(ResolutionError.WithTableError(e.originatingElement, e.message))
}
} else {
this
}
var resolution = resolver.resolve(selectStmt.select_or_values(0), selectStmt)
// Resolve other compound select statements and verify they have equivalent columns.
selectStmt.select_or_values().drop(1).forEach {
val compoundValues = resolver.resolve(it)
if (compoundValues.values.size != resolution.values.size) {
resolution += Resolution(ResolutionError.CompoundError(it,
"Unexpected number of columns in compound statement found: " +
"${compoundValues.values.size} expected: ${resolution.values.size}"))
}
resolution += compoundValues.copy(values = emptyList())
// TODO: Type checking.
//for (valueIndex in 0..values.size) {
// if (values[valueIndex].type != compoundValues[valueIndex].type) {
// throw SqlitePluginException(compoundValues[valueIndex].element, "Incompatible types in " +
// "compound statement for column 2 found: ${compoundValues[valueIndex].type} " +
// "expected: ${values[valueIndex].type}")
// }
//}
}
return resolution
}
/**
* Takes a select_or_values rule and returns the columns selected.
*/
internal fun Resolver.resolve(
selectOrValues: SqliteParser.Select_or_valuesContext,
parentSelect: SqliteParser.Select_stmtContext? = null
): Resolution {
var resolution: Resolution
if (selectOrValues.K_VALUES() != null) {
// No columns are available, only selected columns are returned.
return Resolution(errors = SelectOrValuesValidator(this, scopedValues)
.validate(selectOrValues)) + resolve(selectOrValues.values())
} else if (selectOrValues.join_clause() != null) {
resolution = resolve(selectOrValues.join_clause())
} else if (selectOrValues.table_or_subquery().size > 0) {
resolution = selectOrValues.table_or_subquery().fold(Resolution()) {
response, table_or_subquery -> response + resolve(table_or_subquery)
}
} else {
resolution = Resolution()
}
// Validate the select or values has valid expressions before aliasing/selection.
resolution += Resolution(
errors = SelectOrValuesValidator(this, scopedValues + resolution.values)
.validate(selectOrValues))
if (parentSelect != null) {
resolution += Resolution(
errors = SelectStmtValidator(this, scopedValues + resolution.values)
.validate(parentSelect))
}
return selectOrValues.result_column().fold(Resolution(errors = resolution.errors)) {
response, result_column -> response + resolve(result_column, resolution.values)
}
}
/**
* Take in a list of available columns and return a list of selected columns.
*/
internal fun Resolver.resolve(
resultColumn: SqliteParser.Result_columnContext,
availableValues: List<Value>
): Resolution {
if (resultColumn.text.equals("*")) {
// SELECT *
return Resolution(availableValues)
}
if (resultColumn.table_name() != null) {
// SELECT some_table.*
val result = Resolution(availableValues.filter {
it.tableName == resultColumn.table_name().text
})
if (result.values.isEmpty()) {
return Resolution(errors = listOf(ResolutionError.TableNameNotFound(
resultColumn.table_name(),
"Table name ${resultColumn.table_name().text} not found",
availableValues.map { it.tableName }.filterNotNull().distinct())))
}
return result.findElement(resultColumn.table_name(), result.values.first().tableNameElement!!, elementToFind)
}
if (resultColumn.expr() != null) {
// SELECT expr
var response = copy(scopedValues = availableValues).resolve(resultColumn.expr())
if (resultColumn.column_alias() != null) {
response = Resolution(response.values.map {
it.copy(
tableName = null,
columnName = resultColumn.column_alias().text,
element = resultColumn.column_alias(),
originalTableName = null
)
}, response.errors)
}
return response
}
return Resolution(
ResolutionError.IncompleteRule(resultColumn, "Result set requires at least one column"))
}
/**
* Takes a value rule and returns the columns introduced. Validates that any
* appended values have the same length.
*/
internal fun Resolver.resolve(values: SqliteParser.ValuesContext): Resolution {
var selected = values.expr().fold(Resolution(), { response, expression ->
response + resolve(expression)
})
if (values.values() != null) {
val joinedValues = resolve(values.values())
selected += Resolution(errors = joinedValues.errors)
if (joinedValues.values.size != selected.values.size) {
selected += Resolution(ResolutionError.ValuesError(values.values(),
"Unexpected number of columns in values found: ${joinedValues.values.size} " +
"expected: ${selected.values.size}"))
}
// TODO: Type check
}
return selected
} | 0 | Kotlin | 0 | 0 | ded5cd4117d9a2e7470e0703e48cb7cff7141a6f | 6,148 | sqldelight | Apache License 2.0 |
app/src/test/java/com/twilio/conversations/app/viewModel/MessageListViewModelTest.kt | twilio | 351,834,939 | false | null | package com.twilio.conversations.app.viewModel
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.twilio.conversations.Conversation
import com.twilio.conversations.User
import com.twilio.conversations.app.asPagedList
import com.twilio.conversations.app.common.asMessageListViewItems
import com.twilio.conversations.app.common.enums.ConversationsError
import com.twilio.conversations.app.common.enums.DownloadState
import com.twilio.conversations.app.common.extensions.ConversationsException
import com.twilio.conversations.app.createTestConversationDataItem
import com.twilio.conversations.app.data.localCache.entity.ConversationDataItem
import com.twilio.conversations.app.data.localCache.entity.ParticipantDataItem
import com.twilio.conversations.app.data.models.MessageListViewItem
import com.twilio.conversations.app.data.models.RepositoryRequestStatus
import com.twilio.conversations.app.data.models.RepositoryResult
import com.twilio.conversations.app.getMockedMessages
import com.twilio.conversations.app.manager.MessageListManager
import com.twilio.conversations.app.repository.ConversationsRepository
import com.twilio.conversations.app.testUtil.CoroutineTestRule
import com.twilio.conversations.app.testUtil.waitCalled
import com.twilio.conversations.app.testUtil.waitNotCalled
import com.twilio.conversations.app.testUtil.waitValue
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.io.InputStream
import java.util.*
@RunWith(PowerMockRunner::class)
@PrepareForTest(
Conversation::class
)
class MessageListViewModelTest {
@Rule
var coroutineTestRule = CoroutineTestRule()
@Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val conversationSid = "conversationSid"
private val conversationName = "Test Conversation"
private val messageCount = 10
private val messageBody = "Test Message"
@MockK
private lateinit var selfUser: User
@MockK
private lateinit var conversationsRepository: ConversationsRepository
@MockK
private lateinit var messageListManager: MessageListManager
@MockK
private lateinit var context: Context
private lateinit var messageListViewModel: MessageListViewModel
@Before
fun setUp() {
MockKAnnotations.init(this)
Dispatchers.setMain(Dispatchers.Default)
val conversation: ConversationDataItem? = createTestConversationDataItem(sid = conversationSid, friendlyName = conversationName)
coEvery { conversationsRepository.getConversation(any()) } returns
flowOf(RepositoryResult(conversation, RepositoryRequestStatus.COMPLETE))
coEvery { conversationsRepository.getMessages(any(), any()) } returns
flowOf(RepositoryResult(listOf< MessageListViewItem>().asPagedList(), RepositoryRequestStatus.COMPLETE))
coEvery { messageListManager.updateMessageStatus(any(), any()) } returns Unit
coEvery { conversationsRepository.getTypingParticipants(conversationSid) } returns flowOf(listOf())
every { selfUser.identity } returns "selfuser"
coEvery { conversationsRepository.getSelfUser() } returns flowOf(selfUser)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `messageListViewModel_conversationName should be initialized on init`() = runBlocking {
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
assertEquals(conversationName, messageListViewModel.conversationName.waitValue())
}
@Test
fun `messageListViewModel_messageItems should contain all messages`() = runBlocking {
val expectedMessages = getMockedMessages(messageCount, messageBody, conversationSid).asMessageListViewItems()
coEvery { conversationsRepository.getMessages(any(), any()) } returns
flowOf(RepositoryResult(expectedMessages.asPagedList(), RepositoryRequestStatus.COMPLETE))
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
assertEquals(expectedMessages, messageListViewModel.messageItems.waitValue())
assertEquals(messageCount, messageListViewModel.messageItems.waitValue().size)
}
@Test
fun `messageListViewModel_messageItems should be empty when Error occurred`() = runBlocking {
coEvery { conversationsRepository.getMessages(any(), any()) } returns
flowOf(RepositoryResult(listOf< MessageListViewItem>().asPagedList(), RepositoryRequestStatus.Error(ConversationsError.GENERIC_ERROR)))
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
assertEquals(0, messageListViewModel.messageItems.waitValue().size)
}
@Test
fun `messageListViewModel_sendTextMessage should call onMessageSent on success`() = runBlocking {
coEvery { messageListManager.sendTextMessage(any(), any()) } returns Unit
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.sendTextMessage(messageBody)
assertTrue(messageListViewModel.onMessageSent.waitCalled())
assertTrue(messageListViewModel.onMessageError.waitNotCalled())
}
@Test
fun `messageListViewModel_sendTextMessage should call onMessageError on failure`() = runBlocking {
coEvery { messageListManager.sendTextMessage(any(), any()) } throws ConversationsException(ConversationsError.MESSAGE_SEND_FAILED)
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.sendTextMessage(messageBody)
assertTrue(messageListViewModel.onMessageSent.waitNotCalled())
assertTrue(messageListViewModel.onMessageError.waitValue(ConversationsError.MESSAGE_SEND_FAILED))
}
@Test
fun `messageListViewModel_resendTextMessage should call onMessageSent on success`() = runBlocking {
coEvery { messageListManager.retrySendTextMessage(any()) } returns Unit
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.resendTextMessage(UUID.randomUUID().toString())
assertTrue(messageListViewModel.onMessageSent.waitCalled())
assertTrue(messageListViewModel.onMessageError.waitNotCalled())
}
@Test
fun `messageListViewModel_resendTextMessage should call onMessageError on failure`() = runBlocking {
coEvery { messageListManager.retrySendTextMessage(any()) } throws ConversationsException(ConversationsError.MESSAGE_SEND_FAILED)
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.resendTextMessage(UUID.randomUUID().toString())
assertTrue(messageListViewModel.onMessageSent.waitNotCalled())
assertTrue(messageListViewModel.onMessageError.waitValue(ConversationsError.MESSAGE_SEND_FAILED))
}
@Test
fun `typingParticipantsList is updated`() = runBlocking {
val userFriendlyName = "userFriendlyName"
coEvery { conversationsRepository.getTypingParticipants(conversationSid) } returns flowOf(listOf(
ParticipantDataItem(
identity = "identity", conversationSid = conversationSid, lastReadTimestamp = null,
lastReadMessageIndex = null, sid = "321", friendlyName = userFriendlyName, isOnline = true
)
))
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
assertEquals(listOf(userFriendlyName), messageListViewModel.typingParticipantsList.waitValue())
}
@Test
fun `sendMediaMessage should call onMessageSent on success`() = runBlocking {
coEvery { messageListManager.sendMediaMessage(any(), any(), any(), any(), any()) } returns Unit
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.sendMediaMessage("", mock(InputStream::class.java), null, null)
assertTrue(messageListViewModel.onMessageSent.waitCalled())
assertTrue(messageListViewModel.onMessageError.waitNotCalled())
}
@Test
fun `sendMediaMessage should call onMessageError on failure`() = runBlocking {
coEvery { messageListManager.sendMediaMessage(any(), any(), any(), any(), any()) } throws ConversationsException(ConversationsError.MESSAGE_SEND_FAILED)
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.sendMediaMessage("", mock(InputStream::class.java), null, null)
assertTrue(messageListViewModel.onMessageSent.waitNotCalled())
assertTrue(messageListViewModel.onMessageError.waitValue(ConversationsError.MESSAGE_SEND_FAILED))
}
@Test
fun `resendMediaMessage should call onMessageSent on success`() = runBlocking {
coEvery { messageListManager.retrySendMediaMessage(any(), any()) } returns Unit
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.resendMediaMessage( mock(InputStream::class.java), "")
assertTrue(messageListViewModel.onMessageSent.waitCalled())
assertTrue(messageListViewModel.onMessageError.waitNotCalled())
}
@Test
fun `resendMediaMessage should call onMessageError on failure`() = runBlocking {
coEvery { messageListManager.retrySendMediaMessage(any(), any()) } throws ConversationsException(ConversationsError.MESSAGE_SEND_FAILED)
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.resendMediaMessage( mock(InputStream::class.java), "")
assertTrue(messageListViewModel.onMessageSent.waitNotCalled())
assertTrue(messageListViewModel.onMessageError.waitValue(ConversationsError.MESSAGE_SEND_FAILED))
}
@Test
fun `updateMessageMediaDownloadStatus should call MessageListManager#updateMessageMediaDownloadStatus`() = runBlocking {
val messageIndex = 1L
val downloadState = DownloadState.NOT_STARTED
val downloadedBytes = 2L
val downloadLocation = "asd"
coEvery { messageListManager.updateMessageMediaDownloadState(any(), any(), any(), any()) } returns Unit
messageListViewModel = MessageListViewModel(context, conversationSid, conversationsRepository, messageListManager)
messageListViewModel.updateMessageMediaDownloadStatus(messageIndex, downloadState, downloadedBytes, downloadLocation)
coVerify { messageListManager.updateMessageMediaDownloadState(messageIndex, downloadState, downloadedBytes, downloadLocation) }
}
}
| 4 | null | 6 | 7 | 8b926b002d7fcf8ece0ee4a9a0370565adb58ce1 | 11,742 | twilio-conversations-demo-kotlin | MIT License |
tensorflow-lite-examples-common/src/main/java/com/dailystudio/tflite/example/common/ui/InferenceSettingsFragment.kt | dailystudio | 267,263,865 | false | null | package com.dailystudio.tflite.example.common.ui
import android.content.Context
import android.graphics.drawable.Drawable
import com.dailystudio.devbricksx.settings.*
import com.dailystudio.devbricksx.utils.ResourcesCompatUtils
import com.dailystudio.tflite.example.common.R
import org.tensorflow.lite.support.model.Model
import kotlin.math.roundToInt
open class InferenceSettingsFragment: AbsSettingsDialogFragment() {
override fun createSettings(context: Context): Array<AbsSetting> {
val settingsPrefs = getInferenceSettingsPrefs()
val devices = arrayOf(
SimpleRadioSettingItem(context,
Model.Device.CPU.toString(), R.string.label_cpu),
SimpleRadioSettingItem(context,
Model.Device.GPU.toString(), R.string.label_gpu),
SimpleRadioSettingItem(context,
Model.Device.NNAPI.toString(), R.string.label_nnapi)
)
val deviceSetting = object: RadioSetting<SimpleRadioSettingItem>(
context,
InferenceSettingsPrefs.PREF_DEVICE,
R.drawable.ic_setting_device,
R.string.setting_device,
devices) {
override val selectedId: String?
get() = settingsPrefs.device
override fun setSelected(selectedId: String?) {
selectedId?.let {
settingsPrefs.device = it
}
}
}
val threadSetting = object: SeekBarSetting(
context,
InferenceSettingsPrefs.PREF_NUMBER_OF_THREADS,
R.drawable.ic_setting_threads,
R.string.setting_threads) {
override fun getMaxValue(context: Context): Float {
return InferenceSettings.MAX_NUM_OF_THREADS.toFloat()
}
override fun getMinValue(context: Context): Float {
return InferenceSettings.MIN_NUM_OF_THREADS.toFloat()
}
override fun getProgress(context: Context): Float {
return settingsPrefs.numberOfThreads.toFloat()
}
override fun getStep(context: Context): Float {
return InferenceSettings.NUM_OF_THREADS_STEP.toFloat()
}
override fun setProgress(context: Context, progress: Float) {
settingsPrefs.numberOfThreads = progress.roundToInt()
}
}
return arrayOf(deviceSetting, threadSetting)
}
override fun getDialogThumbImageDrawable(): Drawable? {
return ResourcesCompatUtils.getDrawable(requireContext(), R.drawable.settings_top)
}
open fun getInferenceSettingsPrefs(): InferenceSettingsPrefs {
return InferenceSettingsPrefs()
}
} | 1 | null | 6 | 16 | a6b2b9841154a876c0b66a9159a7aed23023f606 | 2,750 | tensorflow-lite-examples-android | Apache License 2.0 |
src/test/kotlin/com/deledzis/jetroom/view/printer/CommandLinePrinterFactoryTest.kt | deledzis | 253,047,627 | false | null | package com.deledzis.jetroom.view.printer
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
internal class CommandLinePrinterFactoryTest {
@Test
fun getPrinter() {
Assertions.assertTrue { CommandLinePrinterFactory().getPrinter() is CommandLinePrinter }
}
} | 0 | Kotlin | 0 | 0 | ce17be6fd2cd139f0547483a5992542e22830784 | 303 | JetBrainsInternshipJetRoom | MIT License |
src/test/java/filepeektest/FilePeekTestInJavaRoot.kt | christophsturm | 197,566,840 | false | null | package filepeektest
import filepeek.FilePeek
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isEqualTo
class FilePeekTestInJavaRoot {
@Test
fun `finds classes that have a different name than the file they are in`() {
val filePeek = FilePeek(listOf("filepeek."))
expectThat(filePeek.getCallerFileInfo())
.get { line }
.isEqualTo("expectThat(filePeek.getCallerFileInfo())")
}
}
| 3 | Kotlin | 4 | 3 | 540bc68cf3782ae9804d3e05fa2b7c53bc2de8c6 | 471 | filepeek | MIT License |
src/main/kotlin/com/balsdon/androidallyplugin/adb/AdbScriptModifiers.kt | qbalsdon | 729,827,162 | false | null | @file:Suppress("TooManyFunctions")
package com.balsdon.androidallyplugin.adb
import com.balsdon.androidallyplugin.adb.parameters.AdbBoolean
import com.balsdon.androidallyplugin.adb.parameters.AdbParamUsingString
import com.balsdon.androidallyplugin.adb.parameters.AdbPositiveValue
import com.balsdon.androidallyplugin.adb.parameters.BooleanPrintMode
import com.balsdon.androidallyplugin.adb.parameters.ColorCorrectionAdbParam
import com.balsdon.androidallyplugin.adb.parameters.ColorCorrectionType
import com.balsdon.androidallyplugin.adb.parameters.InternalSettingType
import com.balsdon.androidallyplugin.adb.parameters.SettingsScreen
import com.balsdon.androidallyplugin.adb.parameters.TypingTextAdbParam
import com.balsdon.androidallyplugin.adb.parameters.UnitAdbParam
fun talkBackService(activate: Boolean) = AdbScript.AccessibilityService(
activate,
true,
"com.android.talkback4d",
"com.developer.talkback.TalkBackDevService"
)
fun accessibilityScannerService(activate: Boolean) = AdbScript.AccessibilityService(
activate,
false,
"com.google.android.apps.accessibility.auditor",
"com.google.android.apps.accessibility.auditor.ScannerService"
)
fun voiceAccessService(activate: Boolean) = AdbScript.AccessibilityService(
activate,
false,
"com.google.android.apps.accessibility.voiceaccess",
"com.google.android.apps.accessibility.voiceaccess.JustSpeakService"
)
fun switchAccessService(activate: Boolean) = AdbScript.AccessibilityService(
activate,
false,
"com.google.android.accessibility.switchaccess",
"com.android.switchaccess.SwitchAccessService"
)
fun fontScale(scale: Float) = AdbScript.InternalSetting(
name = "font_scale",
internalSettingType = InternalSettingType.SYSTEM,
settingValue = AdbParamUsingString(scale)
)
fun boldFont(enabled: Boolean) = AdbScript.InternalSetting(
name = "font_weight_adjustment",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbParamUsingString(if (enabled) "300" else "0")
)
fun timeToReact(value: Int) = AdbScript.InternalSetting(
name = "accessibility_interactive_ui_timeout_ms",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbParamUsingString(value)
)
fun displayDensity(value: Int = -1) = AdbScript.Command(
commandScript = "wm density $1",
params = listOf(AdbPositiveValue(value, "reset"))
)
fun darkMode(isDarkMode: Boolean) = AdbScript.Command(
commandScript = "cmd uimode night $1",
params = listOf(AdbBoolean(isDarkMode, BooleanPrintMode.ENGLISH))
)
fun colorInversion(isEnabled: Boolean) = AdbScript.InternalSetting(
name = "accessibility_display_inversion_enabled",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(isEnabled, BooleanPrintMode.BINARY)
)
fun showTouches(isEnabled: Boolean) = AdbScript.InternalSetting(
name = "show_touches",
internalSettingType = InternalSettingType.SYSTEM,
settingValue = AdbBoolean(isEnabled, BooleanPrintMode.BINARY)
)
fun highTextContrast(isEnabled: Boolean) = AdbScript.InternalSetting(
name = "high_text_contrast_enabled",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(isEnabled, BooleanPrintMode.BINARY)
)
private fun colorCorrectionEnabled(isEnabled: Boolean) = AdbScript.InternalSetting(
name = "accessibility_display_daltonizer_enabled",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(isEnabled, BooleanPrintMode.BINARY)
)
// Needs to be done in conjunction with enabling
private fun colorCorrectionSetting(correctionType: ColorCorrectionType) = AdbScript.InternalSetting(
name = "accessibility_display_daltonizer",
internalSettingType = InternalSettingType.SECURE,
settingValue = ColorCorrectionAdbParam(correctionType)
)
fun colorCorrection(correctionType: ColorCorrectionType) = AdbScript.CombinationCommand(
commandList = if (correctionType == ColorCorrectionType.OFF) {
listOf(colorCorrectionEnabled(false))
} else {
listOf(
colorCorrectionEnabled(true),
colorCorrectionSetting(correctionType)
)
}
)
fun powerOff() = AdbScript.Command<UnitAdbParam>(
commandScript = "reboot -p"
)
fun reboot() = AdbScript.Command<UnitAdbParam>(
commandScript = "reboot"
)
fun typeText(text: String) = AdbScript.Command(
commandScript = "input text $1",
params = listOf(TypingTextAdbParam(text))
)
fun layoutBounds(enabled: Boolean) = AdbScript.Command(
commandScript = "setprop debug.layout $1; service call activity 1599295570 > /dev/null 2>&1",
params = listOf(AdbBoolean(enabled, BooleanPrintMode.BINARY))
)
fun animations(enabled: Boolean) = AdbScript.Command(
commandScript = "cmd settings put global animator_duration_scale $1; cmd settings put global transition_animation_scale $1; cmd settings put global window_animation_scale $1",
params = listOf(AdbBoolean(enabled, BooleanPrintMode.FLOAT))
)
fun captions(enabled: Boolean) = AdbScript.InternalSetting(
name = "accessibility_captioning_enabled",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(enabled, BooleanPrintMode.BINARY)
)
fun audioDescription(enabled: Boolean) = AdbScript.CombinationCommand(
commandList = listOf(
AdbScript.InternalSetting(
name = "enabled_accessibility_audio_description_by_default",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(enabled, BooleanPrintMode.BINARY)
),
AdbScript.InternalSetting(
name = "accessibility_audio_descriptions_enabled",
internalSettingType = InternalSettingType.SECURE,
settingValue = AdbBoolean(enabled, BooleanPrintMode.BINARY)
)
)
)
fun settings(internalSettingType: InternalSettingType) = if (internalSettingType == InternalSettingType.ALL) {
AdbScript.Command<UnitAdbParam>(
"settings list system | sed 's/^/system./';settings list secure | sed 's/^/secure./';settings list global | sed 's/^/global./';",
)
} else {
AdbScript.Command(
"settings list $1",
listOf(AdbParamUsingString(internalSettingType.name, true))
)
}
fun openScreen(settingsScreen: SettingsScreen) =
AdbScript.Command(
"am start -a $1",
listOf(AdbParamUsingString(settingsScreen.internalAndroidReference))
)
| 2 | null | 0 | 7 | e2925f7d3afc976341e6dcb37d67661aa8fd544a | 6,447 | android-ally-plugin | MIT License |
src/main/kotlin/io/github/cafeteriaguild/advweaponry/AWLoreItems.kt | CafeteriaGuild | 271,669,092 | false | null | package io.github.cafeteriaguild.advweaponry
/**
* Crafting Materials, etc
*/
object AWLoreItems {
} | 0 | Kotlin | 0 | 0 | f06efd30051775f4f5235ea4eca5d26706b2c344 | 103 | AdventurerWeaponry | Apache License 2.0 |
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/draw/DrawModifierTest.kt | RikkaW | 389,105,112 | false | null | /*
* 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.draw
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.AtLeastSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.drawWithCache
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class DrawModifierTest {
@get:Rule
val rule = createComposeRule()
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testCacheHitWithStateChange() {
// Verify that a state change outside of the cache block does not
// require the cache block to be invalidated
val testTag = "testTag"
var cacheBuildCount = 0
val size = 200
rule.setContent {
var rectColor by remember { mutableStateOf(Color.Blue) }
AtLeastSize(
size = size,
modifier = Modifier.testTag(testTag).drawWithCache {
val drawSize = this.size
val path = Path().apply {
lineTo(drawSize.width / 2f, 0f)
lineTo(drawSize.width / 2f, drawSize.height)
lineTo(0f, drawSize.height)
close()
}
cacheBuildCount++
onDrawBehind {
drawRect(rectColor)
drawPath(path, Color.Red)
}
}.clickable {
if (rectColor == Color.Blue) {
rectColor = Color.Green
} else {
rectColor = Color.Blue
}
}
) { }
}
rule.onNodeWithTag(testTag).apply {
// Verify that the path was created only once
assertEquals(1, cacheBuildCount)
captureToBitmap().apply {
assertEquals(Color.Red.toArgb(), getPixel(1, 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 2, 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 2, height / 2 - 2))
assertEquals(Color.Red.toArgb(), getPixel(1, height / 2 - 2))
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 + 1, 1))
assertEquals(Color.Blue.toArgb(), getPixel(width - 2, 1))
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 + 1, height - 2))
assertEquals(Color.Blue.toArgb(), getPixel(width - 2, height - 2))
}
performClick()
}
rule.waitForIdle()
rule.onNodeWithTag(testTag).apply {
// Verify that the path was re-used and only built once
assertEquals(1, cacheBuildCount)
captureToBitmap().apply {
assertEquals(Color.Red.toArgb(), getPixel(1, 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 2, 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 2, height / 2 - 1))
assertEquals(Color.Red.toArgb(), getPixel(1, height / 2 - 2))
assertEquals(Color.Green.toArgb(), getPixel(width / 2 + 1, 1))
assertEquals(Color.Green.toArgb(), getPixel(width - 2, 1))
assertEquals(Color.Green.toArgb(), getPixel(width / 2 + 1, height - 2))
assertEquals(Color.Green.toArgb(), getPixel(width - 2, height - 2))
}
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testCacheInvalidatedAfterStateChange() {
// Verify that a state change within the cache block does
// require the cache block to be invalidated
val testTag = "testTag"
var cacheBuildCount = 0
val size = 200
rule.setContent {
var pathFillBounds by remember { mutableStateOf(false) }
AtLeastSize(
size = size,
modifier = Modifier.testTag(testTag).drawWithCache {
val pathSize = if (pathFillBounds) this.size else this.size / 2f
val path = Path().apply {
lineTo(pathSize.width, 0f)
lineTo(pathSize.width, pathSize.height)
lineTo(0f, pathSize.height)
close()
}
cacheBuildCount++
onDrawBehind {
drawRect(Color.Red)
drawPath(path, Color.Blue)
}
}.clickable {
pathFillBounds = !pathFillBounds
}
) { }
}
rule.onNodeWithTag(testTag).apply {
// Verify that the path was created only once
assertEquals(1, cacheBuildCount)
captureToBitmap().apply {
assertEquals(Color.Blue.toArgb(), getPixel(1, 1))
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 - 2, 1))
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 - 2, height / 2 - 2))
assertEquals(Color.Blue.toArgb(), getPixel(1, height / 2 - 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 + 1, 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 + 1, height / 2 - 1))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 + 1, height / 2 - 2))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 2, height / 2 + 1))
assertEquals(Color.Red.toArgb(), getPixel(1, height / 2 + 1))
assertEquals(Color.Red.toArgb(), getPixel(1, height - 2))
assertEquals(Color.Red.toArgb(), getPixel(width - 2, 1))
assertEquals(Color.Red.toArgb(), getPixel(width - 2, height - 2))
}
performClick()
}
rule.waitForIdle()
rule.onNodeWithTag(testTag).apply {
assertEquals(2, cacheBuildCount)
captureToBitmap().apply {
assertEquals(Color.Blue.toArgb(), getPixel(1, 1))
assertEquals(Color.Blue.toArgb(), getPixel(size - 2, 1))
assertEquals(Color.Blue.toArgb(), getPixel(size - 2, size - 2))
assertEquals(Color.Blue.toArgb(), getPixel(1, size - 2))
}
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testCacheInvalidatedAfterSizeChange() {
// Verify that a size change does cause the cache block to be invalidated
val testTag = "testTag"
var cacheBuildCount = 0
val startSize = 200
val endSize = 400
rule.setContent {
var size by remember { mutableStateOf(startSize) }
AtLeastSize(
size = size,
modifier = Modifier.testTag(testTag).drawWithCache {
val drawSize = this.size
val path = Path().apply {
lineTo(drawSize.width, 0f)
lineTo(drawSize.height, drawSize.height)
lineTo(0f, drawSize.height)
close()
}
cacheBuildCount++
onDrawBehind {
drawPath(path, Color.Red)
}
}.clickable {
if (size == startSize) {
size = endSize
} else {
size = startSize
}
}
) { }
}
rule.onNodeWithTag(testTag).apply {
// Verify that the path was created only once
assertEquals(1, cacheBuildCount)
captureToBitmap().apply {
assertEquals(startSize, this.width)
assertEquals(startSize, this.height)
assertEquals(Color.Red.toArgb(), getPixel(1, 1))
assertEquals(Color.Red.toArgb(), getPixel(width - 2, height - 2))
}
performClick()
}
rule.waitForIdle()
rule.onNodeWithTag(testTag).apply {
// Verify that the path was re-used and only built once
assertEquals(2, cacheBuildCount)
captureToBitmap().apply {
assertEquals(endSize, this.width)
assertEquals(endSize, this.height)
assertEquals(Color.Red.toArgb(), getPixel(1, 1))
assertEquals(Color.Red.toArgb(), getPixel(width - 2, height - 2))
}
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testDrawWithCacheContentDrawnImplicitly() {
// Verify that drawContent is invoked even if it is not explicitly called within
// the implementation of the callback provided in the onDraw method
// in Modifier.drawWithCache
val testTag = "testTag"
val testSize = 200
rule.setContent {
AtLeastSize(
size = testSize,
modifier = Modifier.testTag(testTag).drawWithCache {
onDrawBehind {
drawRect(Color.Red, size = Size(size.width / 2, size.height))
}
}.background(Color.Blue)
)
}
rule.onNodeWithTag(testTag).apply {
captureToBitmap().apply {
assertEquals(Color.Blue.toArgb(), getPixel(0, 0))
assertEquals(Color.Blue.toArgb(), getPixel(width - 1, 0))
assertEquals(Color.Blue.toArgb(), getPixel(width - 1, height - 1))
assertEquals(Color.Blue.toArgb(), getPixel(0, height - 1))
}
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testDrawWithCacheOverContent() {
// Verify that drawContent is not invoked implicitly if it is explicitly called within
// the implementation of the callback provided in the onDraw method
// in Modifier.drawWithCache. That is the red rectangle is drawn above the contents
val testTag = "testTag"
val testSize = 200
rule.setContent {
AtLeastSize(
size = testSize,
modifier = Modifier.testTag(testTag).drawWithCache {
onDrawWithContent {
drawContent()
drawRect(Color.Red, size = Size(size.width / 2, size.height))
}
}.background(Color.Blue)
)
}
rule.onNodeWithTag(testTag).apply {
captureToBitmap().apply {
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 + 1, 0))
assertEquals(Color.Blue.toArgb(), getPixel(width - 1, 0))
assertEquals(Color.Blue.toArgb(), getPixel(width - 1, height - 1))
assertEquals(Color.Blue.toArgb(), getPixel(width / 2 + 1, height - 1))
assertEquals(Color.Red.toArgb(), getPixel(0, 0))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 1, 0))
assertEquals(Color.Red.toArgb(), getPixel(width / 2 - 1, height - 1))
assertEquals(Color.Red.toArgb(), getPixel(0, height - 1))
}
}
}
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testDrawWithCacheBlendsContent() {
// Verify that the drawing commands of drawContent are blended against the green
// rectangle with the specified BlendMode
val testTag = "testTag"
val testSize = 200
rule.setContent {
AtLeastSize(
size = testSize,
modifier = Modifier.testTag(testTag).drawWithCache {
onDrawWithContent {
drawContent()
drawRect(Color.Green, blendMode = BlendMode.Plus)
}
}.background(Color.Blue)
)
}
rule.onNodeWithTag(testTag).apply {
captureToBitmap().apply {
assertEquals(Color.Cyan.toArgb(), getPixel(0, 0))
assertEquals(Color.Cyan.toArgb(), getPixel(width - 1, 0))
assertEquals(Color.Cyan.toArgb(), getPixel(width - 1, height - 1))
assertEquals(Color.Cyan.toArgb(), getPixel(0, height - 1))
}
}
}
fun SemanticsNodeInteraction.captureToBitmap() = captureToImage().asAndroidBitmap()
} | 30 | null | 974 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 14,111 | androidx | Apache License 2.0 |
app/src/main/java/com/example/antheia_plant_manager/model/data/impl/PlantRepositoryImpl.kt | MegaBreadbox | 814,871,131 | false | {"Kotlin": 120448} | package com.example.antheia_plant_manager.model.data.impl
import com.example.antheia_plant_manager.model.data.Plant
import com.example.antheia_plant_manager.model.data.PlantDao
import com.example.antheia_plant_manager.model.data.PlantRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class PlantRepositoryImpl @Inject constructor (private val plantDao: PlantDao): PlantRepository {
override suspend fun addPlant(plant: Plant) {
plantDao.addPlant(plant)
}
override suspend fun deletePlant(plant: Plant) {
plantDao.deletePlant(plant)
}
override suspend fun updatePlant(plant: Plant) {
plantDao.updatePlant(plant)
}
override fun getPlantLocations(): Flow<List<String>> {
return plantDao.getPlantLocations()
}
override fun getPlants(location: String): Flow<List<Plant>> {
return plantDao.getPlants(location)
}
} | 0 | Kotlin | 0 | 0 | f9c418e22a4d3c18a4c92f7819113f743eb77e6e | 918 | Antheia | Apache License 2.0 |
graphql/src/main/kotlin/com/trib3/graphql/execution/SanitizedGraphQLError.kt | trib3 | 191,460,324 | false | null | package com.trib3.graphql.execution
import com.fasterxml.jackson.annotation.JsonIgnore
import graphql.ExceptionWhileDataFetching
import graphql.execution.ResultPath
import graphql.language.SourceLocation
/**
* Removes exception from the error JSON serialization keeping it out of the API response
* and attempts to bubble up the message from the root cause of the exception
*/
class SanitizedGraphQLError(
path: ResultPath,
exception: Throwable,
sourceLocation: SourceLocation
) : ExceptionWhileDataFetching(path, exception, sourceLocation) {
override fun getMessage(): String {
return getCause(super.getException()).message ?: super.getMessage()
}
@JsonIgnore
override fun getException(): Throwable {
return super.getException()
}
/**
* Find the root cause of the exception being thrown
* (Root cause will either have a null or itself under it)
*/
private fun getCause(e: Throwable): Throwable {
var result: Throwable = e
var cause = result.cause
while (cause != null && result != cause) {
result = cause
cause = result.cause
}
return result
}
}
| 33 | null | 3 | 9 | 540e895a9afa4ddf9b9879c505ec9856a88a4a9b | 1,195 | leakycauldron | Apache License 2.0 |
src/main/kotlin/com/coditory/gradle/webjar/WebjarInitTask.kt | coditory | 252,974,843 | false | null | package com.coditory.gradle.webjar
import com.coditory.gradle.webjar.WebjarPlugin.Companion.WEBJAR_INIT_TASK
import com.coditory.gradle.webjar.WebjarPlugin.Companion.WEBJAR_REMOVE_MODULES_TASK
import com.coditory.gradle.webjar.shared.SemVersion
import com.github.gradle.node.NodeExtension
import com.github.gradle.node.npm.task.NpmSetupTask
import com.github.gradle.node.npm.task.NpmTask
import org.gradle.api.Project
object WebjarInitTask {
fun install(project: Project) {
project.tasks.register(WEBJAR_INIT_TASK, NpmTask::class.java) { task ->
task.dependsOn(NpmSetupTask.NAME)
task.dependsOn(WEBJAR_REMOVE_MODULES_TASK)
task.group = WebjarPlugin.WEBJAR_TASK_GROUP
task.args.set(resolveNpmArguments(project))
task.doFirst { ensurePackageJson(project) }
setupCaching(task)
}
}
private fun setupCaching(task: NpmTask) {
task.inputs.files("package.json")
task.outputs.file("package-lock.json")
}
private fun resolveNpmArguments(project: Project): List<String> {
val node = project.extensions.findByType(NodeExtension::class.java)
val npmSemVersion = SemVersion.parseOrNull(node?.npmVersion?.orNull)
return if (npmSemVersion == null || npmSemVersion >= SemVersion.parse("6.0.0")) {
listOf("install", "--package-lock-only")
} else {
listOf("install")
}
}
private fun ensurePackageJson(project: Project) {
val packageJsonFile = project.projectDir.resolve("package.json")
if (!packageJsonFile.isFile) {
packageJsonFile.createNewFile()
packageJsonFile.writeText(
"""
{
"name": "${project.name}",
"scripts": {
"lint": "echo 'missing lint script'",
"test": "echo 'missing test script'",
"clean": "echo 'missing clean script'",
"build": "echo 'missing build script'",
"watch": "echo 'missing watch script'"
}
}
""".trimIndent()
)
}
}
}
| 1 | Kotlin | 2 | 6 | 008e24dbf2a3c0709b79a9fd53e837927aafdc6a | 2,236 | gradle-webjar-plugin | MIT License |
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/RelationDeleteQuery.kt | komapper | 349,909,214 | false | null | package org.komapper.core.dsl.query
import org.komapper.core.dsl.context.RelationDeleteContext
import org.komapper.core.dsl.expression.WhereDeclaration
import org.komapper.core.dsl.metamodel.EntityMetamodel
import org.komapper.core.dsl.operator.plus
import org.komapper.core.dsl.options.DeleteOptions
import org.komapper.core.dsl.visitor.QueryVisitor
/**
* Represents a query to delete rows.
* This query returns the number of rows affected.
*/
interface RelationDeleteQuery : Query<Int> {
/**
* Builds a query with a WHERE clause.
*
* @param declaration the where declaration
* @return the query
*/
fun where(declaration: WhereDeclaration): RelationDeleteQuery
/**
* Builds a query with the options applied.
*
* @param configure the configure function to apply options
* @return the query
*/
fun options(configure: (DeleteOptions) -> DeleteOptions): RelationDeleteQuery
}
internal data class RelationDeleteQueryImpl<ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>>(
private val context: RelationDeleteContext<ENTITY, ID, META>,
) : RelationDeleteQuery {
override fun where(declaration: WhereDeclaration): RelationDeleteQuery {
val newContext = context.copy(where = context.where + declaration)
return copy(context = newContext)
}
override fun options(configure: (DeleteOptions) -> DeleteOptions): RelationDeleteQuery {
val newContext = context.copy(options = configure(context.options))
return copy(context = newContext)
}
override fun <VISIT_RESULT> accept(visitor: QueryVisitor<VISIT_RESULT>): VISIT_RESULT {
return visitor.relationDeleteQuery(context)
}
}
| 7 | null | 4 | 97 | 851b313c66645d60f2e86934a5036efbe435396a | 1,721 | komapper | Apache License 2.0 |
plugins/terminal/src/org/jetbrains/plugins/terminal/exp/TerminalSessionCompletionContributor.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.terminal.exp
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PlatformPatterns.psiFile
import com.intellij.psi.PsiFile
import com.intellij.util.ProcessingContext
import org.jetbrains.plugins.terminal.util.SHELL_TYPE_KEY
import org.jetbrains.plugins.terminal.util.ShellType
class TerminalCompletionContributor : CompletionContributor() {
init {
extend(CompletionType.BASIC, psiElement().inFile(psiFile().with(ShellTypeCondition(ShellType.ZSH))), ShCompletionProvider())
extend(CompletionType.BASIC, psiElement().inFile(psiFile().with(ShellTypeCondition(ShellType.BASH))), ShCompletionProvider())
}
private class ShellTypeCondition(private val type: ShellType) : PatternCondition<PsiFile>("shellType") {
override fun accepts(file: PsiFile, context: ProcessingContext?): Boolean {
var original = file
while (original.originalFile != original) {
original = original.originalFile
}
return original.getUserData(SHELL_TYPE_KEY) == type
}
}
companion object {
fun isSingleCharParameter(value: String): Boolean = value.length == 2 && value[0] == '-'
}
} | 233 | null | 4931 | 15,571 | 92c8aad1c748d6741e2c8e326e76e68f3832f649 | 1,469 | intellij-community | Apache License 2.0 |
z2-core/src/commonMain/kotlin/hu/simplexion/z2/adaptive/testing/RuiTestAdapter.kt | spxbhuhb | 665,463,766 | false | {"Kotlin": 1492824, "CSS": 166164, "Java": 9167, "HTML": 1560, "JavaScript": 975} | /*
* Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.z2.adaptive.testing
import hu.simplexion.z2.adaptive.RuiAdapter
import hu.simplexion.z2.adaptive.RuiBridge
import hu.simplexion.z2.adaptive.RuiFragment
open class RuiTestAdapter : RuiAdapter<TestNode> {
data class TraceEvent(
val name: String,
val point: String,
val data: List<String>
) {
constructor(name: String, point: String, vararg data: Any?) : this(name, point, data.map { it.toString() })
override fun toString(): String {
return "[ ${name.padEnd(30)} ] ${point.padEnd(20)} | ${data.joinToString(" ")}"
}
fun toCode(): String {
return "TraceEvent(\"$name\", \"${point}\", ${data.joinToString(", ") { "\"$it\"" }})"
}
}
val fragments = mutableListOf<RuiFragment<TestNode>>()
var nextId = 1
final override fun newId(): Int = nextId ++ // This is not thread safe, OK for testing, but beware.
override val rootBridge = RuiTestBridge(newId())
val trace = mutableListOf<TraceEvent>()
init {
lastTrace = trace
}
override fun createPlaceholder(): RuiBridge<TestNode> {
return RuiTestBridge(newId())
}
override fun trace(name: String, point: String, vararg data: Any?) {
// convert the data to string so later changes won't change the content
trace += TraceEvent(name, point, data.map { it.asString() })
}
fun Any?.asString(): String =
when (this) {
is RuiTestBridge -> this.id.toString()
else -> this.toString()
}
companion object {
// Unit tests use this property when they run the generated fragment.
// The trace of the last created adapter is here, unit tests should
// clear this field before running the generated code.
var lastTrace: MutableList<TraceEvent> = mutableListOf()
fun assert(expected: List<TraceEvent>): String {
return if (expected == lastTrace) {
"OK"
} else {
"Fail:\n${expected.joinToString("\n")}\n==== vs ====\n${lastTrace.joinToString("\n")}\n==== code ====\n${lastTrace.joinToString(",\n") { it.toCode() }}"
}
}
}
} | 6 | Kotlin | 0 | 1 | cb3effbcd9f086977150bd5b58fb7e7f14ae94ac | 2,363 | z2 | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vswin/utilities/Version2.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.startup.importSettings.providers.vswin.utilities
// If minorVersion is set to -1, it means any minor version is supported and we don't care about minor version.
class Version2(var major: Int, var minor: Int = -1) {
companion object {
fun parse(s: String): Version2 {
if (s.isEmpty()) {
throw IllegalArgumentException("The version string can't be empty")
}
val parts = s.split('.')
when {
parts.size > 2 -> throw IllegalArgumentException("Too many dot-separated parts")
parts.isEmpty() -> throw IllegalArgumentException("Too few dot-separated parts")
}
if (parts[0].toIntOrNull() == null || parts[1].toIntOrNull() == null) {
throw IllegalArgumentException("Can't parse to int")
}
return Version2(parts[0].toInt(), parts[1].toInt())
}
}
override operator fun equals(other: Any?): Boolean {
if (other !is Version2) {
return false
}
if (minor == -1 || other.minor == -1) {
return major == other.major
}
return major == other.major && minor == other.minor
}
operator fun compareTo(other: Version2): Int {
// todo: Current approach is terrible
if (minor == -1 || other.minor == -1) {
return major.compareTo(other.major)
}
return (major*1000+minor).compareTo(other.major*1000+other.minor)
}
override fun hashCode(): Int {
return if (minor != -1) {
31 * major + minor
}
else {
31 * major
}
}
override fun toString(): String {
if (minor == -1) {
return major.toString()
}
return "$major.$minor"
}
} | 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,964 | intellij-community | Apache License 2.0 |
src/main/kotlin/com/github/billialpha/intellijexternaltoolrunconfig/listeners/MyProjectManagerListener.kt | BilliAlpha | 302,920,044 | false | null | package com.github.billialpha.intellijexternaltoolrunconfig.listeners
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.github.billialpha.intellijexternaltoolrunconfig.services.MyProjectService
internal class MyProjectManagerListener : ProjectManagerListener {
override fun projectOpened(project: Project) {
project.getService(MyProjectService::class.java)
}
}
| 0 | Kotlin | 0 | 0 | 6f02b630696d14544582c9acdec925dc65e86885 | 444 | Intellij-ExternalTool-Run-Config | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/CellMargins.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: CellMargins
*
* Full name: System`CellMargins
*
* Usage: CellMargins is an option for Cell that specifies the absolute margins in printer's points to leave around a cell.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/CellMargins
* Documentation: web: http://reference.wolfram.com/language/ref/CellMargins.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun cellMargins(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("CellMargins", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,002 | mathemagika | Apache License 2.0 |
buildSrc/src/main/kotlin/Kdokker.kt | vendelieu | 496,567,172 | false | null | import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
@Serializable
data class Api(
val methods: Map<String, ApiEntity>,
val types: Map<String, ApiEntity>,
)
@Serializable
data class ApiEntity(
var name: String,
var href: String,
var description: List<String>,
var returns: List<String> = emptyList(),
var fields: List<Field> = emptyList(),
)
@Serializable
data class Field(
var name: String,
var types: List<String>,
var required: Boolean,
var description: String,
)
private val mapper = Json { ignoreUnknownKeys = true }
abstract class Kdokker : DefaultTask() {
private val jsonRes = mapper.decodeFromString<Api>(javaClass.getResource("api.json")!!.readText())
private val funRegex = Regex(
"(@\\w+\\s*\\(\\\".*\\\"\\))?\\s*(inline\\s+)?fun\\s+(\\w+)\\s*\\((.*)\\)", RegexOption.DOT_MATCHES_ALL,
)
private val classRegex = Regex(
"@Serializable(?:\\(.*\\))?\\s(?:data|sealed)?\\s?class\\s+(\\w+)\\s*(?:\\(|\\{)",
RegexOption.DOT_MATCHES_ALL,
)
private val kdocRegex = Regex("\\n/\\*\\*.*\\*/", RegexOption.DOT_MATCHES_ALL)
private val NEWLINE = "\n"
private val apiFiles = project.layout.projectDirectory
.dir("src/commonMain/kotlin/eu/vendeli/tgbot/api").asFileTree.files
private val typeFiles = project.layout.projectDirectory
.dir("src/commonMain/kotlin/eu/vendeli/tgbot/types").asFileTree.files.filter {
!it.path.contains("internal")
}
private fun String.beginWithUpperCase(): String = when (this.length) {
0 -> ""
1 -> uppercase()
else -> this[0].uppercase() + this.substring(1)
}
private fun String.snakeToCamelCase() = split('_').mapIndexed { i, it ->
if (i == 0) return@mapIndexed it
it.beginWithUpperCase()
}.joinToString("")
@TaskAction
fun updateKDoc() {
apiFiles.parallelStream().forEach { file ->
if (file.isFile && file.extension == "kt") {
// Read file content
val fileContent = file.readText()
var modifiedContent = fileContent.replace(kdocRegex, "") // remove old kdocs
val method = funRegex.find(modifiedContent) ?: return@forEach
val methodName = method.groups[3]!!.value
val methodMeta = jsonRes.methods[methodName]
?: jsonRes.methods["send" + methodName.beginWithUpperCase()]
?: return@forEach
var kdoc = "/**$NEWLINE"
kdoc += methodMeta.description.joinToString("$NEWLINE * ", " * ")
kdoc += "$NEWLINE * Api reference: ${methodMeta.href}"
kdoc += "$NEWLINE * "
kdoc += methodMeta.fields.joinToString("$NEWLINE * ") {
"@param " + it.name.snakeToCamelCase() + " " + it.description
}
kdoc += NEWLINE + methodMeta.returns.joinToString("|", " * @returns ") { "[$it]" }
kdoc += "$NEWLINE*/$NEWLINE"
modifiedContent = modifiedContent.replace(method.value, kdoc + method.value)
file.writeText(modifiedContent)
}
}
typeFiles.parallelStream().forEach { file ->
if (file.isFile && file.extension == "kt") {
val fileContent = file.readText()
var modifiedContent = fileContent.replace(kdocRegex, "") // remove old kdocs
val clazz = classRegex.find(modifiedContent) ?: return@forEach
val className = clazz.groups.last()!!.value
val classMeta = jsonRes.types[className]
if (classMeta == null) {
logger.warn("Class $className details not found")
return@forEach
}
var kdoc = "/**$NEWLINE"
kdoc += classMeta.description.joinToString("$NEWLINE * ", " * ")
kdoc += "$NEWLINE * "
kdoc += classMeta.fields.joinToString("$NEWLINE * ") {
"@property " + it.name.snakeToCamelCase() + " " + it.description
}
kdoc += NEWLINE + " * Api reference: ${classMeta.href}$NEWLINE*/$NEWLINE"
modifiedContent = modifiedContent.replace(clazz.value, kdoc + clazz.value)
file.writeText(modifiedContent)
}
}
}
}
| 6 | null | 9 | 165 | c1ddf4a42c577410af31249dc650858320668263 | 4,514 | telegram-bot | Apache License 2.0 |
src/main/kotlin/io/prometheus/common/GrpcObjects.kt | pambrose | 87,608,617 | false | null | /*
* Copyright © 2020 <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.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.common
import com.google.protobuf.ByteString
import io.prometheus.grpc.*
import java.util.zip.CRC32
internal object GrpcObjects {
const val EMPTY_AGENTID = "Empty agentId"
const val EMPTY_PATH = "Empty path"
fun newHeartBeatRequest(agentId: String): HeartBeatRequest =
heartBeatRequest {
this.agentId = agentId
}
fun newHeartBeatResponse(valid: Boolean, reason: String): HeartBeatResponse =
heartBeatResponse {
this.valid = valid
this.reason = reason
}
fun newRegisterAgentRequest(agentId: String, agentName: String, hostName: String): RegisterAgentRequest {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
return registerAgentRequest {
this.agentId = agentId
this.agentName = agentName
this.hostName = hostName
}
}
fun newRegisterAgentResponse(valid: Boolean, reason: String, agentId: String): RegisterAgentResponse {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
return registerAgentResponse {
this.valid = valid
this.reason = reason
this.agentId = agentId
}
}
fun newPathMapSizeRequest(agentId: String): PathMapSizeRequest {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
return pathMapSizeRequest {
this.agentId = agentId
}
}
fun newPathMapSizeResponse(pathCount: Int): PathMapSizeResponse =
pathMapSizeResponse {
this.pathCount = pathCount
}
fun newRegisterPathRequest(agentId: String, path: String): RegisterPathRequest {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
require(path.isNotEmpty()) { EMPTY_PATH }
return registerPathRequest {
this.agentId = agentId
this.path = path
}
}
fun newRegisterPathResponse(valid: Boolean,
reason: String,
pathCount: Int,
pathId: Long): RegisterPathResponse =
registerPathResponse {
this.valid = valid
this.reason = reason
this.pathCount = pathCount
this.pathId = pathId
}
fun newScrapeRequest(agentId: String,
scrapeId: Long,
path: String,
encodedQueryParams: String,
accept: String?,
debugEnabled: Boolean): ScrapeRequest {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
return scrapeRequest {
this.agentId = agentId
this.scrapeId = scrapeId
this.path = path
this.encodedQueryParams = encodedQueryParams
this.debugEnabled = debugEnabled
if (!accept.isNullOrBlank())
this.accept = accept
}
}
fun ScrapeResponse.toScrapeResults(): ScrapeResults =
ScrapeResults(
agentId = agentId,
scrapeId = scrapeId,
validResponse = validResponse,
statusCode = statusCode,
contentType = contentType,
zipped = zipped,
failureReason = failureReason,
url = url
).also { results ->
if (zipped)
results.contentAsZipped = contentAsZipped.toByteArray()
else
results.contentAsText = contentAsText
}
fun ScrapeResults.toScrapeResponse(): ScrapeResponse =
scrapeResponse {
val other = this@toScrapeResponse
agentId = other.agentId
scrapeId = other.scrapeId
validResponse = other.validResponse
statusCode = other.statusCode
contentType = other.contentType
zipped = other.zipped
if (zipped)
contentAsZipped = ByteString.copyFrom(other.contentAsZipped)
else
contentAsText = other.contentAsText
failureReason = other.failureReason
url = other.url
}
fun ScrapeResults.toScrapeResponseHeader(): ChunkedScrapeResponse =
chunkedScrapeResponse {
header =
headerData {
val other = this@toScrapeResponseHeader
headerAgentId = other.agentId
headerScrapeId = other.scrapeId
headerValidResponse = other.validResponse
headerStatusCode = other.statusCode
headerContentType = other.contentType
headerFailureReason = other.failureReason
headerUrl = other.url
}
}
fun newScrapeResponseChunk(scrapeId: Long,
totalChunkCount: Int,
readByteCount: Int,
checksum: CRC32,
buffer: ByteArray): ChunkedScrapeResponse =
chunkedScrapeResponse {
chunk =
chunkData {
chunkScrapeId = scrapeId
chunkCount = totalChunkCount
chunkByteCount = readByteCount
chunkChecksum = checksum.value
chunkBytes = ByteString.copyFrom(buffer)
}
}
fun newScrapeResponseSummary(scrapeId: Long,
totalChunkCount: Int,
totalByteCount: Int,
checksum: CRC32): ChunkedScrapeResponse =
chunkedScrapeResponse {
summary =
summaryData {
summaryScrapeId = scrapeId
summaryChunkCount = totalChunkCount
summaryByteCount = totalByteCount
summaryChecksum = checksum.value
}
}
fun newUnregisterPathRequest(agentId: String, path: String): UnregisterPathRequest {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
require(path.isNotEmpty()) { EMPTY_PATH }
return unregisterPathRequest {
this.agentId = agentId
this.path = path
}
}
fun newAgentInfo(agentId: String): AgentInfo {
require(agentId.isNotEmpty()) { EMPTY_AGENTID }
return agentInfo { this.agentId = agentId }
}
private fun heartBeatRequest(block: HeartBeatRequest.Builder.() -> Unit): HeartBeatRequest =
HeartBeatRequest.newBuilder().let {
block.invoke(it)
it.build()
}
private fun heartBeatResponse(block: HeartBeatResponse.Builder.() -> Unit): HeartBeatResponse =
HeartBeatResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun registerAgentRequest(block: RegisterAgentRequest.Builder.() -> Unit): RegisterAgentRequest =
RegisterAgentRequest.newBuilder().let {
block.invoke(it)
it.build()
}
private fun registerAgentResponse(block: RegisterAgentResponse.Builder.() -> Unit): RegisterAgentResponse =
RegisterAgentResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun pathMapSizeRequest(block: PathMapSizeRequest.Builder.() -> Unit): PathMapSizeRequest =
PathMapSizeRequest.newBuilder().let {
block.invoke(it)
it.build()
}
private fun pathMapSizeResponse(block: PathMapSizeResponse.Builder.() -> Unit): PathMapSizeResponse =
PathMapSizeResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun registerPathRequest(block: RegisterPathRequest.Builder.() -> Unit): RegisterPathRequest =
RegisterPathRequest.newBuilder().let {
block.invoke(it)
it.build()
}
private fun registerPathResponse(block: RegisterPathResponse.Builder.() -> Unit): RegisterPathResponse =
RegisterPathResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun scrapeRequest(block: ScrapeRequest.Builder.() -> Unit): ScrapeRequest =
ScrapeRequest.newBuilder().let {
block.invoke(it)
it.build()
}
private fun scrapeResponse(block: ScrapeResponse.Builder.() -> Unit): ScrapeResponse =
ScrapeResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun headerData(block: HeaderData.Builder.() -> Unit): HeaderData =
HeaderData.newBuilder().let {
block.invoke(it)
it.build()
}
private fun chunkData(block: ChunkData.Builder.() -> Unit): ChunkData =
ChunkData.newBuilder().let {
block.invoke(it)
it.build()
}
private fun summaryData(block: SummaryData.Builder.() -> Unit): SummaryData =
SummaryData.newBuilder().let {
block.invoke(it)
it.build()
}
private fun chunkedScrapeResponse(block: ChunkedScrapeResponse.Builder.() -> Unit): ChunkedScrapeResponse =
ChunkedScrapeResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun unregisterPathRequest(block: UnregisterPathRequest.Builder.() -> Unit): UnregisterPathRequest =
UnregisterPathRequest.newBuilder().let {
block.invoke(it)
it.build()
}
internal fun unregisterPathResponse(block: UnregisterPathResponse.Builder.() -> Unit): UnregisterPathResponse =
UnregisterPathResponse.newBuilder().let {
block.invoke(it)
it.build()
}
private fun agentInfo(block: AgentInfo.Builder.() -> Unit): AgentInfo =
AgentInfo.newBuilder().let {
block.invoke(it)
it.build()
}
}
| 4 | null | 23 | 94 | 92ff24c8d2a6955ab11b4f79fcb79c6aea8ff786 | 9,468 | prometheus-proxy | Apache License 2.0 |
app/src/main/java/com/jayeshsolanki/olaplaystudios/ui/portfolio/PortfolioActivity.kt | jayeshsolanki93 | 116,455,630 | false | null | package com.jayeshsolanki.olaplaystudios.ui.portfolio
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import com.jayeshsolanki.olaplaystudios.R
import com.jayeshsolanki.olaplaystudios.util.Constants
import kotlinx.android.synthetic.main.activity_portfolio.*
import kotlinx.android.synthetic.main.toolbar.*
class PortfolioActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_portfolio)
toolbar.title = getString(R.string.activity_portfolio)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
email.setOnClickListener {
val intent = Intent(Intent.ACTION_SENDTO,
Uri.parse(String.format(Constants.MAILTO_URI, Constants.EMAIL)))
intent.putExtra(Intent.EXTRA_SUBJECT, Constants.MAIL_SUBJECT)
intent.putExtra(Intent.EXTRA_TEXT, Constants.MAIL_BODY.trimMargin())
startActivity(intent)
}
github.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(Constants.GITHUB)
startActivity(intent)
}
stackoverflow.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(Constants.STACKOVERFLOW)
startActivity(intent)
}
linkedin.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(Constants.LINKEDIN)
startActivity(intent)
}
twitter.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(Constants.TWITTER)
startActivity(intent)
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| 0 | Kotlin | 2 | 5 | 0c926ad634613420844f479640b116339de0a29c | 2,251 | OlaPlayStudios | The Unlicense |
grazel-gradle-plugin/src/main/kotlin/com/grab/grazel/tasks/internal/FormatBazelBuildFileTask.kt | grab | 379,151,190 | false | {"Kotlin": 813733, "Starlark": 58856, "Java": 644} | /*
* Copyright 2022 Grabtaxi Holdings PTE LTD (GRAB)
*
* 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.grab.grazel.tasks.internal
import com.grab.grazel.util.BUILD_BAZEL
import com.grab.grazel.util.WORKSPACE
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFile
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.process.ExecOperations
import javax.inject.Inject
@CacheableTask
internal open class FormatBazelFileTask
@Inject
constructor(
objectFactory: ObjectFactory,
private val execOperations: ExecOperations,
private val fileSystemOperations: FileSystemOperations,
private val projectLayout: ProjectLayout,
) : DefaultTask() {
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
val inputFile: RegularFileProperty = objectFactory.fileProperty()
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
val buildifierScript: RegularFileProperty = objectFactory.fileProperty()
@get:OutputFile
val outputFile: RegularFileProperty = objectFactory.fileProperty()
@TaskAction
fun action() {
val input = inputFile.get().asFile
if (input.exists()) {
// Create a temp file to not touch the original file
val tmpFile = projectLayout
.buildDirectory
.file("grazel/${input.name}.tmp")
.get()
.asFile
fileSystemOperations.copy {
from(input)
into(tmpFile.parentFile)
rename { tmpFile.name }
}
execOperations.exec {
commandLine = listOf(
buildifierScript.get().asFile.absolutePath,
tmpFile.absolutePath,
)
}
val formattedFile = outputFile.get().asFile
fileSystemOperations.copy {
from(tmpFile)
into(formattedFile.parentFile)
rename { formattedFile.name }
}
}
}
companion object {
private const val FORMAT_BAZEL_FILE_TASK = "formatBazelScripts"
private const val FORMAT_BUILD_BAZEL_FILE_TASK = "formatBuildBazel"
private const val FORMAT_WORK_SPACE_FILE_TASK = "formatWorkSpace"
private fun FormatBazelFileTask.configureConventions(
buildifierScriptProvider: Provider<RegularFile>
) {
group = GRAZEL_TASK_GROUP
buildifierScript.set(buildifierScriptProvider)
}
data class RootFormattingTasks(
val workspace: TaskProvider<FormatBazelFileTask>,
val buildBazel: TaskProvider<FormatBazelFileTask>,
val all: List<TaskProvider<out Task>> = listOf(workspace, buildBazel)
)
fun registerRootFormattingTasks(
project: Project,
buildifierScriptProvider: Provider<RegularFile>,
workspaceFormattingTask: FormatBazelFileTask.() -> Unit,
rootBuildBazelTask: FormatBazelFileTask.() -> Unit,
): RootFormattingTasks {
require(project == project.rootProject) {
"Can only register root formatting tasks on root project"
}
val objects = project.serviceOf<ObjectFactory>()
val exec = project.serviceOf<ExecOperations>()
val fileSystem = project.serviceOf<FileSystemOperations>()
val layout = project.serviceOf<ProjectLayout>()
val workspace = project.tasks.register<FormatBazelFileTask>(
FORMAT_WORK_SPACE_FILE_TASK,
objects, exec, fileSystem, layout
).apply {
configure {
description = "Format $WORKSPACE file"
configureConventions(buildifierScriptProvider)
outputFile.set(
project
.objects
.fileProperty()
.apply { set(project.file(WORKSPACE)) }
)
workspaceFormattingTask(this)
}
}
val buildBazel = project.tasks.register<FormatBazelFileTask>(
FORMAT_BUILD_BAZEL_FILE_TASK,
objects, exec, fileSystem, layout
).apply {
configure {
description = "Format $BUILD_BAZEL file"
configureConventions(buildifierScriptProvider)
outputFile.set(
project
.objects
.fileProperty()
.apply { set(project.file(BUILD_BAZEL)) }
)
rootBuildBazelTask(this)
}
}
return RootFormattingTasks(workspace, buildBazel)
}
/**
* Register formatting task on the given project and provide callbacks to configure it.
*
* @param project The project instance to register for
* @param configureAction Callback to configure the registered task. Can be called multiple times for all registered
* tasks
* @return The created provider for this task.
*/
fun register(
project: Project,
buildifierScriptProvider: Provider<RegularFile>,
configureAction: FormatBazelFileTask.() -> Unit
): TaskProvider<out Task> {
require(project != project.rootProject) {
"Can only register formatting tasks on non-root project"
}
val objects = project.serviceOf<ObjectFactory>()
val exec = project.serviceOf<ExecOperations>()
val fileSystem = project.serviceOf<FileSystemOperations>()
val layout = project.serviceOf<ProjectLayout>()
return project.tasks.register<FormatBazelFileTask>(
FORMAT_BAZEL_FILE_TASK,
objects, exec, fileSystem, layout
).apply {
configure {
description = "Format $BUILD_BAZEL file"
configureConventions(buildifierScriptProvider)
outputFile.set(project.objects.fileProperty().apply {
set(project.file(BUILD_BAZEL))
})
configureAction(this)
}
}
}
}
}
| 11 | Kotlin | 19 | 274 | 6d44b7fc7d5210cc4e4211cfd002547a3126124c | 7,583 | grazel | Apache License 2.0 |
core/src/main/kotlin/sift/core/tree/ActionExt.kt | junkdog | 561,870,959 | false | {"Kotlin": 573369, "Shell": 5738, "Java": 627} | package sift.core.tree
import sift.core.api.Action
fun Action<*, *>.debugTree(): String = toTree().toString()
fun Action<*, *>.toTree(): Tree<String> {
// recursively build tree from action id()
fun buildTree(action: Action<*, *>): Tree<String> {
val tree = Tree(action.id())
when (action) {
is Action.Chain<*> -> {
action.actions.map(::buildTree).forEach(tree::add)
}
is Action.Compose<*, *, *> -> {
tree.add(buildTree(action.a))
tree.add(buildTree(action.b))
}
is Action.Fork<*, *> -> {
tree.add(buildTree(action.forked))
}
is Action.ForkOnEntityExistence<*, *> -> {
tree.add(buildTree(action.forked))
}
else -> Unit
}
return tree
}
return buildTree(this)
} | 5 | Kotlin | 0 | 56 | b486fe82fc07d85355311c13160a9fadc2f65831 | 900 | sift | MIT License |
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/physics/terrain/LowPolyTree.kt | kool-engine | 81,503,047 | false | null | package de.fabmax.kool.demo.physics.terrain
import de.fabmax.kool.math.Mat4f
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Random
import de.fabmax.kool.math.clamp
import de.fabmax.kool.math.spatial.InRadiusTraverser
import de.fabmax.kool.math.spatial.pointKdTree
import de.fabmax.kool.scene.geometry.MeshBuilder
import de.fabmax.kool.scene.geometry.simpleShape
import de.fabmax.kool.util.ColorGradient
import de.fabmax.kool.util.MdColor
import kotlin.math.*
class LowPolyTree(seed: Int = 1337) {
val rand = Random(seed)
var baseStrength = 300f
fun generateNodes(pose: Mat4f): Node {
val root = Node(null, 0)
root.setStrength(baseStrength, baseStrength)
root.pose.set(pose)
root.pose.rotate(rand.randomF(-3f, 3f), 0f, rand.randomF(-3f, 3f))
var tips = listOf(root)
while (tips.isNotEmpty()) {
tips = grow(tips)
}
return root
}
fun trunkMesh(root: Node, tint: Float, target: MeshBuilder) {
target.apply {
color = MdColor.BROWN toneLin (500 + (tint * 300f).toInt())
profile {
simpleShape(true) {
for (i in 0..5) {
val ang = (i / 6f) * 2f * PI.toFloat()
xz(sin(ang), cos(ang))
}
}
fun sampleNode(node: Node, connect: Boolean) {
val r = max(node.strength / 2000f, 0.002f).pow(0.5f)
vertexModFun = {
val nodeHeight = (node.y - root.y)
val senseByHeight = nodeHeight / 50f
val senseByStrength = (1f - node.relStrength).pow(2) * (nodeHeight / 5f).clamp(0f, 1f)
getFloatAttribute(Wind.WIND_SENSITIVITY)?.f = (senseByStrength + senseByHeight).clamp(0f, 1f)
}
withTransform {
transform.set(node.pose)
transform.scale(r)
sample(connect)
}
}
val startNodes = mutableListOf(root)
while (startNodes.isNotEmpty()) {
var it = startNodes.removeAt(startNodes.lastIndex)
it.parent?.let { sampleNode(it, false) }
while (true) {
sampleNode(it, true)
if (it.children.isNotEmpty()) {
if (it.children.size > 1) {
startNodes += it.children[1]
}
it = it.children[0]
} else {
break
}
}
}
}
}
}
fun leafMesh(root: Node, tint: Float, target: MeshBuilder) {
val nodes = mutableListOf<Node>()
fun traverseTree(node: Node) {
if (node.relStrength < 0.3f && node.y - root.y > 1.5f) {
nodes += node
}
node.children.forEach { traverseTree(it) }
}
traverseTree(root)
val tree = pointKdTree(nodes)
val trav = InRadiusTraverser<Node>()
val leafColorRange = ColorGradient(0f to (MdColor.LIGHT_GREEN tone 900), 0.8f to MdColor.LIGHT_GREEN, 1f to MdColor.LIME)
target.apply {
vertexModFun = {
getFloatAttribute(Wind.WIND_SENSITIVITY)?.f = 1f
}
nodes.forEach {
trav.setup(it, 3f).traverse(tree)
val p = 1f - (trav.result.size / 17f).clamp(0.0f, 0.97f)
val pop = rand.randomF() < p
if (pop || it.children.isEmpty()) {
color = leafColorRange.getColor((1f - tint) + rand.randomF(-0.25f, 0.25f)).toLinear()
addLeafSphere(it, 1.35f + p * p * p, this)
}
}
}
}
private fun addLeafSphere(node: Node, leafR: Float, target: MeshBuilder) {
target.apply {
withTransform {
transform.set(node.pose)
val rotAx = MutableVec3f(rand.randomF(-1f, 1f), rand.randomF(-1f, 1f), rand.randomF(-1f, 1f)).norm()
rotate(rand.randomF(0f, 360f), rotAx)
scale(rand.randomF(0.6f, 1f), rand.randomF(0.6f, 1f), rand.randomF(0.6f, 1f))
icoSphere {
steps = 0
radius = leafR
}
}
}
}
private fun grow(leafs: List<Node>): List<Node> {
val newLeafs = mutableListOf<Node>()
leafs.forEach { leaf ->
if (leaf.strength > 0f) {
if (shouldFork(leaf)) {
val splitLeafs = fork(leaf)
leaf.children += splitLeafs
newLeafs += splitLeafs
} else {
val next = Node(leaf, leaf.depth + 1)
next.setStrength(leaf.strength, baseStrength)
leaf.children += next
newLeafs += next
}
}
}
newLeafs.forEach { grow(it) }
return newLeafs
}
private fun grow(node: Node) {
if (node.parent?.parent != null) {
val maxTurn = 2f + (1f - node.relStrength).pow(2) * 10f
node.pose.rotate(rand.randomF(-maxTurn, maxTurn), 0f, rand.randomF(-maxTurn, maxTurn))
}
val growLen = 1f + max(0f, node.strength / 200f)
node.pose.translate(0f, growLen, 0f)
node.updatePosition()
val str = min(node.strength - 5f, node.strength * 0.92f)
node.setStrength(str, baseStrength)
}
private fun fork(node: Node): List<Node> {
var splitW = rand.randomF(0.1f, 0.9f)
if (splitW < 0.5f) {
splitW = 1f - splitW
}
val forkAng = rand.randomF(25f, 40f) + (1f - node.relStrength) * 40f * rand.randomF(0.5f, 1f)
val forkAx = MutableVec3f()
do {
forkAx.set(rand.randomF(-1f, 1f), 0f, rand.randomF(-1f, 1f))
} while (forkAx.length() > 1f)
forkAx.norm()
val a = Node(node, node.depth + 1)
a.setStrength(node.strength * splitW, baseStrength)
a.pose.rotate(forkAng * (1f - splitW), forkAx)
val b = Node(node, node.depth + 1)
b.setStrength(node.strength * (1f - splitW), baseStrength)
b.pose.rotate(-forkAng * splitW, forkAx)
return listOf(a, b)
}
private fun shouldFork(node: Node): Boolean {
if (node.strength < 10f) {
return false
}
var noFork = 0
var it = node.parent
while (it != null && !it.isFork()) {
noFork++
it = it.parent
}
val thresh = min(0.9f - noFork / 4f, node.relStrength.pow(2))
return rand.randomF() > thresh
}
class Node(val parent: Node?, val depth: Int) : MutableVec3f() {
val pose = Mat4f()
val children = mutableListOf<Node>()
var strength = 0f
var relStrength = 0f
init {
if (parent != null) {
strength = parent.strength
pose.set(parent.pose)
}
}
fun updatePosition() {
pose.transform(set(ZERO))
}
fun setStrength(strength: Float, baseStrength: Float) {
this.strength = strength
this.relStrength = (strength / baseStrength).clamp(0f, 1f)
}
fun isFork() = children.size > 1
fun isLeaf() = children.isEmpty()
}
} | 9 | null | 20 | 303 | 8d05acd3e72ff2fc115d0939bf021a5f421469a5 | 7,677 | kool | Apache License 2.0 |
src/test/kotlin/com/enniovisco/Stubs.kt | ennioVisco | 444,874,188 | false | {"Kotlin": 105477, "HTML": 3038, "Shell": 1983, "Java": 802, "Handlebars": 497} | package com.enniovisco
import io.github.moonlightsuite.moonlight.offline.signal.*
import java.util.function.*
val alwaysTrueSignal = run {
val signal = SpatialTemporalSignal<List<Boolean>>(9)
signal.add(0.0) { listOf(true) }
signal.add(1.0) { listOf(true) }
signal
}
val alwaysFalseSignal = run {
val signal = SpatialTemporalSignal<List<Boolean>>(9)
signal.add(0.0) { listOf(false) }
signal.add(1.0) { listOf(false) }
signal
}
val alwaysTrueThenAlwaysFalse = run {
val signal = SpatialTemporalSignal<List<Boolean>>(9)
signal.add(0.0) { listOf(true) }
signal.add(1.0) { listOf(false) }
signal
}
fun evenLocationsAreTrueSignal(size: Int) =
createStubSignal(size) { _, location ->
location % 2 == 0
}
private fun <T> createStubSignal(
locations: Int,
f: BiFunction<Double, Int, T>
)
: SpatialTemporalSignal<T> {
val s = SpatialTemporalSignal<T>(locations)
for (time in 0..1) {
val dTime = time.toDouble()
s.add(dTime) { f.apply(dTime, it) }
}
return s
}
| 0 | Kotlin | 0 | 3 | 9f7363c5adfda168d956e15c68559842b56e506b | 1,069 | webmonitor | MIT License |
app/src/main/java/com/vedworx/sastantflx/fragments/LandingPage.kt | vedantmamgain | 416,591,123 | false | null | package com.vedworx.sastantflx.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.vedworx.sastantflx.R
import com.vedworx.sastantflx.activities.seriesdetailed
import com.vedworx.sastantflx.adapters.recyclerviewseriesscreen
import com.vedworx.sastantflx.interfaces.seriesclicklistener
import com.vedworx.sastantflx.models.series
import com.vedworx.sastantflx.viewmodel.seriesviewmodel
import kotlinx.android.synthetic.main.series.*
class landingPage : Fragment(),
seriesclicklistener {
private lateinit var viewmodelsave: seriesviewmodel
private var adapter =
recyclerviewseriesscreen()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewmodelsave = ViewModelProviders.of(this).get(seriesviewmodel::class.java)
return inflater.inflate(
R.layout.series,
container,
false
)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewmodelsave.fetchSeries()
seriesrecyclerview.adapter = adapter
adapter.listener = this
viewmodelsave.serieslisiting.observe(viewLifecycleOwner, Observer {
adapter.setSeries(it)
loaderofLanding.stopShimmer()
loaderofLanding.visibility=View.GONE
})
}
override fun onseriesitemclicked(view: View, seriesmodel: series) {
when (view.id) {
R.id.seasonimageview -> {
val intent = Intent(this.context, seriesdetailed::class.java)
intent.putExtra("idd", seriesmodel.id)
intent.putExtra("name", seriesmodel.name)
startActivity(intent)
}
}
}
} | 1 | Kotlin | 1 | 1 | e7b798119ffc9f9bb4ffa62e680f643de1ca7cbc | 2,048 | SastaNetflix | MIT License |
template/DayXTest.kt | EmRe-One | 442,916,831 | false | null | package tr.emreone.adventofcode.days
import tr.emreone.utils.Resources
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class Day$1Test {
@Test
fun part1() {
val input = Resources.resourceAsList("day$1_example.txt")
assertEquals(-1, Day$1.part1(input), "Day$1, Part1 should be -1.")
}
@Test
fun part2() {
val input = Resources.resourceAsList("day$1_example.txt")
assertEquals(-1, Day$1.part2(input), "Day$1, Part2 should be -1.")
}
} | 0 | Kotlin | 0 | 0 | aee38364ca1827666949557acb15ae3ea21881a1 | 530 | kotlin-utils | Apache License 2.0 |
play-kml-tour/src/main/java/com/esri/arcgismaps/sample/playkmltour/MainActivity.kt | Esri | 530,805,756 | false | {"Kotlin": 900529, "Python": 31233, "Java": 9909, "Dockerfile": 620, "Ruby": 597} | /* Copyright 2023 Esri
*
* 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.esri.arcgismaps.sample.playkmltour
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.mapping.ArcGISScene
import com.arcgismaps.mapping.ArcGISTiledElevationSource
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Surface
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.ViewpointType
import com.arcgismaps.mapping.kml.KmlContainer
import com.arcgismaps.mapping.kml.KmlDataset
import com.arcgismaps.mapping.kml.KmlNode
import com.arcgismaps.mapping.kml.KmlTour
import com.arcgismaps.mapping.kml.KmlTourController
import com.arcgismaps.mapping.kml.KmlTourStatus
import com.arcgismaps.mapping.layers.KmlLayer
import com.esri.arcgismaps.sample.playkmltour.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val provisionPath: String by lazy {
getExternalFilesDir(null)?.path.toString() + File.separator + getString(R.string.app_name)
}
// set up data binding for the activity
private val activityMainBinding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_main)
}
private val sceneView by lazy {
activityMainBinding.sceneView
}
private val playPauseButton by lazy {
activityMainBinding.playPauseButton
}
private val resetTourButton by lazy {
activityMainBinding.resetTourButton
}
private val tourStatusTV by lazy {
activityMainBinding.tourStatusTV
}
private val tourProgressBar by lazy {
activityMainBinding.tourProgressBar
}
private var initialViewpoint: Viewpoint? = null
private val kmlTourController = KmlTourController()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// authentication with an API key or named user is
// required to access basemaps and other location services
ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.API_KEY)
lifecycle.addObserver(sceneView)
// add elevation data
val surface = Surface().apply {
elevationSources.add(ArcGISTiledElevationSource(getString(R.string.world_terrain_service)))
}
// create a scene and set the surface
sceneView.scene = ArcGISScene(BasemapStyle.ArcGISImagery).apply {
baseSurface = surface
}
// add a KML layer from a KML dataset with a KML tour
val kmlDataset = KmlDataset(provisionPath + getString(R.string.kml_tour_path))
val kmlLayer = KmlLayer(kmlDataset)
// add the layer to the scene view's operational layers
sceneView.scene?.operationalLayers?.add(kmlLayer)
// load the KML layer
lifecycleScope.launch {
kmlLayer.load().onFailure {
showError(it.message.toString())
}.onSuccess {
// get the first loaded KML tour
val kmlTour = findFirstKMLTour(kmlDataset.rootNodes)
if (kmlTour == null) {
showError("Cannot find KML tour in dataset")
return@onSuccess
}
// collect changes in KML tour status
collectKmlTourStatus(kmlTour)
// set the KML tour to the controller
kmlTourController.tour = kmlTour
}
}
resetTourButton.setOnClickListener {
// set tour to the initial viewpoint
initialViewpoint?.let { sceneView.setViewpoint(it) }
// reset tour controller
kmlTourController.reset()
}
playPauseButton.setOnClickListener {
// button was clicked when tour was playing
if (kmlTourController.tour?.status?.value == KmlTourStatus.Playing)
// pause KML tour
kmlTourController.pause()
else
// play KML tour
kmlTourController.play()
}
}
/**
* Recursively searches for the first KML tour in a list of [kmlNodes].
* Returns the first [KmlTour], or null if there are no tours.
*/
private fun findFirstKMLTour(kmlNodes: List<KmlNode>): KmlTour? {
kmlNodes.forEach { node ->
if (node is KmlTour)
return node
else if (node is KmlContainer)
return findFirstKMLTour(node.childNodes)
}
return null
}
/**
* Collects KmlTourStatus events from the [kmlTour] and then calls
* showKmlTourStatus()
*/
private fun collectKmlTourStatus(kmlTour: KmlTour) = lifecycleScope.launch {
kmlTour.status.collect { kmlTourStatus ->
when (kmlTourStatus) {
KmlTourStatus.Completed -> {
showKmlTourStatus("Completed", isResetEnabled = false, isPlayingTour = false)
}
KmlTourStatus.Initialized -> {
showKmlTourStatus("Initialized", isResetEnabled = false, isPlayingTour = false)
}
KmlTourStatus.Paused -> {
showKmlTourStatus("Paused", isResetEnabled = true, isPlayingTour = false)
}
KmlTourStatus.Playing -> {
showKmlTourStatus("Playing", isResetEnabled = true, isPlayingTour = true)
// set the tour's initial viewpoint
if (initialViewpoint == null) {
initialViewpoint = sceneView.getCurrentViewpoint(
ViewpointType.BoundingGeometry
)
}
}
else -> {}
}
}
}
/**
* Displays the KML tour status using the [kmlTourStatus], display [resetTourButton]
* if [isResetEnabled] and set [playPauseButton] based on [isPlayingTour].
*/
private fun showKmlTourStatus(
kmlTourStatus: String,
isResetEnabled: Boolean,
isPlayingTour: Boolean
) {
// set the KML tour status
tourStatusTV.text = String.format("Tour status: %s", kmlTourStatus)
// enable the buttons
resetTourButton.isEnabled = isResetEnabled
playPauseButton.isEnabled = true
// show pause button if true
if (isPlayingTour) {
playPauseButton.apply {
// set button icon
icon = AppCompatResources.getDrawable(
this@MainActivity,
R.drawable.ic_round_pause_24
)
// set button text
text = String.format("Pause")
}
} else { // show play button if false
playPauseButton.apply {
// set button icon
icon = AppCompatResources.getDrawable(
this@MainActivity,
R.drawable.ic_round_play_arrow_24
)
// set button text
text = String.format("Play")
}
}
// get progress of tour every second
lifecycleScope.launch {
// run as long as KML tour status is "Playing"
while (kmlTourStatus == "Playing") {
// get percentage of current position over total duration
val tourProgressInt = ((kmlTourController.currentPosition.value * 100.0)
/ (kmlTourController.totalDuration.value)).roundToInt()
tourProgressBar.progress = tourProgressInt
// set a second delay
delay(1000)
}
}
}
private fun showError(message: String) {
Log.e(localClassName, message)
Snackbar.make(sceneView, message, Snackbar.LENGTH_SHORT).show()
}
}
| 4 | Kotlin | 7 | 43 | 3ad9236362a048d5772e1bed49fbfe2f10038e9e | 8,824 | arcgis-maps-sdk-kotlin-samples | Apache License 2.0 |
src/com/potter/riderunity3dconnector/runConfig/UnityDotNetRemoteConfigurationFactory.kt | van800 | 80,879,090 | false | null | package com.potter.riderunity3dconnector.runConfig
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.project.Project
import com.jetbrains.resharper.run.configurations.DotNetConfigurationFactoryBase
/**
* Created by Ivan.Shakhov on 14.02.2017.
*/
class UnityDotNetRemoteConfigurationFactory(unityMonoRemoteConfigType: UnityMonoRemoteDebugConfigType) : DotNetConfigurationFactoryBase<UnityDotNetRemoteConfiguration>(unityMonoRemoteConfigType){
override fun createTemplateConfiguration(project: Project): RunConfiguration = UnityDotNetRemoteConfiguration(project, this, "")
} | 0 | Kotlin | 2 | 0 | e0bc6cf1ca9f52ff258f73aa1dd34b93429cbca2 | 621 | RiderUnity3DConnector | MIT License |
app/src/main/java/gr/pchasapis/moviedb/mvvm/interactor/base/BaseInteractor.kt | pandelisgreen13 | 210,415,019 | false | {"Kotlin": 110631} | package gr.pchasapis.moviedb.mvvm.interactor.base
open class BaseInteractor : MVVMInteractor {
override fun detach() {}
} | 0 | Kotlin | 0 | 5 | 3becd796af5034f7900718c929a4b2d4beabfca2 | 128 | movieDB | MIT License |
model/src/main/kotlin/org/katan/model/unit/ImageUpdatePolicy.kt | KatanPanel | 182,468,654 | false | null | package org.katan.model.unit
enum class ImageUpdatePolicy(val id: String) {
Always("always"),
Never("never");
companion object {
@JvmStatic
fun getById(id: String): ImageUpdatePolicy {
return values().first { it.id.equals(id, ignoreCase = true) }
}
}
}
| 0 | Kotlin | 5 | 55 | 8e2f39310ec87bf19eed5a8a73b105518cabe7d9 | 309 | Katan | Apache License 2.0 |
app/src/main/java/com/example/nba/data/local/database/NbaDatabase.kt | EvaldasSo | 639,254,729 | false | null | package com.example.nba.data.local.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.nba.data.local.dao.GameMatchDao
import com.example.nba.data.local.dao.GameMatchKeysDao
import com.example.nba.data.local.dao.TeamDao
import com.example.nba.data.local.dao.TeamKeysDao
import com.example.nba.data.local.entity.GameMatchEntity
import com.example.nba.data.local.entity.GameMatchKeysEntity
import com.example.nba.data.local.entity.TeamEntity
import com.example.nba.data.local.entity.TeamKeysEntity
@Database(
entities = [TeamEntity::class, GameMatchEntity::class, GameMatchKeysEntity::class, TeamKeysEntity::class],
version = 9,
exportSchema = false
)
abstract class NbaDatabase: RoomDatabase() {
abstract val dao: TeamDao
abstract fun teamKeysDao(): TeamKeysDao
abstract val gameMatchDao: GameMatchDao
abstract fun gameMatchKeysDao(): GameMatchKeysDao
} | 0 | Kotlin | 0 | 0 | 387c427548a9bc3d92f906f2406019e1bd4d4310 | 924 | NBA-Dashboard | Apache License 2.0 |
livedata-support/src/test/java/com/chibatching/kotpref/livedata/LiveDataSupportTest.kt | VitaliBov | 194,615,533 | true | {"Kotlin": 109293} | package com.chibatching.kotpref.livedata
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.SharedPreferences
import com.chibatching.kotpref.Kotpref
import com.chibatching.kotpref.KotprefModel
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
class LiveDataSupportTest {
class Example : KotprefModel() {
var someProperty by stringPref("default")
var customKeyProperty by intPref(8, "custom_key")
}
lateinit var example: Example
lateinit var context: Context
lateinit var pref: SharedPreferences
@Before
fun setUp() {
context = RuntimeEnvironment.application
Kotpref.init(context)
example = Example()
pref = example.preferences
pref.edit().clear().commit()
}
@After
fun tearDown() {
example.clear()
}
@Test
fun providesDefaultValue() {
val latch = CountDownLatch(1)
val liveData = example.asLiveData(example::someProperty)
liveData.observeForever {
assertThat(it).isEqualTo("default")
latch.countDown()
}
latch.await(1, TimeUnit.SECONDS)
}
@Test
fun providesDefaultValueWithCustomKey() {
val latch = CountDownLatch(1)
val liveData = example.asLiveData(example::customKeyProperty)
liveData.observeForever {
assertThat(it).isEqualTo(8)
latch.countDown()
}
latch.await(1, TimeUnit.SECONDS)
}
@Test
fun firesValueChanges() {
val latch = CountDownLatch(3)
val values = listOf("default", "some value 1", "value 2")
var i = 0
val liveData = example.asLiveData(example::someProperty)
liveData.observeForever {
assertThat(it).isEqualTo(values[i++])
latch.countDown()
}
example.someProperty = values[1]
example.someProperty = values[2]
latch.await(1, TimeUnit.SECONDS)
}
@Test
fun firesValueChangesWithCustomKey() {
val latch = CountDownLatch(3)
val values = listOf(8, 1, 12)
var i = 0
val liveData = example.asLiveData(example::customKeyProperty)
liveData.observeForever {
assertThat(it).isEqualTo(values[i++])
latch.countDown()
}
example.customKeyProperty = values[1]
example.customKeyProperty = values[2]
latch.await(1, TimeUnit.SECONDS)
}
@Test
fun firesLatestValueOnObserve() {
val latch = CountDownLatch(5)
val values = listOf("some value 1", "value 2")
val expectedResults = listOf("default", "default", values[0], values[0], values[1])
var i = 0
val liveData = example.asLiveData(example::someProperty)
val observer = Observer<String> {
assertThat(it).isEqualTo(expectedResults[i++])
latch.countDown()
}
liveData.observeForever(observer)
liveData.removeObserver(observer)
(0..1).forEach {
liveData.observeForever(observer)
example.someProperty = values[it]
liveData.removeObserver(observer)
}
latch.await(1, TimeUnit.SECONDS)
}
@Test
fun firesLatestValueOnObserveWithCustomKey() {
val latch = CountDownLatch(5)
val values = listOf(1, 12)
val expectedResults = listOf(8, 8, values[0], values[0], values[1])
var i = 0
val liveData = example.asLiveData(example::customKeyProperty)
val observer = Observer<Int> {
assertThat(it).isEqualTo(expectedResults[i++])
latch.countDown()
}
liveData.observeForever(observer)
liveData.removeObserver(observer)
(0..1).forEach {
liveData.observeForever(observer)
example.customKeyProperty = values[it]
liveData.removeObserver(observer)
}
latch.await(1, TimeUnit.SECONDS)
}
}
| 0 | Kotlin | 0 | 0 | b00305c813f8a63ac4a0d6ae63564ef6df823410 | 4,294 | Kotpref | Apache License 2.0 |
service/src/main/kotlin/no/nav/su/se/bakover/service/revurdering/RevurderingServiceImpl.kt | navikt | 227,366,088 | false | {"Kotlin": 9408311, "Shell": 4372, "TSQL": 1233, "Dockerfile": 1211} | package no.nav.su.se.bakover.service.revurdering
import arrow.core.Either
import arrow.core.flatMap
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.right
import dokument.domain.Dokument
import dokument.domain.brev.BrevService
import dokument.domain.brev.Brevvalg
import no.nav.su.se.bakover.common.domain.PdfA
import no.nav.su.se.bakover.common.domain.attestering.Attestering
import no.nav.su.se.bakover.common.domain.oppgave.OppgaveId
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.persistence.SessionFactory
import no.nav.su.se.bakover.common.persistence.TransactionContext
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.periode.Periode
import no.nav.su.se.bakover.domain.beregning.Beregning
import no.nav.su.se.bakover.domain.beregning.Månedsberegning
import no.nav.su.se.bakover.domain.grunnlag.Grunnlag
import no.nav.su.se.bakover.domain.grunnlag.fradrag.LeggTilFradragsgrunnlagRequest
import no.nav.su.se.bakover.domain.oppdrag.UtbetalingsinstruksjonForEtterbetalinger
import no.nav.su.se.bakover.domain.oppdrag.simulering.simulerUtbetaling
import no.nav.su.se.bakover.domain.oppgave.OppgaveConfig
import no.nav.su.se.bakover.domain.oppgave.OppgaveService
import no.nav.su.se.bakover.domain.revurdering.AbstraktRevurdering
import no.nav.su.se.bakover.domain.revurdering.AvsluttetRevurdering
import no.nav.su.se.bakover.domain.revurdering.BeregnetRevurdering
import no.nav.su.se.bakover.domain.revurdering.GjenopptaYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.IverksattRevurdering
import no.nav.su.se.bakover.domain.revurdering.KunneIkkeAvslutteRevurdering
import no.nav.su.se.bakover.domain.revurdering.KunneIkkeLeggeTilVedtaksbrevvalg
import no.nav.su.se.bakover.domain.revurdering.LeggTilVedtaksbrevvalg
import no.nav.su.se.bakover.domain.revurdering.OpprettetRevurdering
import no.nav.su.se.bakover.domain.revurdering.Revurdering
import no.nav.su.se.bakover.domain.revurdering.RevurderingTilAttestering
import no.nav.su.se.bakover.domain.revurdering.SimulertRevurdering
import no.nav.su.se.bakover.domain.revurdering.StansAvYtelseRevurdering
import no.nav.su.se.bakover.domain.revurdering.UnderkjentRevurdering
import no.nav.su.se.bakover.domain.revurdering.attestering.KunneIkkeSendeRevurderingTilAttestering
import no.nav.su.se.bakover.domain.revurdering.attestering.SendTilAttesteringRequest
import no.nav.su.se.bakover.domain.revurdering.beregning.KunneIkkeBeregneOgSimulereRevurdering
import no.nav.su.se.bakover.domain.revurdering.beregning.KunneIkkeBeregneRevurdering
import no.nav.su.se.bakover.domain.revurdering.beregning.VurderOmBeløpsendringErStørreEnnEllerLik10ProsentAvGjeldendeUtbetaling
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeForhåndsvarsle
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeLageBrevutkastForAvsluttingAvRevurdering
import no.nav.su.se.bakover.domain.revurdering.brev.KunneIkkeLageBrevutkastForRevurdering
import no.nav.su.se.bakover.domain.revurdering.brev.LeggTilBrevvalgRequest
import no.nav.su.se.bakover.domain.revurdering.brev.lagDokumentKommando
import no.nav.su.se.bakover.domain.revurdering.iverksett.KunneIkkeIverksetteRevurdering
import no.nav.su.se.bakover.domain.revurdering.iverksett.iverksettRevurdering
import no.nav.su.se.bakover.domain.revurdering.oppdater.KunneIkkeOppdatereRevurdering
import no.nav.su.se.bakover.domain.revurdering.oppdater.OppdaterRevurderingCommand
import no.nav.su.se.bakover.domain.revurdering.oppdater.oppdaterRevurdering
import no.nav.su.se.bakover.domain.revurdering.opphør.AnnullerKontrollsamtaleVedOpphørService
import no.nav.su.se.bakover.domain.revurdering.opphør.IdentifiserRevurderingsopphørSomIkkeStøttes
import no.nav.su.se.bakover.domain.revurdering.opprett.KunneIkkeOppretteRevurdering
import no.nav.su.se.bakover.domain.revurdering.opprett.OpprettRevurderingCommand
import no.nav.su.se.bakover.domain.revurdering.opprett.opprettRevurdering
import no.nav.su.se.bakover.domain.revurdering.repo.RevurderingRepo
import no.nav.su.se.bakover.domain.revurdering.service.RevurderingOgFeilmeldingerResponse
import no.nav.su.se.bakover.domain.revurdering.service.RevurderingService
import no.nav.su.se.bakover.domain.revurdering.tilbakekreving.KunneIkkeOppdatereTilbakekrevingsbehandling
import no.nav.su.se.bakover.domain.revurdering.tilbakekreving.OppdaterTilbakekrevingsbehandlingRequest
import no.nav.su.se.bakover.domain.revurdering.tilbakekreving.oppdaterTilbakekrevingsbehandling
import no.nav.su.se.bakover.domain.revurdering.underkjenn.KunneIkkeUnderkjenneRevurdering
import no.nav.su.se.bakover.domain.revurdering.varsel.Varselmelding
import no.nav.su.se.bakover.domain.revurdering.vilkår.bosituasjon.KunneIkkeLeggeTilBosituasjongrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.bosituasjon.LeggTilBosituasjonerRequest
import no.nav.su.se.bakover.domain.revurdering.vilkår.formue.KunneIkkeLeggeTilFormuegrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.fradag.KunneIkkeLeggeTilFradragsgrunnlag
import no.nav.su.se.bakover.domain.revurdering.vilkår.uføre.KunneIkkeLeggeTilUføreVilkår
import no.nav.su.se.bakover.domain.revurdering.vilkår.utenlandsopphold.KunneIkkeLeggeTilUtenlandsopphold
import no.nav.su.se.bakover.domain.sak.SakService
import no.nav.su.se.bakover.domain.sak.lagNyUtbetaling
import no.nav.su.se.bakover.domain.sak.lagUtbetalingForOpphør
import no.nav.su.se.bakover.domain.satser.SatsFactory
import no.nav.su.se.bakover.domain.statistikk.StatistikkEvent
import no.nav.su.se.bakover.domain.statistikk.StatistikkEventObserver
import no.nav.su.se.bakover.domain.statistikk.notify
import no.nav.su.se.bakover.domain.vedtak.VedtakRepo
import no.nav.su.se.bakover.domain.vilkår.FormuegrenserFactory
import no.nav.su.se.bakover.domain.vilkår.Vilkårsvurderinger
import no.nav.su.se.bakover.domain.vilkår.fastopphold.KunneIkkeLeggeFastOppholdINorgeVilkår
import no.nav.su.se.bakover.domain.vilkår.fastopphold.LeggTilFastOppholdINorgeRequest
import no.nav.su.se.bakover.domain.vilkår.flyktning.KunneIkkeLeggeTilFlyktningVilkår
import no.nav.su.se.bakover.domain.vilkår.flyktning.LeggTilFlyktningVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.formue.LeggTilFormuevilkårRequest
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.KunneIkkeLeggeTilInstitusjonsoppholdVilkår
import no.nav.su.se.bakover.domain.vilkår.institusjonsopphold.LeggTilInstitusjonsoppholdVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.KunneIkkeLeggetilLovligOppholdVilkårForRevurdering
import no.nav.su.se.bakover.domain.vilkår.lovligopphold.LeggTilLovligOppholdRequest
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.KunneIkkeLeggeTilOpplysningsplikt
import no.nav.su.se.bakover.domain.vilkår.opplysningsplikt.LeggTilOpplysningspliktRequest
import no.nav.su.se.bakover.domain.vilkår.oppmøte.KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering
import no.nav.su.se.bakover.domain.vilkår.oppmøte.LeggTilPersonligOppmøteVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.pensjon.KunneIkkeLeggeTilPensjonsVilkår
import no.nav.su.se.bakover.domain.vilkår.pensjon.LeggTilPensjonsVilkårRequest
import no.nav.su.se.bakover.domain.vilkår.uføre.LeggTilUførevurderingerRequest
import no.nav.su.se.bakover.domain.vilkår.utenlandsopphold.LeggTilFlereUtenlandsoppholdRequest
import no.nav.su.se.bakover.oppgave.domain.KunneIkkeOppdatereOppgave
import no.nav.su.se.bakover.service.tilbakekreving.TilbakekrevingService
import no.nav.su.se.bakover.service.utbetaling.UtbetalingService
import no.nav.su.se.bakover.service.vedtak.FerdigstillVedtakService
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import person.domain.PersonService
import java.time.Clock
import java.util.UUID
class RevurderingServiceImpl(
private val utbetalingService: UtbetalingService,
private val revurderingRepo: RevurderingRepo,
private val oppgaveService: OppgaveService,
private val personService: PersonService,
private val brevService: BrevService,
private val clock: Clock,
private val vedtakRepo: VedtakRepo,
private val annullerKontrollsamtaleService: AnnullerKontrollsamtaleVedOpphørService,
private val sessionFactory: SessionFactory,
private val formuegrenserFactory: FormuegrenserFactory,
private val sakService: SakService,
private val tilbakekrevingService: TilbakekrevingService,
private val satsFactory: SatsFactory,
private val ferdigstillVedtakService: FerdigstillVedtakService,
) : RevurderingService {
private val log: Logger = LoggerFactory.getLogger(this::class.java)
private val observers: MutableList<StatistikkEventObserver> = mutableListOf()
fun addObserver(observer: StatistikkEventObserver) {
observers.add(observer)
}
fun getObservers(): List<StatistikkEventObserver> = observers.toList()
override fun hentRevurdering(revurderingId: UUID): AbstraktRevurdering? {
return revurderingRepo.hent(revurderingId)
}
override fun opprettRevurdering(
command: OpprettRevurderingCommand,
): Either<KunneIkkeOppretteRevurdering, OpprettetRevurdering> {
return sakService.hentSak(command.sakId).getOrNull()!!
.opprettRevurdering(
command = command,
clock = clock,
).map {
val oppgaveResponse = personService.hentAktørId(it.fnr).getOrElse {
return KunneIkkeOppretteRevurdering.FantIkkeAktørId(it).left()
}.let { aktørId ->
oppgaveService.opprettOppgave(
it.oppgaveConfig(aktørId),
).getOrElse {
return KunneIkkeOppretteRevurdering.KunneIkkeOppretteOppgave(it).left()
}
}
it.leggTilOppgaveId(oppgaveResponse.oppgaveId)
}.map {
revurderingRepo.lagre(it.opprettetRevurdering)
observers.notify(it.statistikkHendelse)
it.opprettetRevurdering
}
}
override fun leggTilUførevilkår(
request: LeggTilUførevurderingerRequest,
): Either<KunneIkkeLeggeTilUføreVilkår, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilUføreVilkår.FantIkkeBehandling.left() }
val uførevilkår = request.toVilkår(
behandlingsperiode = revurdering.periode,
clock = clock,
).getOrElse {
return KunneIkkeLeggeTilUføreVilkår.UgyldigInput(it).left()
}
return revurdering.oppdaterUføreOgMarkerSomVurdert(uførevilkår).mapLeft {
KunneIkkeLeggeTilUføreVilkår.UgyldigTilstand(fra = it.fra, til = it.til)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun leggTilUtenlandsopphold(
request: LeggTilFlereUtenlandsoppholdRequest,
): Either<KunneIkkeLeggeTilUtenlandsopphold, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilUtenlandsopphold.FantIkkeBehandling.left() }
val utenlandsoppholdVilkår = request.tilVilkår(clock).getOrElse {
return it.tilService()
}
return revurdering.oppdaterUtenlandsoppholdOgMarkerSomVurdert(utenlandsoppholdVilkår).mapLeft {
it.tilService()
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
private fun LeggTilFlereUtenlandsoppholdRequest.UgyldigUtenlandsopphold.tilService(): Either<KunneIkkeLeggeTilUtenlandsopphold, Nothing> {
return when (this) {
LeggTilFlereUtenlandsoppholdRequest.UgyldigUtenlandsopphold.OverlappendeVurderingsperioder -> {
KunneIkkeLeggeTilUtenlandsopphold.OverlappendeVurderingsperioder.left()
}
LeggTilFlereUtenlandsoppholdRequest.UgyldigUtenlandsopphold.PeriodeForGrunnlagOgVurderingErForskjellig -> {
KunneIkkeLeggeTilUtenlandsopphold.PeriodeForGrunnlagOgVurderingErForskjellig.left()
}
}
}
private fun Revurdering.KunneIkkeLeggeTilUtenlandsopphold.tilService(): KunneIkkeLeggeTilUtenlandsopphold {
return when (this) {
is Revurdering.KunneIkkeLeggeTilUtenlandsopphold.UgyldigTilstand -> {
KunneIkkeLeggeTilUtenlandsopphold.UgyldigTilstand(fra = this.fra, til = this.til)
}
Revurdering.KunneIkkeLeggeTilUtenlandsopphold.VurderingsperiodeUtenforBehandlingsperiode -> {
KunneIkkeLeggeTilUtenlandsopphold.VurderingsperiodeUtenforBehandlingsperiode
}
Revurdering.KunneIkkeLeggeTilUtenlandsopphold.AlleVurderingsperioderMåHaSammeResultat -> {
KunneIkkeLeggeTilUtenlandsopphold.AlleVurderingsperioderMåHaSammeResultat
}
Revurdering.KunneIkkeLeggeTilUtenlandsopphold.MåVurdereHelePerioden -> {
KunneIkkeLeggeTilUtenlandsopphold.MåVurdereHelePerioden
}
}
}
override fun leggTilOpplysningspliktVilkår(request: LeggTilOpplysningspliktRequest.Revurdering): Either<KunneIkkeLeggeTilOpplysningsplikt, RevurderingOgFeilmeldingerResponse> {
return hent(request.behandlingId).mapLeft {
KunneIkkeLeggeTilOpplysningsplikt.FantIkkeBehandling
}.flatMap { revurdering ->
revurdering.oppdaterOpplysningspliktOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeTilOpplysningsplikt.Revurdering(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
}
override fun leggTilPensjonsVilkår(request: LeggTilPensjonsVilkårRequest): Either<KunneIkkeLeggeTilPensjonsVilkår, RevurderingOgFeilmeldingerResponse> {
return hent(request.behandlingId).mapLeft {
KunneIkkeLeggeTilPensjonsVilkår.FantIkkeBehandling
}.flatMap { revurdering ->
revurdering.oppdaterPensjonsvilkårOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeTilPensjonsVilkår.Revurdering(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
}
override fun leggTilLovligOppholdVilkår(
request: LeggTilLovligOppholdRequest,
): Either<KunneIkkeLeggetilLovligOppholdVilkårForRevurdering, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggetilLovligOppholdVilkårForRevurdering.FantIkkeBehandling.left() }
val vilkår = request.toVilkår(clock)
.getOrElse {
return KunneIkkeLeggetilLovligOppholdVilkårForRevurdering.UgyldigLovligOppholdVilkår(it).left()
}
return revurdering.oppdaterLovligOppholdOgMarkerSomVurdert(vilkår).mapLeft {
KunneIkkeLeggetilLovligOppholdVilkårForRevurdering.Domenefeil(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun leggTilFlyktningVilkår(request: LeggTilFlyktningVilkårRequest): Either<KunneIkkeLeggeTilFlyktningVilkår, RevurderingOgFeilmeldingerResponse> {
return hent(request.behandlingId).mapLeft {
KunneIkkeLeggeTilFlyktningVilkår.FantIkkeBehandling
}.flatMap { revurdering ->
revurdering.oppdaterFlyktningvilkårOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeTilFlyktningVilkår.Revurdering(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
}
override fun leggTilFastOppholdINorgeVilkår(request: LeggTilFastOppholdINorgeRequest): Either<KunneIkkeLeggeFastOppholdINorgeVilkår, RevurderingOgFeilmeldingerResponse> {
return hent(request.behandlingId).mapLeft {
KunneIkkeLeggeFastOppholdINorgeVilkår.FantIkkeBehandling
}.flatMap { revurdering ->
revurdering.oppdaterFastOppholdINorgeOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeFastOppholdINorgeVilkår.Revurdering(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
}
override fun leggTilFradragsgrunnlag(request: LeggTilFradragsgrunnlagRequest): Either<KunneIkkeLeggeTilFradragsgrunnlag, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilFradragsgrunnlag.FantIkkeBehandling.left() }
return revurdering.oppdaterFradragOgMarkerSomVurdert(request.fradragsgrunnlag).mapLeft {
when (it) {
is Revurdering.KunneIkkeLeggeTilFradrag.Valideringsfeil -> KunneIkkeLeggeTilFradragsgrunnlag.KunneIkkeEndreFradragsgrunnlag(
it.feil,
)
is Revurdering.KunneIkkeLeggeTilFradrag.UgyldigTilstand -> KunneIkkeLeggeTilFradragsgrunnlag.UgyldigTilstand(
fra = it.fra,
til = it.til,
)
}
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun leggTilPersonligOppmøteVilkår(request: LeggTilPersonligOppmøteVilkårRequest): Either<KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering, RevurderingOgFeilmeldingerResponse> {
return hent(request.behandlingId).mapLeft {
KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering.FantIkkeBehandling
}.flatMap { revurdering ->
revurdering.oppdaterPersonligOppmøtevilkårOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeTilPersonligOppmøteVilkårForRevurdering.Underliggende(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
}
override fun leggTilBosituasjongrunnlag(request: LeggTilBosituasjonerRequest): Either<KunneIkkeLeggeTilBosituasjongrunnlag, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilBosituasjongrunnlag.FantIkkeBehandling.left() }
val bosituasjongrunnlag = request.toDomain(
clock = clock,
) {
personService.hentPerson(it)
}.getOrElse {
return it.left()
}
return revurdering.oppdaterBosituasjonOgMarkerSomVurdert(bosituasjongrunnlag).mapLeft {
KunneIkkeLeggeTilBosituasjongrunnlag.KunneIkkeLeggeTilBosituasjon(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun leggTilFormuegrunnlag(
request: LeggTilFormuevilkårRequest,
): Either<KunneIkkeLeggeTilFormuegrunnlag, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilFormuegrunnlag.FantIkkeRevurdering.left() }
// TODO("flere_satser mulig å gjøre noe for å unngå casting?")
@Suppress("UNCHECKED_CAST")
val bosituasjon =
revurdering.grunnlagsdata.bosituasjon as List<Grunnlag.Bosituasjon.Fullstendig>
val vilkår = request.toDomain(bosituasjon, revurdering.periode, formuegrenserFactory).getOrElse {
return KunneIkkeLeggeTilFormuegrunnlag.KunneIkkeMappeTilDomenet(it).left()
}
return revurdering.oppdaterFormueOgMarkerSomVurdert(vilkår).mapLeft {
when (it) {
is Revurdering.KunneIkkeLeggeTilFormue.Konsistenssjekk -> {
KunneIkkeLeggeTilFormuegrunnlag.Konsistenssjekk(it.feil)
}
is Revurdering.KunneIkkeLeggeTilFormue.UgyldigTilstand -> {
KunneIkkeLeggeTilFormuegrunnlag.UgyldigTilstand(it.fra, it.til)
}
}
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun leggTilInstitusjonsoppholdVilkår(
request: LeggTilInstitusjonsoppholdVilkårRequest,
): Either<KunneIkkeLeggeTilInstitusjonsoppholdVilkår, RevurderingOgFeilmeldingerResponse> {
val revurdering =
hent(request.behandlingId).getOrElse { return KunneIkkeLeggeTilInstitusjonsoppholdVilkår.FantIkkeBehandling.left() }
return revurdering.oppdaterInstitusjonsoppholdOgMarkerSomVurdert(request.vilkår).mapLeft {
KunneIkkeLeggeTilInstitusjonsoppholdVilkår.Revurdering(it)
}.map {
revurderingRepo.lagre(it)
identifiserFeilOgLagResponse(it)
}
}
override fun defaultTransactionContext(): TransactionContext {
return sessionFactory.newTransactionContext()
}
private fun identifiserFeilOgLagResponse(revurdering: Revurdering): RevurderingOgFeilmeldingerResponse {
val sak = sakService.hentSakForRevurdering(revurderingId = revurdering.id)
val gjeldendeMånedsberegninger = sak.hentGjeldendeMånedsberegninger(
periode = revurdering.periode,
clock = clock,
)
val feilmeldinger = when (revurdering) {
is OpprettetRevurdering -> {
identifiserUtfallSomIkkeStøttes(
vilkårsvurderinger = revurdering.vilkårsvurderinger,
periode = revurdering.periode,
).swap().getOrElse { emptySet() }
}
is BeregnetRevurdering -> {
identifiserUtfallSomIkkeStøttes(
revurderingsperiode = revurdering.periode,
vilkårsvurderinger = revurdering.vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = revurdering.beregning,
).swap().getOrElse { emptySet() }
}
is SimulertRevurdering -> {
identifiserUtfallSomIkkeStøttes(
revurderingsperiode = revurdering.periode,
vilkårsvurderinger = revurdering.vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = revurdering.beregning,
).swap().getOrElse { emptySet() }
}
else -> throw IllegalStateException("Skal ikke kunne lage en RevurderingOgFeilmeldingerResponse fra ${revurdering::class}")
}
return RevurderingOgFeilmeldingerResponse(revurdering, feilmeldinger.toList())
}
override fun oppdaterRevurdering(
command: OppdaterRevurderingCommand,
): Either<KunneIkkeOppdatereRevurdering, OpprettetRevurdering> {
return sakService.hentSakForRevurdering(command.revurderingId)
.oppdaterRevurdering(
command = command,
clock = clock,
).map {
revurderingRepo.lagre(it)
it
}
}
override fun beregnOgSimuler(
revurderingId: UUID,
saksbehandler: NavIdentBruker.Saksbehandler,
skalUtsetteTilbakekreving: Boolean,
): Either<KunneIkkeBeregneOgSimulereRevurdering, RevurderingOgFeilmeldingerResponse> {
val sak = sakService.hentSakForRevurdering(revurderingId)
val originalRevurdering = sak.revurderinger.single { it.id == revurderingId } as Revurdering
return when (originalRevurdering) {
is BeregnetRevurdering, is OpprettetRevurdering, is SimulertRevurdering, is UnderkjentRevurdering -> {
val eksisterendeUtbetalinger = sak.utbetalinger
val gjeldendeVedtaksdata = sak.hentGjeldendeVedtaksdata(
periode = originalRevurdering.periode,
clock = clock,
).getOrElse {
throw IllegalStateException("Fant ikke gjeldende vedtaksdata for sak:${originalRevurdering.sakId}")
}
val beregnetRevurdering = originalRevurdering.beregn(
eksisterendeUtbetalinger = eksisterendeUtbetalinger,
clock = clock,
gjeldendeVedtaksdata = gjeldendeVedtaksdata,
satsFactory = satsFactory,
).getOrElse {
return when (it) {
is KunneIkkeBeregneRevurdering.KanIkkeVelgeSisteMånedVedNedgangIStønaden -> {
KunneIkkeBeregneOgSimulereRevurdering.KanIkkeVelgeSisteMånedVedNedgangIStønaden
}
is KunneIkkeBeregneRevurdering.UgyldigBeregningsgrunnlag -> {
KunneIkkeBeregneOgSimulereRevurdering.UgyldigBeregningsgrunnlag(it.reason)
}
KunneIkkeBeregneRevurdering.KanIkkeHaFradragSomTilhørerEpsHvisBrukerIkkeHarEps -> {
KunneIkkeBeregneOgSimulereRevurdering.KanIkkeHaFradragSomTilhørerEpsHvisBrukerIkkeHarEps
}
}.left()
}
val potensielleVarsel = listOf(
(
eksisterendeUtbetalinger.isNotEmpty() &&
!VurderOmBeløpsendringErStørreEnnEllerLik10ProsentAvGjeldendeUtbetaling(
eksisterendeUtbetalinger = eksisterendeUtbetalinger,
nyBeregning = beregnetRevurdering.beregning,
).resultat &&
!(beregnetRevurdering is BeregnetRevurdering.Opphørt && beregnetRevurdering.opphørSkyldesVilkår())
) to Varselmelding.BeløpsendringUnder10Prosent,
gjeldendeVedtaksdata.let { gammel ->
(gammel.grunnlagsdata.bosituasjon.any { it.harEPS() } && beregnetRevurdering.grunnlagsdata.bosituasjon.none { it.harEPS() }) to Varselmelding.FradragOgFormueForEPSErFjernet
},
)
when (beregnetRevurdering) {
is BeregnetRevurdering.Innvilget -> {
beregnetRevurdering.simuler(
saksbehandler = saksbehandler,
clock = clock,
skalUtsetteTilbakekreving = skalUtsetteTilbakekreving,
simuler = { beregning, uføregrunnlag ->
sak.lagNyUtbetaling(
saksbehandler = saksbehandler,
beregning = beregning,
clock = clock,
utbetalingsinstruksjonForEtterbetaling = UtbetalingsinstruksjonForEtterbetalinger.SåFortSomMulig,
uføregrunnlag = uføregrunnlag,
).let {
simulerUtbetaling(
utbetalingForSimulering = it,
simuler = utbetalingService::simulerUtbetaling,
).map { simuleringsresultat ->
// TODO simulering jah: Returner simuleringsresultatet til saksbehandler.
simuleringsresultat.simulertUtbetaling.simulering
}
}
},
).mapLeft {
KunneIkkeBeregneOgSimulereRevurdering.KunneIkkeSimulere(it)
}.map { simulert ->
revurderingRepo.lagre(simulert)
identifiserFeilOgLagResponse(simulert).leggTil(potensielleVarsel)
}
}
is BeregnetRevurdering.Opphørt -> {
// TODO simulering jah: er tanken at vi skal oppdatere saksbehandler her? Det kan se ut som vi har tenkt det, men aldri fullført.
beregnetRevurdering.simuler(
saksbehandler = saksbehandler,
clock = clock,
skalUtsetteTilbakekreving = skalUtsetteTilbakekreving,
simuler = { opphørsperiode: Periode, behandler: NavIdentBruker.Saksbehandler ->
sak.lagUtbetalingForOpphør(
opphørsperiode = opphørsperiode,
behandler = behandler,
clock = clock,
).let {
simulerUtbetaling(
utbetalingForSimulering = it,
simuler = utbetalingService::simulerUtbetaling,
// TODO simulering jah: Returner simuleringsresultatet til saksbehandler.
).map { it.simulertUtbetaling }
}
},
).mapLeft {
KunneIkkeBeregneOgSimulereRevurdering.KunneIkkeSimulere(it)
}.map { simulert ->
revurderingRepo.lagre(simulert)
identifiserFeilOgLagResponse(simulert).leggTil(potensielleVarsel)
}
}
}
}
else -> return KunneIkkeBeregneOgSimulereRevurdering.UgyldigTilstand(
originalRevurdering::class,
SimulertRevurdering::class,
).left()
}
}
private fun identifiserUtfallSomIkkeStøttes(
revurderingsperiode: Periode,
vilkårsvurderinger: Vilkårsvurderinger,
gjeldendeMånedsberegninger: List<Månedsberegning>,
nyBeregning: Beregning,
) = IdentifiserRevurderingsopphørSomIkkeStøttes.MedBeregning(
revurderingsperiode = revurderingsperiode,
vilkårsvurderinger = vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = nyBeregning,
clock = clock,
).resultat
private fun identifiserUtfallSomIkkeStøttes(
vilkårsvurderinger: Vilkårsvurderinger,
periode: Periode,
) = IdentifiserRevurderingsopphørSomIkkeStøttes.UtenBeregning(
vilkårsvurderinger = vilkårsvurderinger,
periode = periode,
).resultat
override fun lagreOgSendForhåndsvarsel(
revurderingId: UUID,
utførtAv: NavIdentBruker.Saksbehandler,
fritekst: String,
): Either<KunneIkkeForhåndsvarsle, Revurdering> {
val revurdering = hent(revurderingId).getOrElse { return KunneIkkeForhåndsvarsle.FantIkkeRevurdering.left() }
kanSendesTilAttestering(revurdering).getOrElse {
return KunneIkkeForhåndsvarsle.Attestering(it).left()
}
return revurdering.lagForhåndsvarsel(
fritekst = fritekst,
utførtAv = utførtAv,
).mapLeft {
KunneIkkeForhåndsvarsle.UgyldigTilstand
}.flatMap { brevCommand ->
brevService.lagDokument(brevCommand).mapLeft {
KunneIkkeForhåndsvarsle.KunneIkkeGenerereDokument(it)
}
}.flatMap { dokumentUtenMetadata ->
Either.catch {
sessionFactory.withTransactionContext { tx ->
brevService.lagreDokument(
dokument = dokumentUtenMetadata.leggTilMetadata(
Dokument.Metadata(
sakId = revurdering.sakId,
revurderingId = revurdering.id,
),
),
transactionContext = tx,
)
revurderingRepo.lagre(
revurdering = revurdering,
transactionContext = tx,
)
prøvÅOppdatereOppgaveEtterViHarSendtForhåndsvarsel(
revurderingId = revurdering.id,
oppgaveId = revurdering.oppgaveId,
).onLeft {
log.info("Hopper over å oppdatere oppgave for revurdering ${revurdering.id}. Dette vil uansett dukke opp som en journalpost i Gosys.")
}
log.info("Forhåndsvarsel sendt for revurdering ${revurdering.id}")
revurdering
}
}.mapLeft {
if (it is KunneIkkeOppdatereOppgave) {
KunneIkkeForhåndsvarsle.KunneIkkeOppdatereOppgave
} else {
throw it
}
}
}
}
private fun prøvÅOppdatereOppgaveEtterViHarSendtForhåndsvarsel(
revurderingId: UUID,
oppgaveId: OppgaveId,
): Either<KunneIkkeOppdatereOppgave, Unit> {
return oppgaveService.oppdaterOppgave(
oppgaveId = oppgaveId,
beskrivelse = "Forhåndsvarsel er sendt.",
).onLeft {
log.error("Kunne ikke oppdatere oppgave $oppgaveId for revurdering $revurderingId med informasjon om at forhåndsvarsel er sendt")
}.onRight {
log.info("Oppdatert oppgave $oppgaveId for revurdering $revurderingId med informasjon om at forhåndsvarsel er sendt")
}.map { }
}
override fun lagBrevutkastForForhåndsvarsling(
revurderingId: UUID,
utførtAv: NavIdentBruker.Saksbehandler,
fritekst: String,
): Either<KunneIkkeLageBrevutkastForRevurdering, PdfA> {
return hent(revurderingId).mapLeft {
KunneIkkeLageBrevutkastForRevurdering.FantIkkeRevurdering
}.flatMap { revurdering ->
revurdering.lagForhåndsvarsel(
utførtAv = utførtAv,
fritekst = fritekst,
).mapLeft {
KunneIkkeLageBrevutkastForRevurdering.UgyldigTilstand
}.flatMap {
brevService.lagDokument(it).mapLeft {
KunneIkkeLageBrevutkastForRevurdering.KunneIkkeGenererePdf(it)
}.map { it.generertDokument }
}
}
}
override fun oppdaterTilbakekrevingsbehandling(request: OppdaterTilbakekrevingsbehandlingRequest): Either<KunneIkkeOppdatereTilbakekrevingsbehandling, Revurdering> {
val revurdering =
hent(request.revurderingId).getOrElse { throw IllegalArgumentException("Fant ikke revurdering ${request.revurderingId}") }
return revurdering.oppdaterTilbakekrevingsbehandling(request, clock).onRight {
revurderingRepo.lagre(it)
}
}
override fun sendTilAttestering(
request: SendTilAttesteringRequest,
): Either<KunneIkkeSendeRevurderingTilAttestering, Revurdering> {
return hent(request.revurderingId).mapLeft { return KunneIkkeSendeRevurderingTilAttestering.FantIkkeRevurdering.left() }
.flatMap {
sendTilAttestering(
revurdering = it,
saksbehandler = request.saksbehandler,
)
}
}
private fun sendTilAttestering(
revurdering: Revurdering,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeSendeRevurderingTilAttestering, Revurdering> {
kanSendesTilAttestering(revurdering).getOrElse {
return it.left()
}
val aktørId = personService.hentAktørId(revurdering.fnr).getOrElse {
log.error("Fant ikke aktør-id")
return KunneIkkeSendeRevurderingTilAttestering.FantIkkeAktørId.left()
}
val tilordnetRessurs = revurdering.attesteringer.lastOrNull()?.attestant
val oppgaveResponse = oppgaveService.opprettOppgave(
OppgaveConfig.AttesterRevurdering(
saksnummer = revurdering.saksnummer,
aktørId = aktørId,
// Første gang den sendes til attestering er attestant null, de påfølgende gangene vil den være attestanten som har underkjent.
tilordnetRessurs = tilordnetRessurs,
clock = clock,
),
).getOrElse {
log.error("Kunne ikke opprette Attesteringsoppgave. Avbryter handlingen.")
return KunneIkkeSendeRevurderingTilAttestering.KunneIkkeOppretteOppgave.left()
}
oppgaveService.lukkOppgave(revurdering.oppgaveId).mapLeft {
log.error("Kunne ikke lukke oppgaven med id ${revurdering.oppgaveId}, knyttet til revurderingen. Oppgaven må lukkes manuelt.")
}
// TODO endre rekkefølge slik at vi ikke lager/lukker oppgaver før vi har vært innom domenemodellen
val (tilAttestering, statistikkhendelse) = when (revurdering) {
is SimulertRevurdering.Innvilget -> revurdering.tilAttestering(
oppgaveResponse.oppgaveId,
saksbehandler,
).getOrElse {
return KunneIkkeSendeRevurderingTilAttestering.FeilInnvilget(it).left()
}.let {
Pair(it, StatistikkEvent.Behandling.Revurdering.TilAttestering.Innvilget(it))
}
is SimulertRevurdering.Opphørt -> revurdering.tilAttestering(
oppgaveResponse.oppgaveId,
saksbehandler,
).getOrElse {
return KunneIkkeSendeRevurderingTilAttestering.FeilOpphørt(it).left()
}.let {
Pair(it, StatistikkEvent.Behandling.Revurdering.TilAttestering.Opphør(it))
}
is UnderkjentRevurdering.Opphørt -> revurdering.tilAttestering(
oppgaveResponse.oppgaveId,
saksbehandler,
).getOrElse {
return KunneIkkeSendeRevurderingTilAttestering.KanIkkeRegulereGrunnbeløpTilOpphør.left()
}.let {
Pair(it, StatistikkEvent.Behandling.Revurdering.TilAttestering.Opphør(it))
}
is UnderkjentRevurdering.Innvilget -> revurdering.tilAttestering(
oppgaveResponse.oppgaveId,
saksbehandler,
).let {
Pair(it, StatistikkEvent.Behandling.Revurdering.TilAttestering.Innvilget(it))
}
else -> return KunneIkkeSendeRevurderingTilAttestering.UgyldigTilstand(
revurdering::class,
RevurderingTilAttestering::class,
).left()
}
revurderingRepo.lagre(tilAttestering)
statistikkhendelse.also {
observers.notify(it)
}
return tilAttestering.right()
}
private fun kanSendesTilAttestering(revurdering: Revurdering): Either<KunneIkkeSendeRevurderingTilAttestering, Unit> {
val sak = sakService.hentSakForRevurdering(revurderingId = revurdering.id)
val gjeldendeMånedsberegninger = sak.hentGjeldendeMånedsberegninger(
periode = revurdering.periode,
clock = clock,
)
tilbakekrevingService.hentAvventerKravgrunnlag(revurdering.sakId).ifNotEmpty {
return KunneIkkeSendeRevurderingTilAttestering.SakHarRevurderingerMedÅpentKravgrunnlagForTilbakekreving(
revurderingId = this.first().avgjort.revurderingId,
).left()
}
return when (revurdering) {
is SimulertRevurdering -> {
identifiserUtfallSomIkkeStøttes(
revurderingsperiode = revurdering.periode,
vilkårsvurderinger = revurdering.vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = revurdering.beregning,
).mapLeft {
KunneIkkeSendeRevurderingTilAttestering.RevurderingsutfallStøttesIkke(it.toList())
}
}
is UnderkjentRevurdering.Innvilget -> {
identifiserUtfallSomIkkeStøttes(
revurderingsperiode = revurdering.periode,
vilkårsvurderinger = revurdering.vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = revurdering.beregning,
).mapLeft {
KunneIkkeSendeRevurderingTilAttestering.RevurderingsutfallStøttesIkke(it.toList())
}
}
is UnderkjentRevurdering.Opphørt -> {
identifiserUtfallSomIkkeStøttes(
revurderingsperiode = revurdering.periode,
vilkårsvurderinger = revurdering.vilkårsvurderinger,
gjeldendeMånedsberegninger = gjeldendeMånedsberegninger,
nyBeregning = revurdering.beregning,
).mapLeft {
KunneIkkeSendeRevurderingTilAttestering.RevurderingsutfallStøttesIkke(it.toList())
}
}
else -> KunneIkkeSendeRevurderingTilAttestering.UgyldigTilstand(
fra = revurdering::class,
til = RevurderingTilAttestering::class,
).left()
}
}
override fun leggTilBrevvalg(request: LeggTilBrevvalgRequest): Either<KunneIkkeLeggeTilVedtaksbrevvalg, Revurdering> {
return hentEllerKast(request.revurderingId)
.let {
it as? LeggTilVedtaksbrevvalg
?: return KunneIkkeLeggeTilVedtaksbrevvalg.UgyldigTilstand(it::class).left()
}
.let {
it.leggTilBrevvalg(request.toDomain()).right()
.onRight { revurderingRepo.lagre(it) }
}
}
override fun lagBrevutkastForRevurdering(
revurderingId: UUID,
): Either<KunneIkkeLageBrevutkastForRevurdering, PdfA> {
return hent(revurderingId)
.mapLeft { KunneIkkeLageBrevutkastForRevurdering.FantIkkeRevurdering }
.flatMap { revurdering ->
brevService.lagDokument(revurdering.lagDokumentKommando(satsFactory = satsFactory, clock = clock))
.mapLeft {
KunneIkkeLageBrevutkastForRevurdering.KunneIkkeGenererePdf(it)
}
.map { it.generertDokument }
}
}
override fun iverksett(
revurderingId: UUID,
attestant: NavIdentBruker.Attestant,
): Either<KunneIkkeIverksetteRevurdering, IverksattRevurdering> {
return sakService.hentSakForRevurdering(revurderingId).iverksettRevurdering(
revurderingId = revurderingId,
attestant = attestant,
clock = clock,
simuler = utbetalingService::simulerUtbetaling,
).flatMap {
it.ferdigstillIverksettelseITransaksjon(
sessionFactory = sessionFactory,
klargjørUtbetaling = utbetalingService::klargjørUtbetaling,
lagreVedtak = vedtakRepo::lagreITransaksjon,
lagreRevurdering = revurderingRepo::lagre,
annullerKontrollsamtale = { sakId, tx ->
annullerKontrollsamtaleService.annuller(sakId, tx)
},
) { observers }.mapLeft {
KunneIkkeIverksetteRevurdering.IverksettelsestransaksjonFeilet(it)
}
}
}
override fun underkjenn(
revurderingId: UUID,
attestering: Attestering.Underkjent,
): Either<KunneIkkeUnderkjenneRevurdering, UnderkjentRevurdering> {
val revurdering =
hent(revurderingId).getOrElse { return KunneIkkeUnderkjenneRevurdering.FantIkkeRevurdering.left() }
if (revurdering !is RevurderingTilAttestering) {
return KunneIkkeUnderkjenneRevurdering.UgyldigTilstand(
revurdering::class,
RevurderingTilAttestering::class,
).left()
}
if (revurdering.saksbehandler.navIdent == attestering.attestant.navIdent) {
return KunneIkkeUnderkjenneRevurdering.SaksbehandlerOgAttestantKanIkkeVæreSammePerson.left()
}
val aktørId = personService.hentAktørId(revurdering.fnr).getOrElse {
log.error("Fant ikke aktør-id for revurdering: ${revurdering.id}")
return KunneIkkeUnderkjenneRevurdering.FantIkkeAktørId.left()
}
val oppgaveResponse = oppgaveService.opprettOppgave(
OppgaveConfig.Revurderingsbehandling(
saksnummer = revurdering.saksnummer,
aktørId = aktørId,
tilordnetRessurs = revurdering.saksbehandler,
clock = clock,
),
).getOrElse {
log.error("revurdering ${revurdering.id} ble ikke underkjent. Klarte ikke opprette behandlingsoppgave")
return@underkjenn KunneIkkeUnderkjenneRevurdering.KunneIkkeOppretteOppgave.left()
}
val underkjent = revurdering.underkjenn(attestering, oppgaveResponse.oppgaveId)
revurderingRepo.lagre(underkjent)
val eksisterendeOppgaveId = revurdering.oppgaveId
oppgaveService.lukkOppgave(eksisterendeOppgaveId).mapLeft {
log.error("Kunne ikke lukke attesteringsoppgave $eksisterendeOppgaveId ved underkjenning av revurdering $revurderingId. Dette må gjøres manuelt.")
}.map {
log.info("Lukket attesteringsoppgave $eksisterendeOppgaveId ved underkjenning av revurdering $revurderingId")
}
when (underkjent) {
is UnderkjentRevurdering.Innvilget -> observers.notify(
StatistikkEvent.Behandling.Revurdering.Underkjent.Innvilget(underkjent),
)
is UnderkjentRevurdering.Opphørt -> observers.notify(
StatistikkEvent.Behandling.Revurdering.Underkjent.Opphør(underkjent),
)
}
return underkjent.right()
}
override fun avsluttRevurdering(
revurderingId: UUID,
begrunnelse: String,
brevvalg: Brevvalg.SaksbehandlersValg?,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeAvslutteRevurdering, AbstraktRevurdering> {
return revurderingRepo.hent(revurderingId)?.let {
avsluttRevurdering(
revurdering = it,
begrunnelse = begrunnelse,
brevvalg = brevvalg,
saksbehandler = saksbehandler,
)
} ?: return KunneIkkeAvslutteRevurdering.FantIkkeRevurdering.left()
}
/**
* Denne kan ikke returnere [KunneIkkeAvslutteRevurdering.FantIkkeRevurdering]
*
* @param brevvalg Kun dersom saksbehandler har forhåndsvarslet, må det tas et brevvalg. Dersom det ikke er forhåndsvarslet skal det ikke sendes brev.
*/
private fun avsluttRevurdering(
revurdering: AbstraktRevurdering,
begrunnelse: String,
brevvalg: Brevvalg.SaksbehandlersValg?,
saksbehandler: NavIdentBruker.Saksbehandler,
): Either<KunneIkkeAvslutteRevurdering, AbstraktRevurdering> {
val (avsluttetRevurdering, skalSendeAvslutningsbrev) = when (revurdering) {
is GjenopptaYtelseRevurdering -> {
if (brevvalg != null) return KunneIkkeAvslutteRevurdering.BrevvalgIkkeTillatt.left()
revurdering.avslutt(begrunnelse, Tidspunkt.now(clock), saksbehandler).map {
it to it.skalSendeAvslutningsbrev()
}.getOrElse {
return KunneIkkeAvslutteRevurdering.KunneIkkeLageAvsluttetGjenopptaAvYtelse(it).left()
}
}
is StansAvYtelseRevurdering -> {
if (brevvalg != null) return KunneIkkeAvslutteRevurdering.BrevvalgIkkeTillatt.left()
revurdering.avslutt(begrunnelse, Tidspunkt.now(clock), saksbehandler).map {
it to it.skalSendeAvslutningsbrev()
}.getOrElse {
return KunneIkkeAvslutteRevurdering.KunneIkkeLageAvsluttetStansAvYtelse(it).left()
}
}
is Revurdering -> revurdering.avslutt(begrunnelse, brevvalg, Tidspunkt.now(clock), saksbehandler).map {
it to it.skalSendeAvslutningsbrev()
}.getOrElse {
return KunneIkkeAvslutteRevurdering.KunneIkkeLageAvsluttetRevurdering(it).left()
}
}
if (avsluttetRevurdering is Revurdering) {
oppgaveService.lukkOppgave(avsluttetRevurdering.oppgaveId).mapLeft {
log.error("Kunne ikke lukke oppgave ${avsluttetRevurdering.oppgaveId} ved avslutting av revurdering ${revurdering.id}. Dette må gjøres manuelt.")
}.map {
log.info("Lukket oppgave ${avsluttetRevurdering.oppgaveId} ved avslutting av revurdering ${revurdering.id}..")
}
}
val resultat = if (avsluttetRevurdering is Revurdering && skalSendeAvslutningsbrev) {
brevService.lagDokument(avsluttetRevurdering.lagDokumentKommando(satsFactory = satsFactory, clock = clock))
.mapLeft {
return KunneIkkeAvslutteRevurdering.KunneIkkeLageDokument.left()
}.map { dokument ->
val dokumentMedMetaData = dokument.leggTilMetadata(
metadata = Dokument.Metadata(
sakId = revurdering.sakId,
revurderingId = revurdering.id,
),
)
sessionFactory.withTransactionContext {
brevService.lagreDokument(dokumentMedMetaData, it)
revurderingRepo.lagre(avsluttetRevurdering, it)
}
}
avsluttetRevurdering.right()
} else {
revurderingRepo.lagre(avsluttetRevurdering)
avsluttetRevurdering.right()
}
val event: StatistikkEvent? = when (val result = resultat.getOrElse { null }) {
is AvsluttetRevurdering -> StatistikkEvent.Behandling.Revurdering.Avsluttet(result, saksbehandler)
is GjenopptaYtelseRevurdering.AvsluttetGjenoppta -> StatistikkEvent.Behandling.Gjenoppta.Avsluttet(result)
is StansAvYtelseRevurdering.AvsluttetStansAvYtelse -> StatistikkEvent.Behandling.Stans.Avsluttet(result)
else -> null
}
event?.let {
observers.forEach { observer ->
observer.handle(it)
}
}
return resultat
}
override fun lagBrevutkastForAvslutting(
revurderingId: UUID,
fritekst: String,
avsluttetAv: NavIdentBruker,
): Either<KunneIkkeLageBrevutkastForAvsluttingAvRevurdering, Pair<Fnr, PdfA>> {
val revurdering = hent(revurderingId)
.getOrElse { return KunneIkkeLageBrevutkastForAvsluttingAvRevurdering.FantIkkeRevurdering.left() }
// Lager en midlertidig avsluttet revurdering for å konstruere brevet - denne skal ikke lagres
val avsluttetRevurdering = revurdering.avslutt(
begrunnelse = "",
brevvalg = Brevvalg.SaksbehandlersValg.SkalSendeBrev.InformasjonsbrevMedFritekst(fritekst),
tidspunktAvsluttet = Tidspunkt.now(clock),
avsluttetAv = avsluttetAv,
).getOrElse {
return KunneIkkeLageBrevutkastForAvsluttingAvRevurdering.KunneIkkeAvslutteRevurdering(it).left()
}
return brevService.lagDokument(avsluttetRevurdering.lagDokumentKommando(satsFactory, clock)).mapLeft {
KunneIkkeLageBrevutkastForAvsluttingAvRevurdering.KunneIkkeLageDokument(it)
}.map {
Pair(avsluttetRevurdering.fnr, it.generertDokument)
}
}
private fun hentEllerKast(id: UUID): Revurdering {
return hent(id).getOrElse { throw IllegalArgumentException("Fant ikke revurdering med id $id") }
}
private fun hent(id: UUID): Either<KunneIkkeHenteRevurdering, Revurdering> {
return revurderingRepo.hent(id)
?.let { if (it is Revurdering) it.right() else KunneIkkeHenteRevurdering.IkkeInstansAvRevurdering.left() }
?: KunneIkkeHenteRevurdering.FantIkkeRevurdering.left()
}
sealed class KunneIkkeHenteRevurdering {
data object IkkeInstansAvRevurdering : KunneIkkeHenteRevurdering()
data object FantIkkeRevurdering : KunneIkkeHenteRevurdering()
}
}
| 9 | Kotlin | 1 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 52,884 | su-se-bakover | MIT License |
src/main/kotlin/run-configuration-options.kt | afucher | 685,113,896 | false | {"Clojure": 77619, "Kotlin": 2095} | package com.github.clojure_repl.intellij.configuration
import com.intellij.execution.configurations.RunConfigurationOptions
class ReplRemoteRunOptions : RunConfigurationOptions() {
private var nreplHostOption = string("localhost").provideDelegate(this, "nreplHost")
private var nreplPortOption = string("").provideDelegate(this, "nreplPort")
private var projectOption = string("").provideDelegate(this, "project")
private var modeOption = string("manual-config").provideDelegate(this, "mode")
var nreplHost: String
get() = nreplHostOption.getValue(this) ?: "localhost"
set(value) = nreplHostOption.setValue(this, value)
var nreplPort: String
get() = nreplPortOption.getValue(this) ?: ""
set(value) = nreplPortOption.setValue(this, value)
var project: String
get() = projectOption.getValue(this) ?: ""
set(value) = projectOption.setValue(this, value)
var mode: String
get() = modeOption.getValue(this) ?: "manual-config"
set(value) = modeOption.setValue(this, value)
}
class ReplLocalRunOptions : RunConfigurationOptions() {
private var projectOption = string("").provideDelegate(this, "project")
private var projectTypeOption = string("").provideDelegate(this, "projectType")
private var aliasesOption = list<String>().provideDelegate(this, "aliases")
var project: String
get() = projectOption.getValue(this) ?: ""
set(value) = projectOption.setValue(this, value)
var projectType: String?
get() = projectTypeOption.getValue(this)
set(value) = projectTypeOption.setValue(this, value)
var aliases: MutableList<String>
get() = aliasesOption.getValue(this)
set(value) = aliasesOption.setValue(this, value)
}
| 9 | Clojure | 8 | 56 | 9e25ef54f62b781cb2a612ae949531cd1d7d5ce9 | 1,785 | clojure-repl-intellij | MIT License |
feature-dashboard/src/main/java/com/standup/app/dashboard/repo/DashboardRepo.kt | kevalpatel2106 | 109,775,416 | false | null | /*
* Copyright 2018 Keval Patel.
*
* 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.standup.app.dashboard.repo
import com.kevalpatel2106.common.userActivity.DailyActivitySummary
import io.reactivex.Flowable
/**
* Created by Kevalpatel2106 on 25-Dec-17.
*
* @author [kevalpatel2106](https://github.com/kevalpatel2106)
*/
internal interface DashboardRepo {
fun getTodaySummary(): Flowable<DailyActivitySummary>
fun getNextReminderStatus(): String
}
| 18 | Kotlin | 1 | 3 | d4d0313062118521621da5dac90e836f512ddd54 | 1,002 | Stand-Up | Apache License 2.0 |
app/src/main/java/com/dew/aihua/infolist/holder/PlaylistMiniInfoItemHolder.kt | ed828a | 172,828,123 | false | null | package com.dew.aihua.infolist.holder
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.dew.aihua.R
import com.dew.aihua.infolist.adapter.InfoItemBuilder
import com.dew.aihua.player.helper.ImageDisplayConstants
import com.dew.aihua.report.ErrorActivity
import com.dew.aihua.util.NavigationHelper
import de.hdodenhof.circleimageview.CircleImageView
import org.schabi.newpipe.extractor.InfoItem
import org.schabi.newpipe.extractor.playlist.PlaylistInfoItem
/**
* Created by Edward on 3/2/2019.
*/
open class PlaylistMiniInfoItemHolder(infoItemBuilder: InfoItemBuilder, layoutId: Int, parent: ViewGroup) : InfoItemHolder(infoItemBuilder, layoutId, parent) {
val itemThumbnailView: ImageView = itemView.findViewById(R.id.itemThumbnailView)
val itemTitleView: TextView = itemView.findViewById(R.id.itemTitleView)
val itemUploaderView: TextView = itemView.findViewById(R.id.itemUploaderView)
val itemStreamCountView: TextView = itemView.findViewById(R.id.itemStreamCountView)
val itemUploaderThumbnail: CircleImageView? = itemView.findViewById(R.id.detail_uploader_thumbnail_view)
constructor(infoItemBuilder: InfoItemBuilder, parent: ViewGroup) : this(infoItemBuilder, R.layout.list_playlist_mini_item, parent)
override fun updateFromItem(infoItem: InfoItem) {
if (infoItem !is PlaylistInfoItem) return
itemTitleView.text = infoItem.name
itemStreamCountView.text = infoItem.streamCount.toString()
itemUploaderView.text = infoItem.uploaderName
if (itemUploaderThumbnail != null && !TextUtils.isEmpty(infoItem.thumbnailUrl) ) {
itemBuilder.imageLoader.displayImage(
infoItem.thumbnailUrl, itemUploaderThumbnail,
ImageDisplayConstants.DISPLAY_AVATAR_OPTIONS
)
}
itemBuilder.imageLoader
.displayImage(infoItem.thumbnailUrl, itemThumbnailView, ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS)
itemView.setOnClickListener {
itemBuilder.onPlaylistSelectedListener?.selected(infoItem)
}
itemView.isLongClickable = true
itemView.setOnLongClickListener {
itemBuilder.onPlaylistSelectedListener?.held(infoItem)
true
}
}
}
| 0 | Kotlin | 0 | 1 | 1896f46888b5a954b367e83f40b845ce174a2328 | 2,432 | Aihua | Apache License 2.0 |
waltid-openid4vc/src/commonMain/kotlin/id/walt/oid4vc/errors/AuthorizationError.kt | walt-id | 701,058,624 | false | null | package id.walt.oid4vc.errors
import id.walt.oid4vc.requests.AuthorizationRequest
import id.walt.oid4vc.responses.AuthorizationCodeResponse
import id.walt.oid4vc.responses.AuthorizationErrorCode
import id.walt.oid4vc.responses.PushedAuthorizationResponse
class AuthorizationError(
val authorizationRequest: AuthorizationRequest,
val errorCode: AuthorizationErrorCode,
override val message: String? = null
) : Exception() {
fun toAuthorizationErrorResponse() = AuthorizationCodeResponse.error(errorCode, message)
fun toPushedAuthorizationErrorResponse() = PushedAuthorizationResponse.error(errorCode, message)
}
| 24 | null | 46 | 98 | a86bd0c843d594f6afe6e747d3c4de7d8a4789a8 | 633 | waltid-identity | Apache License 2.0 |
src/main/kotlin/com/github/muxiu1997/mjt/validation/Date.kt | MuXiu1997 | 561,190,214 | false | {"Kotlin": 47519} | package com.github.muxiu1997.mjt.validation
import javax.validation.Constraint
import javax.validation.Payload
import kotlin.reflect.KClass
/**
* The annotated element must be a formatted date with specific patterns. Accepts [CharSequence].
*/
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.FIELD,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.TYPE
)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [DateValidator::class])
annotation class Date(
/**
* @return patterns of this date, default is `["yyyy-MM-dd'T'HH:mm:ss"]`
*/
val patterns: Array<String> = ["yyyy-MM-dd'T'HH:mm:ss"],
/**
* @return this date is required or not, default is `true`
*/
val required: Boolean = true,
val message: String = "invalid date",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
| 0 | Kotlin | 0 | 1 | 027fc29705eb62890733440431ed1dbaba87b843 | 1,043 | mjt | MIT License |
work/workmanager-ktx/src/main/java/androidx/work/OneTimeWorkRequest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Always inline ktx extension methods unless we have additional call site costs.
@file:Suppress("NOTHING_TO_INLINE")
package androidx.work
import android.support.annotation.NonNull
import kotlin.reflect.KClass
/**
* Creates a [OneTimeWorkRequest] with the given [Worker].
*/
inline fun <reified W : Worker> OneTimeWorkRequestBuilder() =
OneTimeWorkRequest.Builder(W::class.java)
/**
* Sets an [InputMerger] on the [OneTimeWorkRequest.Builder].
*/
inline fun OneTimeWorkRequest.Builder.setInputMerger(
@NonNull inputMerger: KClass<out InputMerger>
) = setInputMerger(inputMerger.java)
| 0 | null | 1 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 1,222 | androidx | Apache License 2.0 |
graphql-dgs-client/src/test/kotlin/com/netflix/graphql/dgs/client/SSESubscriptionGraphQLClientTest.kt | Netflix | 317,375,887 | false | null | /*
* Copyright 2021 Netflix, 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.netflix.graphql.dgs.client
import com.netflix.graphql.dgs.DgsComponent
import com.netflix.graphql.dgs.DgsSubscription
import com.netflix.graphql.dgs.DgsTypeDefinitionRegistry
import com.netflix.graphql.dgs.autoconfig.DgsAutoConfiguration
import com.netflix.graphql.dgs.subscriptions.graphql.sse.DgsGraphQLSSEAutoConfig
import com.netflix.graphql.dgs.subscriptions.sse.DgsSSEAutoConfig
import graphql.language.FieldDefinition.newFieldDefinition
import graphql.language.ObjectTypeDefinition.newObjectTypeDefinition
import graphql.language.TypeName
import graphql.schema.idl.TypeDefinitionRegistry
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import reactor.core.publisher.Flux
import reactor.test.StepVerifier
@SpringBootTest(
classes = [DgsAutoConfiguration::class, DgsSSEAutoConfig::class, TestApp::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@EnableAutoConfiguration(exclude = [DgsGraphQLSSEAutoConfig::class])
internal class SSESubscriptionGraphQLClientTest {
@LocalServerPort
var port: Int? = null
@Test
fun `A successful subscription should publish ticks`() {
val client = SSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
val reactiveExecuteQuery =
client.reactiveExecuteQuery("subscription {numbers}", emptyMap()).mapNotNull { r -> r.data["numbers"] }
StepVerifier.create(reactiveExecuteQuery)
.expectNext(1, 2, 3)
.expectComplete()
.verify()
}
@Test
fun `An error on the subscription should send the error as a response and end the subscription`() {
val client = SSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
val reactiveExecuteQuery = client.reactiveExecuteQuery("subscription {withError}", emptyMap())
StepVerifier.create(reactiveExecuteQuery)
.consumeNextWith { r -> r.hasErrors() }
.expectComplete()
.verify()
}
@Test
fun `A connection error should result in a WebClientException`() {
val client = SSESubscriptionGraphQLClient("/wrongurl", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.NotFound::class.java) {
client.reactiveExecuteQuery("subscription {withError}", emptyMap()).blockLast()
}
}
@Test
fun `A badly formatted query should result in a WebClientException`() {
val client = SSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.BadRequest::class.java) {
client.reactiveExecuteQuery("invalid query", emptyMap()).blockLast()
}
}
@Test
fun `An invalid query should result in a WebClientException`() {
val client = SSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.BadRequest::class.java) {
client.reactiveExecuteQuery("subscriptions { unkownField }", emptyMap()).blockLast()
}
}
}
@SpringBootApplication
internal open class TestApp {
@DgsComponent
class SubscriptionDataFetcher {
@DgsSubscription
fun numbers(): Flux<Int> {
return Flux.just(1, 2, 3)
}
@DgsSubscription
fun withError(): Flux<Int> {
return Flux.error(IllegalArgumentException("testing"), true)
}
@DgsTypeDefinitionRegistry
fun typeDefinitionRegistry(): TypeDefinitionRegistry {
val newRegistry = TypeDefinitionRegistry()
newRegistry.add(
newObjectTypeDefinition().name("Subscription")
.fieldDefinition(
newFieldDefinition()
.name("numbers")
.type(TypeName("Int")).build()
)
.fieldDefinition(
newFieldDefinition()
.name("withError")
.type(TypeName("Int")).build()
)
.build()
)
return newRegistry
}
}
}
| 88 | null | 289 | 3,037 | bd2d0c524e70a9d1d625d518a94926c7b53a7e7c | 5,319 | dgs-framework | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/contactdiary/ui/edit/ContactDiaryEditLocationsViewModel.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.contactdiary.ui.edit
import androidx.lifecycle.asLiveData
import com.squareup.inject.assisted.AssistedInject
import de.rki.coronawarnapp.contactdiary.model.ContactDiaryLocation
import de.rki.coronawarnapp.contactdiary.storage.entity.ContactDiaryLocationEntity
import de.rki.coronawarnapp.contactdiary.storage.entity.toContactDiaryLocationEntity
import de.rki.coronawarnapp.contactdiary.storage.repo.ContactDiaryRepository
import de.rki.coronawarnapp.exception.ExceptionCategory
import de.rki.coronawarnapp.exception.reporting.report
import de.rki.coronawarnapp.ui.SingleLiveEvent
import de.rki.coronawarnapp.util.coroutine.DispatcherProvider
import de.rki.coronawarnapp.util.viewmodel.CWAViewModel
import de.rki.coronawarnapp.util.viewmodel.SimpleCWAViewModelFactory
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.map
class ContactDiaryEditLocationsViewModel @AssistedInject constructor(
private val contactDiaryRepository: ContactDiaryRepository,
dispatcherProvider: DispatcherProvider
) : CWAViewModel(dispatcherProvider = dispatcherProvider) {
private val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, ex ->
ex.report(ExceptionCategory.INTERNAL, TAG)
}
val locationsLiveData = contactDiaryRepository.locations
.asLiveData(dispatcherProvider.IO)
val navigationEvent = SingleLiveEvent<NavigationEvent>()
val isButtonEnabled = contactDiaryRepository.locations.map { !it.isNullOrEmpty() }
.asLiveData(dispatcherProvider.IO)
val isListVisible = contactDiaryRepository.locations.map { !it.isNullOrEmpty() }
.asLiveData(dispatcherProvider.IO)
fun onDeleteAllLocationsClick() {
navigationEvent.postValue(NavigationEvent.ShowDeletionConfirmationDialog)
}
fun onDeleteAllConfirmedClick() {
launch(coroutineExceptionHandler) {
contactDiaryRepository.deleteAllLocationVisits()
contactDiaryRepository.deleteAllLocations()
}
}
fun onEditLocationClick(location: ContactDiaryLocation) {
navigationEvent.postValue(NavigationEvent.ShowLocationDetailSheet(location.toContactDiaryLocationEntity()))
}
companion object {
private val TAG = ContactDiaryEditLocationsViewModel::class.java.simpleName
}
@AssistedInject.Factory
interface Factory : SimpleCWAViewModelFactory<ContactDiaryEditLocationsViewModel>
sealed class NavigationEvent {
object ShowDeletionConfirmationDialog : NavigationEvent()
data class ShowLocationDetailSheet(val location: ContactDiaryLocationEntity) : NavigationEvent()
}
}
| 6 | null | 8 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 2,674 | cwa-app-android | Apache License 2.0 |
node-kotlin/src/jsMain/kotlin/node/crypto/SecureHeapUsage.kt | karakum-team | 393,199,102 | false | {"Kotlin": 7083457} | // Automatically generated - do not modify!
package node.crypto
sealed external interface SecureHeapUsage {
/**
* The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
*/
var total: Number
/**
* The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
*/
var min: Number
/**
* The total number of bytes currently allocated from the secure heap.
*/
var used: Number
/**
* The calculated ratio of `used` to `total` allocated bytes.
*/
var utilization: Number
}
| 0 | Kotlin | 6 | 26 | 3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18 | 628 | types-kotlin | Apache License 2.0 |
compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AssigningNamedArgumentToVarargChecker.kt | alireza-naghizadeh | 119,830,321 | true | {"Java": 27241287, "Kotlin": 26410083, "JavaScript": 155117, "HTML": 56625, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8587, "Shell": 5436, "CSS": 4679, "Batchfile": 4437} | /*
* Copyright 2010-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 org.jetbrains.kotlin.resolve.calls.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isArrayOrArrayLiteral
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isParameterOfAnnotation
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
class AssigningNamedArgumentToVarargChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
for ((parameterDescriptor, resolvedArgument) in resolvedCall.valueArguments) {
for (argument in resolvedArgument.arguments) {
checkAssignmentOfSingleElementToVararg(argument, parameterDescriptor, context.resolutionContext)
}
}
}
private fun checkAssignmentOfSingleElementToVararg(
argument: ValueArgument,
parameterDescriptor: ValueParameterDescriptor,
context: ResolutionContext<*>
) {
if (!context.languageVersionSettings.supportsFeature(LanguageFeature.AssigningArraysToVarargsInNamedFormInAnnotations)) return
if (!argument.isNamed()) return
if (!parameterDescriptor.isVararg) return
val argumentExpression = argument.getArgumentExpression() ?: return
if (isParameterOfAnnotation(parameterDescriptor)) {
checkAssignmentOfSingleElementInAnnotation(argument, argumentExpression, context)
}
else {
checkAssignmentOfSingleElementInFunction(argument, argumentExpression, context, parameterDescriptor)
}
}
private fun checkAssignmentOfSingleElementInAnnotation(
argument: ValueArgument,
argumentExpression: KtExpression,
context: ResolutionContext<*>
) {
if (isArrayOrArrayLiteral(argument, context)) {
if (argument.hasSpread()) {
context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION.on(argumentExpression))
}
}
else {
context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION.on(argumentExpression))
}
}
private fun checkAssignmentOfSingleElementInFunction(
argument: ValueArgument,
argumentExpression: KtExpression,
context: ResolutionContext<*>,
parameterDescriptor: ValueParameterDescriptor
) {
if (!argument.hasSpread()) {
context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.on(argumentExpression, parameterDescriptor.type))
}
}
private fun ValueArgument.hasSpread() = getSpreadElement() != null
} | 0 | Java | 0 | 1 | cf2e9c70028199ff2446d7b568983e387fb58ef4 | 3,693 | kotlin | Apache License 2.0 |
jstressy-platform/jstressy-impl/jstressy-config-dsl/src/main/kotlin/com/github/timofeevda/jstressy/config/dsl/configScriptDefinition.kt | timofeevda | 126,821,248 | false | {"Kotlin": 267318, "Dockerfile": 1313, "Shell": 214} | package com.github.timofeevda.jstressy.config.dsl
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.api.RefineScriptCompilationConfigurationHandler
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.ScriptCollectedData
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.ScriptConfigurationRefinementContext
import kotlin.script.experimental.api.asSuccess
import kotlin.script.experimental.api.collectedAnnotations
import kotlin.script.experimental.api.compilerOptions
import kotlin.script.experimental.api.defaultImports
import kotlin.script.experimental.api.dependencies
import kotlin.script.experimental.api.importScripts
import kotlin.script.experimental.api.onSuccess
import kotlin.script.experimental.api.refineConfiguration
import kotlin.script.experimental.dependencies.CompoundDependenciesResolver
import kotlin.script.experimental.dependencies.DependsOn
import kotlin.script.experimental.dependencies.FileSystemDependenciesResolver
import kotlin.script.experimental.dependencies.Repository
import kotlin.script.experimental.dependencies.maven.MavenDependenciesResolver
import kotlin.script.experimental.dependencies.resolveFromScriptSourceAnnotations
import kotlin.script.experimental.host.FileBasedScriptSource
import kotlin.script.experimental.host.FileScriptSource
import kotlin.script.experimental.jvm.JvmDependency
import kotlin.script.experimental.jvm.dependenciesFromCurrentContext
import kotlin.script.experimental.jvm.jvm
@Target(AnnotationTarget.FILE)
@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class Import(vararg val paths: String)
@KotlinScript(
fileExtension = "kts",
compilationConfiguration = ConfigScriptCompilationConfiguration::class
)
abstract class StressyConfigScriptDefinition
object ConfigScriptCompilationConfiguration : ScriptCompilationConfiguration({
defaultImports(Import::class, DependsOn::class, Repository::class)
jvm {
dependenciesFromCurrentContext(wholeClasspath = true, unpackJarCollections = true)
}
// https://youtrack.jetbrains.com/issue/KT-57907
compilerOptions.append("-Xadd-modules=ALL-MODULE-PATH")
refineConfiguration{
onAnnotations(Import::class, DependsOn::class, Repository::class, handler = RefineConfigurationHandler())
}
})
class RefineConfigurationHandler : RefineScriptCompilationConfigurationHandler {
private val resolver = CompoundDependenciesResolver(FileSystemDependenciesResolver(), MavenDependenciesResolver())
override operator fun invoke(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics<ScriptCompilationConfiguration> =
processAnnotations(context)
private fun processAnnotations(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics<ScriptCompilationConfiguration> {
val annotations = context.collectedData?.get(ScriptCollectedData.collectedAnnotations)?.takeIf { it.isNotEmpty() }
?: return context.compilationConfiguration.asSuccess()
val scriptBaseDir = (context.script as? FileBasedScriptSource)?.file?.parentFile
val importedSources = annotations.flatMap {
(it.annotation as? Import)?.paths?.map { sourceName ->
FileScriptSource(scriptBaseDir?.resolve(sourceName) ?: File(sourceName))
} ?: emptyList()
}
val dependencyAnnotations = annotations.filter { it.annotation is DependsOn || it.annotation is Repository }
if (dependencyAnnotations.isNotEmpty()) {
return runBlocking {
resolver.resolveFromScriptSourceAnnotations(dependencyAnnotations)
}.onSuccess {
ScriptCompilationConfiguration(context.compilationConfiguration) {
if (importedSources.isNotEmpty()) {
importScripts.append(importedSources)
}
dependencies.append(JvmDependency(it))
}.asSuccess()
}
} else {
return ScriptCompilationConfiguration(context.compilationConfiguration) {
if (importedSources.isNotEmpty()) {
importScripts.append(importedSources)
}
}.asSuccess()
}
}
} | 0 | Kotlin | 0 | 2 | 4a8300a7354fbc22e06f1f6ed0a9dc724d6d3bd2 | 4,423 | jstressy | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ec2/CfnRoute.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 140726596} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ec2
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Specifies a route in a route table. For more information, see
* [Routes](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#route-table-routes)
* in the *Amazon VPC User Guide* .
*
* You must specify either a destination CIDR block or prefix list ID. You must also specify exactly
* one of the resources as the target.
*
* If you create a route that references a transit gateway in the same template where you create the
* transit gateway, you must declare a dependency on the transit gateway attachment. The route table
* cannot use the transit gateway until it has successfully attached to the VPC. Add a [DependsOn
* Attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html)
* in the `AWS::EC2::Route` resource to explicitly declare a dependency on the
* `AWS::EC2::TransitGatewayAttachment` resource.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.ec2.*;
* CfnRoute cfnRoute = CfnRoute.Builder.create(this, "MyCfnRoute")
* .routeTableId("routeTableId")
* // the properties below are optional
* .carrierGatewayId("carrierGatewayId")
* .coreNetworkArn("coreNetworkArn")
* .destinationCidrBlock("destinationCidrBlock")
* .destinationIpv6CidrBlock("destinationIpv6CidrBlock")
* .destinationPrefixListId("destinationPrefixListId")
* .egressOnlyInternetGatewayId("egressOnlyInternetGatewayId")
* .gatewayId("gatewayId")
* .instanceId("instanceId")
* .localGatewayId("localGatewayId")
* .natGatewayId("natGatewayId")
* .networkInterfaceId("networkInterfaceId")
* .transitGatewayId("transitGatewayId")
* .vpcEndpointId("vpcEndpointId")
* .vpcPeeringConnectionId("vpcPeeringConnectionId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html)
*/
public open class CfnRoute internal constructor(
internal override val cdkObject: software.amazon.awscdk.services.ec2.CfnRoute,
) : CfnResource(cdkObject), IInspectable {
/**
* The IPv4 CIDR block.
*/
public open fun attrCidrBlock(): String = unwrap(this).getAttrCidrBlock()
/**
* The ID of the carrier gateway.
*/
public open fun carrierGatewayId(): String? = unwrap(this).getCarrierGatewayId()
/**
* The ID of the carrier gateway.
*/
public open fun carrierGatewayId(`value`: String) {
unwrap(this).setCarrierGatewayId(`value`)
}
/**
* The Amazon Resource Name (ARN) of the core network.
*/
public open fun coreNetworkArn(): String? = unwrap(this).getCoreNetworkArn()
/**
* The Amazon Resource Name (ARN) of the core network.
*/
public open fun coreNetworkArn(`value`: String) {
unwrap(this).setCoreNetworkArn(`value`)
}
/**
* The IPv4 CIDR address block used for the destination match.
*/
public open fun destinationCidrBlock(): String? = unwrap(this).getDestinationCidrBlock()
/**
* The IPv4 CIDR address block used for the destination match.
*/
public open fun destinationCidrBlock(`value`: String) {
unwrap(this).setDestinationCidrBlock(`value`)
}
/**
* The IPv6 CIDR block used for the destination match.
*/
public open fun destinationIpv6CidrBlock(): String? = unwrap(this).getDestinationIpv6CidrBlock()
/**
* The IPv6 CIDR block used for the destination match.
*/
public open fun destinationIpv6CidrBlock(`value`: String) {
unwrap(this).setDestinationIpv6CidrBlock(`value`)
}
/**
* The ID of a prefix list used for the destination match.
*/
public open fun destinationPrefixListId(): String? = unwrap(this).getDestinationPrefixListId()
/**
* The ID of a prefix list used for the destination match.
*/
public open fun destinationPrefixListId(`value`: String) {
unwrap(this).setDestinationPrefixListId(`value`)
}
/**
* [IPv6 traffic only] The ID of an egress-only internet gateway.
*/
public open fun egressOnlyInternetGatewayId(): String? =
unwrap(this).getEgressOnlyInternetGatewayId()
/**
* [IPv6 traffic only] The ID of an egress-only internet gateway.
*/
public open fun egressOnlyInternetGatewayId(`value`: String) {
unwrap(this).setEgressOnlyInternetGatewayId(`value`)
}
/**
* The ID of an internet gateway or virtual private gateway attached to your VPC.
*/
public open fun gatewayId(): String? = unwrap(this).getGatewayId()
/**
* The ID of an internet gateway or virtual private gateway attached to your VPC.
*/
public open fun gatewayId(`value`: String) {
unwrap(this).setGatewayId(`value`)
}
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector::unwrap))
}
/**
* The ID of a NAT instance in your VPC.
*/
public open fun instanceId(): String? = unwrap(this).getInstanceId()
/**
* The ID of a NAT instance in your VPC.
*/
public open fun instanceId(`value`: String) {
unwrap(this).setInstanceId(`value`)
}
/**
* The ID of the local gateway.
*/
public open fun localGatewayId(): String? = unwrap(this).getLocalGatewayId()
/**
* The ID of the local gateway.
*/
public open fun localGatewayId(`value`: String) {
unwrap(this).setLocalGatewayId(`value`)
}
/**
* [IPv4 traffic only] The ID of a NAT gateway.
*/
public open fun natGatewayId(): String? = unwrap(this).getNatGatewayId()
/**
* [IPv4 traffic only] The ID of a NAT gateway.
*/
public open fun natGatewayId(`value`: String) {
unwrap(this).setNatGatewayId(`value`)
}
/**
* The ID of a network interface.
*/
public open fun networkInterfaceId(): String? = unwrap(this).getNetworkInterfaceId()
/**
* The ID of a network interface.
*/
public open fun networkInterfaceId(`value`: String) {
unwrap(this).setNetworkInterfaceId(`value`)
}
/**
* The ID of the route table for the route.
*/
public open fun routeTableId(): String = unwrap(this).getRouteTableId()
/**
* The ID of the route table for the route.
*/
public open fun routeTableId(`value`: String) {
unwrap(this).setRouteTableId(`value`)
}
/**
* The ID of a transit gateway.
*/
public open fun transitGatewayId(): String? = unwrap(this).getTransitGatewayId()
/**
* The ID of a transit gateway.
*/
public open fun transitGatewayId(`value`: String) {
unwrap(this).setTransitGatewayId(`value`)
}
/**
* The ID of a VPC endpoint.
*/
public open fun vpcEndpointId(): String? = unwrap(this).getVpcEndpointId()
/**
* The ID of a VPC endpoint.
*/
public open fun vpcEndpointId(`value`: String) {
unwrap(this).setVpcEndpointId(`value`)
}
/**
* The ID of a VPC peering connection.
*/
public open fun vpcPeeringConnectionId(): String? = unwrap(this).getVpcPeeringConnectionId()
/**
* The ID of a VPC peering connection.
*/
public open fun vpcPeeringConnectionId(`value`: String) {
unwrap(this).setVpcPeeringConnectionId(`value`)
}
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.ec2.CfnRoute].
*/
@CdkDslMarker
public interface Builder {
/**
* The ID of the carrier gateway.
*
* You can only use this option when the VPC contains a subnet which is associated with a
* Wavelength Zone.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-carriergatewayid)
* @param carrierGatewayId The ID of the carrier gateway.
*/
public fun carrierGatewayId(carrierGatewayId: String)
/**
* The Amazon Resource Name (ARN) of the core network.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-corenetworkarn)
* @param coreNetworkArn The Amazon Resource Name (ARN) of the core network.
*/
public fun coreNetworkArn(coreNetworkArn: String)
/**
* The IPv4 CIDR address block used for the destination match.
*
* Routing decisions are based on the most specific match. We modify the specified CIDR block to
* its canonical form; for example, if you specify `172.16.58.3/18` , we modify it to
* `192.168.3.11/18` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationcidrblock)
* @param destinationCidrBlock The IPv4 CIDR address block used for the destination match.
*/
public fun destinationCidrBlock(destinationCidrBlock: String)
/**
* The IPv6 CIDR block used for the destination match.
*
* Routing decisions are based on the most specific match.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationipv6cidrblock)
* @param destinationIpv6CidrBlock The IPv6 CIDR block used for the destination match.
*/
public fun destinationIpv6CidrBlock(destinationIpv6CidrBlock: String)
/**
* The ID of a prefix list used for the destination match.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationprefixlistid)
* @param destinationPrefixListId The ID of a prefix list used for the destination match.
*/
public fun destinationPrefixListId(destinationPrefixListId: String)
/**
* [IPv6 traffic only] The ID of an egress-only internet gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-egressonlyinternetgatewayid)
* @param egressOnlyInternetGatewayId [IPv6 traffic only] The ID of an egress-only internet
* gateway.
*/
public fun egressOnlyInternetGatewayId(egressOnlyInternetGatewayId: String)
/**
* The ID of an internet gateway or virtual private gateway attached to your VPC.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-gatewayid)
* @param gatewayId The ID of an internet gateway or virtual private gateway attached to your
* VPC.
*/
public fun gatewayId(gatewayId: String)
/**
* The ID of a NAT instance in your VPC.
*
* The operation fails if you specify an instance ID unless exactly one network interface is
* attached.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-instanceid)
* @param instanceId The ID of a NAT instance in your VPC.
*/
public fun instanceId(instanceId: String)
/**
* The ID of the local gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-localgatewayid)
* @param localGatewayId The ID of the local gateway.
*/
public fun localGatewayId(localGatewayId: String)
/**
* [IPv4 traffic only] The ID of a NAT gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-natgatewayid)
* @param natGatewayId [IPv4 traffic only] The ID of a NAT gateway.
*/
public fun natGatewayId(natGatewayId: String)
/**
* The ID of a network interface.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-networkinterfaceid)
* @param networkInterfaceId The ID of a network interface.
*/
public fun networkInterfaceId(networkInterfaceId: String)
/**
* The ID of the route table for the route.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-routetableid)
* @param routeTableId The ID of the route table for the route.
*/
public fun routeTableId(routeTableId: String)
/**
* The ID of a transit gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-transitgatewayid)
* @param transitGatewayId The ID of a transit gateway.
*/
public fun transitGatewayId(transitGatewayId: String)
/**
* The ID of a VPC endpoint.
*
* Supported for Gateway Load Balancer endpoints only.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcendpointid)
* @param vpcEndpointId The ID of a VPC endpoint.
*/
public fun vpcEndpointId(vpcEndpointId: String)
/**
* The ID of a VPC peering connection.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcpeeringconnectionid)
* @param vpcPeeringConnectionId The ID of a VPC peering connection.
*/
public fun vpcPeeringConnectionId(vpcPeeringConnectionId: String)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.ec2.CfnRoute.Builder =
software.amazon.awscdk.services.ec2.CfnRoute.Builder.create(scope, id)
/**
* The ID of the carrier gateway.
*
* You can only use this option when the VPC contains a subnet which is associated with a
* Wavelength Zone.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-carriergatewayid)
* @param carrierGatewayId The ID of the carrier gateway.
*/
override fun carrierGatewayId(carrierGatewayId: String) {
cdkBuilder.carrierGatewayId(carrierGatewayId)
}
/**
* The Amazon Resource Name (ARN) of the core network.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-corenetworkarn)
* @param coreNetworkArn The Amazon Resource Name (ARN) of the core network.
*/
override fun coreNetworkArn(coreNetworkArn: String) {
cdkBuilder.coreNetworkArn(coreNetworkArn)
}
/**
* The IPv4 CIDR address block used for the destination match.
*
* Routing decisions are based on the most specific match. We modify the specified CIDR block to
* its canonical form; for example, if you specify `172.16.58.3/18` , we modify it to
* `192.168.3.11/18` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationcidrblock)
* @param destinationCidrBlock The IPv4 CIDR address block used for the destination match.
*/
override fun destinationCidrBlock(destinationCidrBlock: String) {
cdkBuilder.destinationCidrBlock(destinationCidrBlock)
}
/**
* The IPv6 CIDR block used for the destination match.
*
* Routing decisions are based on the most specific match.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationipv6cidrblock)
* @param destinationIpv6CidrBlock The IPv6 CIDR block used for the destination match.
*/
override fun destinationIpv6CidrBlock(destinationIpv6CidrBlock: String) {
cdkBuilder.destinationIpv6CidrBlock(destinationIpv6CidrBlock)
}
/**
* The ID of a prefix list used for the destination match.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationprefixlistid)
* @param destinationPrefixListId The ID of a prefix list used for the destination match.
*/
override fun destinationPrefixListId(destinationPrefixListId: String) {
cdkBuilder.destinationPrefixListId(destinationPrefixListId)
}
/**
* [IPv6 traffic only] The ID of an egress-only internet gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-egressonlyinternetgatewayid)
* @param egressOnlyInternetGatewayId [IPv6 traffic only] The ID of an egress-only internet
* gateway.
*/
override fun egressOnlyInternetGatewayId(egressOnlyInternetGatewayId: String) {
cdkBuilder.egressOnlyInternetGatewayId(egressOnlyInternetGatewayId)
}
/**
* The ID of an internet gateway or virtual private gateway attached to your VPC.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-gatewayid)
* @param gatewayId The ID of an internet gateway or virtual private gateway attached to your
* VPC.
*/
override fun gatewayId(gatewayId: String) {
cdkBuilder.gatewayId(gatewayId)
}
/**
* The ID of a NAT instance in your VPC.
*
* The operation fails if you specify an instance ID unless exactly one network interface is
* attached.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-instanceid)
* @param instanceId The ID of a NAT instance in your VPC.
*/
override fun instanceId(instanceId: String) {
cdkBuilder.instanceId(instanceId)
}
/**
* The ID of the local gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-localgatewayid)
* @param localGatewayId The ID of the local gateway.
*/
override fun localGatewayId(localGatewayId: String) {
cdkBuilder.localGatewayId(localGatewayId)
}
/**
* [IPv4 traffic only] The ID of a NAT gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-natgatewayid)
* @param natGatewayId [IPv4 traffic only] The ID of a NAT gateway.
*/
override fun natGatewayId(natGatewayId: String) {
cdkBuilder.natGatewayId(natGatewayId)
}
/**
* The ID of a network interface.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-networkinterfaceid)
* @param networkInterfaceId The ID of a network interface.
*/
override fun networkInterfaceId(networkInterfaceId: String) {
cdkBuilder.networkInterfaceId(networkInterfaceId)
}
/**
* The ID of the route table for the route.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-routetableid)
* @param routeTableId The ID of the route table for the route.
*/
override fun routeTableId(routeTableId: String) {
cdkBuilder.routeTableId(routeTableId)
}
/**
* The ID of a transit gateway.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-transitgatewayid)
* @param transitGatewayId The ID of a transit gateway.
*/
override fun transitGatewayId(transitGatewayId: String) {
cdkBuilder.transitGatewayId(transitGatewayId)
}
/**
* The ID of a VPC endpoint.
*
* Supported for Gateway Load Balancer endpoints only.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcendpointid)
* @param vpcEndpointId The ID of a VPC endpoint.
*/
override fun vpcEndpointId(vpcEndpointId: String) {
cdkBuilder.vpcEndpointId(vpcEndpointId)
}
/**
* The ID of a VPC peering connection.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcpeeringconnectionid)
* @param vpcPeeringConnectionId The ID of a VPC peering connection.
*/
override fun vpcPeeringConnectionId(vpcPeeringConnectionId: String) {
cdkBuilder.vpcPeeringConnectionId(vpcPeeringConnectionId)
}
public fun build(): software.amazon.awscdk.services.ec2.CfnRoute = cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.ec2.CfnRoute.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnRoute {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnRoute(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnRoute): CfnRoute =
CfnRoute(cdkObject)
internal fun unwrap(wrapped: CfnRoute): software.amazon.awscdk.services.ec2.CfnRoute =
wrapped.cdkObject
}
}
| 1 | Kotlin | 0 | 4 | a18731816a3ec710bc89fb8767d2ab71cec558a6 | 21,981 | kotlin-cdk-wrapper | Apache License 2.0 |
guides/micronaut-oracle-cloud-streaming/chess-listener/kotlin/src/main/kotlin/example/micronaut/chess/repository/OracleGameStateRepository.kt | micronaut-projects | 326,986,278 | false | {"Java": 2324179, "Groovy": 1117014, "Kotlin": 977645, "JavaScript": 110091, "HTML": 93851, "CSS": 30567, "Shell": 5473, "AppleScript": 1063, "Python": 47} | /*
* Copyright 2017-2024 original authors
*
* 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 example.micronaut.chess.repository
import io.micronaut.context.annotation.Primary
import io.micronaut.context.annotation.Requires
import io.micronaut.context.env.Environment.ORACLE_CLOUD
import io.micronaut.context.env.Environment.TEST
import io.micronaut.data.jdbc.annotation.JdbcRepository
import io.micronaut.data.model.query.builder.sql.Dialect.ORACLE
@Primary
@JdbcRepository(dialect = ORACLE) // <1>
@Requires(env = [ORACLE_CLOUD, TEST]) // <2>
interface OracleGameRepository : GameRepository
| 209 | Java | 31 | 36 | f40e50dc8f68cdb3080cb3802d8082ada9ca6787 | 1,111 | micronaut-guides | Creative Commons Attribution 4.0 International |
particle-wallet/android/src/main/java/com/particlewallet/ParticleWalletPackage.kt | Particle-Network | 553,295,666 | false | {"TypeScript": 360885, "Kotlin": 183841, "Swift": 100563, "Java": 26757, "Ruby": 25934, "JavaScript": 19168, "Objective-C": 18745, "Objective-C++": 10885, "Python": 9366, "C": 618, "Starlark": 602} | package com.particlewallet
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class ParticleWalletPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(ParticleWalletPlugin(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| 2 | TypeScript | 7 | 12 | 2c48116fbf3450cae3ed5747ad1994ac21a09231 | 549 | particle-react-native | Apache License 2.0 |
courses/6-unit_3-display_lists_and_use_material_design/4-woof/app/src/main/java/com/stc/woof/screen/ScreenDog.kt | jjose14-Jacob-Jose | 798,449,153 | false | {"Kotlin": 195471} | package com.stc.woof.screen
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
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.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.stc.woof.R
import com.stc.woof.data.DataSourceDog
import com.stc.woof.model.Dog
import com.stc.woof.ui.theme.WoofTheme
class ScreenDog {
@Composable
fun Show(
dog: Dog,
modifier : Modifier = Modifier
) {
var isHobbyVisible by remember { mutableStateOf(false) }
Card(
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(dimensionResource(id = R.dimen.padding_small))
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioHighBouncy,
stiffness = Spring.StiffnessMedium
)
),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = dog.imageResourceId),
contentDescription = stringResource(id = R.string.content_description_image_dog)
+ stringResource(id = dog.name),
modifier = Modifier
.size(dimensionResource(id = R.dimen.image_size))
.padding(dimensionResource(id = R.dimen.padding_small))
.clip(MaterialTheme.shapes.small),
contentScale = ContentScale.Crop
)
Column() {
Text(
text = stringResource(id = dog.name),
style = MaterialTheme.typography.displayMedium,
modifier = modifier.padding(top = dimensionResource(id = R.dimen.padding_small))
)
Text(
text = stringResource(id = R.string.years_old, dog.age),
style = MaterialTheme.typography.bodyLarge,
)
if (isHobbyVisible) {
Text(
text = stringResource(id = R.string.about),
style = MaterialTheme.typography.titleSmall,
modifier = modifier.padding(top = dimensionResource(id = R.dimen.padding_small))
)
Text(
text = stringResource(id = dog.hobby),
style = MaterialTheme.typography.bodySmall,
)
}
}
Box(
modifier = modifier
.padding(end= dimensionResource(id = R.dimen.padding_small))
.fillMaxWidth()
.clickable { isHobbyVisible = !isHobbyVisible },
contentAlignment = Alignment.BottomEnd
) {
Image (
painter = painterResource(id = if(isHobbyVisible) R.drawable.keyboard_arrow_up_24px else R.drawable.keyboard_arrow_down_24px),
contentDescription = "Keyboard arrow pointing down",
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun PreviewDogItem() {
WoofTheme {
val modifier = Modifier
Surface(
modifier = modifier
.fillMaxSize()
) {
Show(
DataSourceDog.listDogs.get(0),
modifier
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 88eb0ea6711154060e0e9ad85d7952e006b183b3 | 5,220 | kotlin-google-tutorial | Apache License 2.0 |
geary-commons-papermc/src/main/kotlin/com/mineinabyss/geary/papermc/actions/systems/ApplyDamage.kt | MineInAbyss | 388,677,224 | false | null | package com.mineinabyss.geary.papermc.actions.systems
import com.mineinabyss.geary.annotations.AutoScan
import com.mineinabyss.geary.annotations.Handler
import com.mineinabyss.geary.commons.events.configurable.components.Apply
import com.mineinabyss.geary.papermc.actions.components.DealDamage
import com.mineinabyss.geary.systems.GearyListener
import com.mineinabyss.geary.systems.accessors.EventScope
import com.mineinabyss.geary.systems.accessors.TargetScope
import com.mineinabyss.idofront.typealiases.BukkitEntity
import com.mineinabyss.idofront.util.randomOrMin
import org.bukkit.entity.LivingEntity
@AutoScan
class ApplyDamage : GearyListener() {
val TargetScope.bukkit by get<BukkitEntity>()
val EventScope.damage by getRelations<Apply?, DealDamage>()
@Handler
fun applyDamage(target: TargetScope, event: EventScope) {
val livingTarget = target.bukkit as? LivingEntity ?: return
with(event.damage.targetData) {
val chosenDamage = damage.randomOrMin()
//if true, damage dealt ignores armor, otherwise factors armor into damage calc
livingTarget.health = (livingTarget.health - chosenDamage).coerceAtLeast(minHealth)
}
}
}
| 6 | Kotlin | 2 | 1 | 838d46d8111ce2235afabef90a7c0cb9dd87b085 | 1,213 | Geary-addons | MIT License |
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTRpcResult.kt | y9san9 | 285,876,206 | false | null | package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MTRpcResult @JvmOverloads constructor(var messageId: Long = 0, var content: ByteArray = ByteArray(0), var contentLen: Int = 0) : TLObject() {
override fun getConstructorId(): Long {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeLong(messageId, stream)
writeByteArray(content, 0, contentLen, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
messageId = readLong(stream)
contentLen = stream.available()
content = ByteArray(contentLen)
readBytes(content, 0, contentLen, stream)
}
override fun toString(): String {
return "rpc_result#f35c6d01"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = -212046591L
}
}
| 12 | null | 89 | 5 | 34f98671bd0aa15c67b0ead1ed0292755bf8c7eb | 1,157 | kotlogram | MIT License |
tangem-core/src/main/java/com/tangem/common/tlv/TlvEncoder.kt | byennen | 267,425,784 | true | {"Java Properties": 8, "Gradle": 8, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Text": 27, "Ruby": 2, "Ignore List": 1, "XML": 397, "INI": 3, "Proguard": 2, "Kotlin": 127, "JSON": 252, "SQL": 9, "Motorola 68K Assembly": 9, "Java": 166, "JAR Manifest": 1, "HTML": 16, "CSS": 6, "JavaScript": 3, "YAML": 1} | package com.tangem.common.tlv
import com.tangem.Log
import com.tangem.TangemSdkError
import com.tangem.commands.*
import com.tangem.commands.common.IssuerDataMode
import com.tangem.common.extensions.calculateSha256
import com.tangem.common.extensions.hexToBytes
import com.tangem.common.extensions.toByteArray
import java.util.*
/**
* Encodes information that is to be written on the card from parsed classes into [ByteArray]
* (according to the provided [TlvTag] and corresponding [TlvValueType])
* and then forms [Tlv] with the encoded values.
*/
class TlvEncoder {
/**
* @param tag [TlvTag] which defines the type of [Tlv] that will be created.
* @param value information that is to be encoded into [Tlv].
*/
internal inline fun <reified T> encode(tag: TlvTag, value: T?): Tlv {
if (value != null) {
return Tlv(tag, encodeValue(tag, value))
} else {
Log.e(this::class.simpleName!!, "Encoding error. Value for tag $tag is null")
throw TangemSdkError.EncodingFailed()
}
}
internal inline fun <reified T> encodeValue(tag: TlvTag, value: T): ByteArray {
return when (tag.valueType()) {
TlvValueType.HexString -> {
typeCheck<T, String>(tag)
(value as String).hexToBytes()
}
TlvValueType.HexStringToHash -> {
typeCheck<T, String>(tag)
(value as String).calculateSha256()
}
TlvValueType.Utf8String -> {
typeCheck<T, String>(tag)
(value as String).toByteArray()
}
TlvValueType.Uint16 -> {
typeCheck<T, Int>(tag)
(value as Int).toByteArray(2)
}
TlvValueType.Uint32 -> {
typeCheck<T, Int>(tag)
(value as Int).toByteArray()
}
TlvValueType.BoolValue -> {
typeCheck<T, Boolean>(tag)
val booleanValue = value as Boolean
if (booleanValue) byteArrayOf(1) else byteArrayOf(0)
}
TlvValueType.ByteArray -> {
typeCheck<T, ByteArray>(tag)
value as ByteArray
}
TlvValueType.EllipticCurve -> {
typeCheck<T, EllipticCurve>(tag)
(value as EllipticCurve).curve.toByteArray()
}
TlvValueType.DateTime -> {
typeCheck<T, Date>(tag)
val calendar = Calendar.getInstance().apply { time = (value as Date) }
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH) + 1
val day = calendar.get(Calendar.DAY_OF_MONTH)
return year.toByteArray(2) + month.toByte() + day.toByte()
}
TlvValueType.ProductMask -> {
typeCheck<T, ProductMask>(tag)
byteArrayOf(
(value as ProductMask).rawValue.toByte()
)
}
TlvValueType.SettingsMask -> {
typeCheck<T, SettingsMask>(tag)
val rawValue = (value as SettingsMask).rawValue
rawValue.toByteArray(determineByteArraySize(rawValue))
}
TlvValueType.CardStatus -> {
typeCheck<T, CardStatus>(tag)
(value as CardStatus).code.toByteArray()
}
TlvValueType.SigningMethod -> {
typeCheck<T, SigningMethodMask>(tag)
byteArrayOf((value as SigningMethodMask).rawValue.toByte())
}
TlvValueType.IssuerDataMode -> {
typeCheck<T, IssuerDataMode>(tag)
byteArrayOf((value as IssuerDataMode).code)
}
}
}
private fun determineByteArraySize(value: Int): Int {
val mask = 0xFFFF0000.toInt()
return if ((value and mask) != 0) 4 else 2
}
private inline fun <reified T, reified ExpectedT> typeCheck(tag: TlvTag) {
if (T::class != ExpectedT::class) {
Log.e(this::class.simpleName!!,
"Mapping error. Type for tag: $tag must be ${tag.valueType()}. It is ${T::class}")
throw TangemSdkError.EncodingFailedTypeMismatch()
}
}
} | 0 | Java | 0 | 1 | baaedaf504cc6658272becad7d88b340eacdd6e8 | 4,346 | tangem-sdk-android | MIT License |
app/src/main/java/com/padcx/travelapp/travelapp_testautomation_mmz/persistances/CountryListTypeConverters.kt | junelaykris | 280,520,797 | false | null | package com.padcx.travelapp.travelapp_testautomation_mmz.persistances
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.padcx.travelapp.travelapp_testautomation_mmz.datas.vos.CountryVO
class CoutryListTypeConverters {
@TypeConverter
fun toString(dataList:ArrayList<CountryVO>):String{
return Gson().toJson(dataList)
}
@TypeConverter
fun toCountryList(countryListJsonStr:String):ArrayList<CountryVO>{
val countryListType = object : TypeToken<ArrayList<CountryVO>>(){}.type
return Gson().fromJson(countryListJsonStr,countryListType)
}
} | 0 | Kotlin | 0 | 0 | a090335c2dd1be2569cf532bc6749e65a4cb64c4 | 651 | PADCX_TravelApp_TestAutomation_MMZ | MIT License |
src/main/java/io/github/binaryfoo/decoders/apdu/InternalAuthenticateAPDUDecoder.kt | binaryfoo | 24,409,565 | false | null | package io.github.binaryfoo.decoders.apdu
import io.github.binaryfoo.DecodedData
import io.github.binaryfoo.decoders.DecodeSession
import io.github.binaryfoo.decoders.PopulatedDOLDecoder
import io.github.binaryfoo.EmvTags
import java.util.logging.Logger
import kotlin.collections.listOf
import kotlin.text.substring
class InternalAuthenticateAPDUDecoder : CommandAPDUDecoder {
override fun getCommand(): APDUCommand {
return APDUCommand.InternalAuthenticate
}
override fun decode(input: String, startIndexInBytes: Int, session: DecodeSession): DecodedData {
val length = Integer.parseInt(input.substring(8, 10), 16)
val data = input.substring(10, 10 + length * 2)
val ddolValues = decodeDDOLElements(session, data, startIndexInBytes + 5)
return DecodedData.constructed("C-APDU: Internal Authenticate", data, startIndexInBytes, startIndexInBytes + 6 + length, ddolValues)
}
private fun decodeDDOLElements(session: DecodeSession, populatedDdol: String, startIndexInBytes: Int): List<DecodedData> {
val cdol = session[EmvTags.DDOL]
if (cdol != null) {
try {
return PopulatedDOLDecoder().decode(cdol, populatedDdol, startIndexInBytes, session)
} catch (e: Exception) {
LOG.throwing(GenerateACAPDUDecoder::class.java.simpleName, "decodeDDOLElements", e)
}
}
return listOf()
}
companion object {
private val LOG = Logger.getLogger(InternalAuthenticateAPDUDecoder::class.java.name)
}
}
| 7 | Kotlin | 57 | 136 | dda526e6b9d6e45a5d8b5c74217540a478f1154b | 1,566 | emv-bertlv | MIT License |
app/src/main/java/com/day/record/ui/day/DayTaskFragment.kt | JereChen11 | 326,435,207 | false | null | package com.day.record.ui.day
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.day.record.data.entity.DayTask
import com.day.record.databinding.FragmentDayTaskBinding
import com.day.record.databinding.RcyItemDayTaskViewBinding
import com.day.record.databinding.RcyItemTaskBottomViewBinding
import com.day.record.ui.task.CrudTaskActivity
import com.day.record.utils.SpUtils
import com.day.record.utils.Utils
/**
* @author Jere
*/
class DayTaskFragment : Fragment() {
private lateinit var dayTaskViewModel: DayTaskViewModel
private var binding: FragmentDayTaskBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDayTaskBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dayTaskViewModel = ViewModelProvider(this)[DayTaskViewModel::class.java]
dayTaskViewModel.dayTaskListLd.observe(viewLifecycleOwner) {
binding?.dayTaskRcy?.adapter = DayTaskListAdapter(it,
object : DayTaskListAdapter.ItemCheckBoxListener {
override fun onChange(view: View, position: Int, isChecked: Boolean) {
val dayTask = it[position]
dayTask.isFinish = isChecked
dayTaskViewModel.updateTask(isChecked, dayTask)
}
})
}
}
override fun onResume() {
super.onResume()
//todo need add new dayTask on new day
if (SpUtils.getInstance().getDate() != Utils.getCurrentDate()) {
dayTaskViewModel.resetDayTask()
SpUtils.getInstance().setDate(Utils.getCurrentDate())
} else {
dayTaskViewModel.getCurrentDateAllTasks()
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
class DayTaskListAdapter(
private var dayTaskList: List<DayTask>,
private val itemCheckBoxListener: ItemCheckBoxListener
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val NORMAL_TYPE = 0
private const val BOTTOM_TYPE = 1
}
interface ItemCheckBoxListener {
fun onChange(view: View, position: Int, isChecked: Boolean)
}
class MyViewHolder(
private val binding: RcyItemDayTaskViewBinding,
private val itemCheckBoxListener: ItemCheckBoxListener
) :
RecyclerView.ViewHolder(binding.root) {
fun bind(dayTask: DayTask) {
binding.checkbox.text = dayTask.taskName
binding.checkbox.isChecked = dayTask.isFinish
binding.checkbox.setOnCheckedChangeListener { buttonView, isChecked ->
itemCheckBoxListener.onChange(buttonView, bindingAdapterPosition, isChecked)
}
}
}
class BottomViewHolder(private val binding: RcyItemTaskBottomViewBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind() {
Handler(Looper.getMainLooper()).postDelayed(Runnable {
kotlin.run {
binding.addTaskContainerLl.visibility = View.VISIBLE
}
}, 100)
binding.addTaskContainerLl.setOnClickListener {
val intent = Intent(it.context, CrudTaskActivity::class.java)
val bundle = Bundle()
bundle.putInt(CrudTaskActivity.OPERATE_TYPE_KEY, CrudTaskActivity.ADD_OPERATE)
intent.putExtras(bundle)
it.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == NORMAL_TYPE) {
val binding = RcyItemDayTaskViewBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return MyViewHolder(binding, itemCheckBoxListener)
}
val bottomBinding =
RcyItemTaskBottomViewBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return BottomViewHolder(bottomBinding)
}
override fun getItemViewType(position: Int): Int {
if (itemCount == 0 || position == itemCount - 1) {
return BOTTOM_TYPE
}
return NORMAL_TYPE
}
override fun getItemCount(): Int {
return dayTaskList.size + 1
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val type = getItemViewType(position)
if (type == NORMAL_TYPE) {
val myViewHolder = holder as MyViewHolder
myViewHolder.bind(dayTaskList[position])
} else {
val bottomViewHolder = holder as BottomViewHolder
bottomViewHolder.bind()
}
}
}
} | 0 | Kotlin | 0 | 0 | f5a7c49f48ee3430f89860287351239808c6c41c | 5,685 | Day_Record | Apache License 2.0 |
chords-core/src/commonMain/kotlin/com.chrynan.chords/parser/Parser.kt | chRyNaN | 51,400,387 | false | null | package com.chrynan.chords.parser
/**
* A generic interface to parse an input into an output.
*
* @author chRyNaN
*/
interface Parser<IN, OUT> {
/**
* Parses the provided input [IN] and returns the output [OUT]. If an exception is encountered
* during the parsing process, then that exception will be thrown. If you would rather catch
* the exception and have null return, use the [parseOrNull] function instead.
*
* @author chRyNaN
*/
suspend fun parse(input: IN): OUT
/**
* Parses the provided input [IN] and returns the output [OUT]. If an exception is encountered
* during the parsing process, then that exception will be caught and null will be returned. If
* you would rather handle the exception, then use the [parse] function instead.
*
* @author chRyNaN
*/
suspend fun parseOrNull(input: IN): OUT? = try {
parse(input = input)
} catch (throwable: Throwable) {
null
}
} | 0 | Kotlin | 5 | 28 | 5a2e21c9b4789c878f0459e3d5c6fcfcbc66658d | 984 | chords | Apache License 2.0 |
src/test/kotlin/app/load/utility/ConverterTest.kt | uk-gov-mirror | 356,709,418 | false | null | package app.load.utility
import com.beust.klaxon.JsonObject
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.kotest.matchers.types.beInstanceOf
import java.text.ParseException
class ConverterTest : StringSpec({
val converter = Converter()
"valid input converts to json" {
val jsonString = """{"testOne":"test1", "testTwo":2}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
json should beInstanceOf<JsonObject>()
json.string("testOne") shouldBe "test1"
json.int("testTwo") shouldBe 2
}
"valid nested input converts to json" {
val jsonString = """{"testOne":{"testTwo":2}}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val jsonTwo: JsonObject = json.obj("testOne") as JsonObject
json should beInstanceOf<JsonObject>()
jsonTwo.int("testTwo") shouldBe 2
}
"invalid nested input throws exception" {
val jsonString = """{"testOne":"""
val exception = shouldThrow<IllegalArgumentException> {
converter.convertToJson(jsonString.toByteArray())
}
exception.message shouldBe "Cannot parse invalid JSON"
}
"can generate consistent base64 encoded string" {
val jsonStringWithFakeHash = """82&%${"$"}dsdsd{"testOne":"test1", "testTwo":2}"""
val encodedStringOne = converter.encodeToBase64(jsonStringWithFakeHash)
val encodedStringTwo = converter.encodeToBase64(jsonStringWithFakeHash)
encodedStringOne shouldBe encodedStringTwo
}
"can encode and decode string with base64" {
val jsonStringWithFakeHash = """82&%${"$"}dsdsd{"testOne":"test1", "testTwo":2}"""
val encodedString = converter.encodeToBase64(jsonStringWithFakeHash)
val decodedString = converter.decodeFromBase64(encodedString)
decodedString shouldBe jsonStringWithFakeHash
}
"sorts json by key name" {
val jsonStringUnsorted = """{"testA":"test1", "testC":2, "testB":true}"""
val jsonObjectUnsorted: JsonObject = converter.convertToJson(jsonStringUnsorted.toByteArray())
val jsonStringSorted = """{"testA":"test1","testB":true,"testC":2}"""
val sortedJson = converter.sortJsonByKey(jsonObjectUnsorted)
sortedJson shouldBe jsonStringSorted
}
"sorts json by key name case sensitively" {
val jsonStringUnsorted = """{"testb":true, "testA":"test1", "testC":2}"""
val jsonObjectUnsorted: JsonObject = converter.convertToJson(jsonStringUnsorted.toByteArray())
val jsonStringSorted = """{"testA":"test1","testC":2,"testb":true}"""
val sortedJson = converter.sortJsonByKey(jsonObjectUnsorted)
sortedJson shouldBe jsonStringSorted
}
"checksums are different with different inputs" {
val jsonStringOne = """{"testOne":"test1", "testTwo":2}"""
val jsonStringTwo = """{"testOne":"test2", "testTwo":2}"""
val checksum = converter.generateFourByteChecksum(jsonStringOne)
val checksumTwo = converter.generateFourByteChecksum(jsonStringTwo)
checksum shouldNotBe checksumTwo
}
"can generate consistent checksums from json" {
val jsonString = """{"testOne":"test1", "testTwo":2}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val checksumOne = converter.generateFourByteChecksum(json.toString())
val checksumTwo = converter.generateFourByteChecksum(json.toString())
checksumOne shouldBe checksumTwo
}
"generated checksums are four bytes" {
// assertAll { input: String ->
// val checksum = converter.generateFourByteChecksum(input)
// checksum.size shouldBe 4
// }
}
"valid timestamp format in the message gets parsed as long correctly" {
val jsonString = """{
"traceId": "00001111-abcd-4567-1234-1234567890ab",
"unitOfWorkId": "00002222-abcd-4567-1234-1234567890ab",
"@type": "V4",
"version": "core-X.release_XXX.XX",
"timestamp": "2018-12-14T15:01:02.000+0000",
"message": {
"@type": "MONGO_UPDATE",
"collection": "exampleCollectionName",
"db": "exampleDbName",
"_id": {
"exampleId": "aaaa1111-abcd-4567-1234-1234567890ab"
},
"_lastModifiedDateTime": "2018-12-14T15:01:02.000+0000",
"encryption": {
"encryptionKeyId": "55556666-abcd-89ab-1234-1234567890ab",
"encryptedEncryptionKey": "bHJjhg2Jb0uyidkl867gtFkjl4fgh9Ab",
"initialisationVector": "kjGyvY67jhJHVdo2",
"keyEncryptionKeyId": "example-key_2019-12-14_01"
},
"dbObject": "bubHJjhg2Jb0uyidkl867gtFkjl4fgh9AbubHJjhg2Jb0uyidkl867gtFkjl4fgh9AbubHJjhg2Jb0uyidkl867gtFkjl4fgh9A"
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
val timeStampAsLong = converter.getTimestampAsLong(timestamp)
timestamp shouldBe "2018-12-14T15:01:02.000+0000"
timeStampAsLong shouldBe 1544799662000
fieldName shouldBe "_lastModifiedDateTime"
}
"Invalid timestamp format in the message throws Exception" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": "2018-12-14",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, _) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "2018-12-14"
shouldThrow<ParseException> {
converter.getTimestampAsLong(timestamp)
}
}
"Last modified date time returned when valid created date time" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": "2018-12-14T15:01:02.000+0000",
"createdDateTime": "2019-11-13T14:02:03.001+0000",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "2018-12-14T15:01:02.000+0000"
fieldName shouldBe "_lastModifiedDateTime"
}
"Missing last modified date time returns created date time" {
val jsonString = """{
"message": {
"createdDateTime": "2019-11-13T14:02:03.001+0000",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "2019-11-13T14:02:03.001+0000"
fieldName shouldBe "createdDateTime"
}
"Empty last modified date time returns created date time" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": "",
"createdDateTime": "2019-11-13T14:02:03.001+0000",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "2019-11-13T14:02:03.001+0000"
fieldName shouldBe "createdDateTime"
}
"Null last modified date time returns created date time" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": null,
"createdDateTime": "2019-11-13T14:02:03.001+0000",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "2019-11-13T14:02:03.001+0000"
fieldName shouldBe "createdDateTime"
}
"Missing last modified date time and created date time returns epoch" {
val jsonString = """{
"message": {
"_lastModifiedDateTime1": "2018-12-14T15:01:02.000+0000",
"createdDateTime1": "2019-11-13T14:02:03.001+0000",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "1980-01-01T00:00:00.000+0000"
fieldName shouldBe "epoch"
}
"Empty last modified date time and created date time returns epoch" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": "",
"createdDateTime": "",
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "1980-01-01T00:00:00.000+0000"
fieldName shouldBe "epoch"
}
"Null last modified date time and created date time returns epoch" {
val jsonString = """{
"message": {
"_lastModifiedDateTime": null,
"createdDateTime": null,
}
}"""
val json: JsonObject = converter.convertToJson(jsonString.toByteArray())
val (timestamp, fieldName) = converter.getLastModifiedTimestamp(json)
timestamp shouldBe "1980-01-01T00:00:00.000+0000"
fieldName shouldBe "epoch"
}
})
| 0 | null | 1 | 0 | 9015c4827e4599ba44ee96735d929d456df4f4cd | 9,731 | historic-data-loader | MIT License |
compose/src/commonMain/kotlin/pro/respawn/kmmutils/compose/Haptics.kt | respawn-app | 557,470,802 | false | {"Kotlin": 209713} | @file:Suppress("unused")
package pro.respawn.kmmutils.compose
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
/**
* Plays a medium haptic feedback, similar to force-touch or long-tap effect.
*
* The effect can vary between platforms or be unavailable (e.g. desktop, browser).
*
* @see HapticFeedbackType.LongPress
*/
public fun HapticFeedback.medium(): Unit = performHapticFeedback(HapticFeedbackType.LongPress)
/**
* Plays a short haptic feedback, similar to a software keyboard typing vibration.
*
* The effect can vary between platforms or be unavailable (e.g. desktop, browser).
*
* @see HapticFeedbackType.TextHandleMove
*/
public fun HapticFeedback.short(): Unit = performHapticFeedback(HapticFeedbackType.TextHandleMove)
| 0 | Kotlin | 0 | 59 | 72a0900574170c0c74072d0f0348558f2ff9e5d6 | 814 | KMPUtils | Apache License 2.0 |
src/main/kotlin/com/igorini/togepibot/gui/keyword/OopsKeyword.kt | igorini | 123,990,696 | false | null | package com.igorini.togepibot.gui.keyword
/** Represents a keyword for text and sound associated with "Oops" */
object OopsKeyword : Keyword() {
override fun folder() = "oops"
override fun voiceRus() = listOf("упс", "упсь")
override fun voiceEng() = listOf("oops", "oopsie")
override fun textRus() = voiceRus()
override fun textEng() = voiceEng()
override fun emotes() = listOf("oops")
} | 0 | Kotlin | 0 | 0 | 80de398881b5999dfd107b12c9a279915788306b | 412 | togepi-bot | Apache License 2.0 |
app/src/main/kotlin/dfialho/tveebot/app/repositories/FileStashRepository.kt | dfialho | 132,515,212 | false | null | package dfialho.tveebot.app.repositories
import dfialho.tveebot.app.components.FileStash
interface FileStashRepository {
fun insert(stashedFile: FileStash.StashedFile)
fun findByName(name: String): FileStash.StashedFile?
fun remove(name: String)
fun list(): List<FileStash.StashedFile>
}
| 3 | Kotlin | 0 | 0 | 9423027242154b4b199befcf4d8ee5f909861cb3 | 307 | tveebot | MIT License |
src/main/kotlin/net/ankertal/kafka/metamorphosis/PerformanceTest.kt | kertal | 164,400,512 | false | null | package net.ankertal.kafka.metamorphosis
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.serialization.StringSerializer
import org.apache.log4j.LogManager
import java.util.*
/**
* A basic Performance Test class sending messages to a given Kafka broker,
* waiting for ACK for each message, returning the number of milliseconds it took
* to send all messages
* It's using coroutines Channels to build a data pipeline with multiple workers
* https://kotlinlang.org/docs/reference/coroutines/channels.html
* It's using still experimental features of the coroutines API
**/
class PerformanceTest(val brokers: String = "localhost:9092") {
private val logger = LogManager.getLogger(javaClass)
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun run(
topic: String = "kafka-metamorphosis-test",
nrOfRecords: Int = 1000,
workers: Int = 1,
payload: String = "test"
): Long = runBlocking {
logger.info("Start with topic $topic, nrOfRecords $nrOfRecords, workers $workers")
val props = Properties()
props["bootstrap.servers"] = brokers
props["key.serializer"] = StringSerializer::class.java
props["value.serializer"] = StringSerializer::class.java
val kafkaProducer = KafkaProducer<String, String>(props)
logger.info("Start message producer channel")
val msgProdChannel = produce {
logger.info("${Thread.currentThread().name} Start Record Producer")
repeat(nrOfRecords) {
send(payload)
}
}
logger.info("Start message consumer channels - the Kafka producer")
val start = System.currentTimeMillis()
val msgConsChannel = Array(workers) {
val thread = "kafka-m-worker-${it}"
produce(newSingleThreadContext(thread)) {
logger.info(" Start message consumer channel,thread: ${Thread.currentThread().name} ")
for (msg in msgProdChannel) {
kafkaProducer.send(ProducerRecord(topic, msg)).get()
}
send("finished")
}
}
msgConsChannel.forEach { it.receive() }
val duration = System.currentTimeMillis() - start
logger.info("Finished in $duration ms")
duration
}
}
| 0 | Kotlin | 1 | 1 | 53b3781285b632765d91202c6d353d7de682d70c | 2,481 | kafka-metamorphosis | MIT License |
proxy/src/main/kotlin/ys/phoebos/redis/proxy/worker/RxWorker.kt | phoebosys | 162,104,139 | false | null | /*
* Copyright Phoebosys
*
* 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 ys.phoebos.redis.proxy.worker
import ys.phoebos.redis.proxy.LOG
import ys.phoebos.redis.proxy.sender.RxSender
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableOnSubscribe
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import ys.phoebos.redis.CHARSET
import ys.phoebos.redis.MessageType
import ys.phoebos.redis.protocol.*
import java.io.InputStream
import java.io.InputStreamReader
class RxWorker(
private val type: MessageType,
private val senders: List<RxSender>,
reqIn: InputStream,
rspIn: InputStream
) {
private var reqFlow: Readiable
private var rspFlow: Readiable
init {
when(type) {
MessageType.PROTOCOL, MessageType.STRING -> {
reqFlow = CommandInputStream(reqIn)
rspFlow = ReplyInputStream(rspIn)
}
MessageType.ROW -> {
reqFlow = ReadiableReader(InputStreamReader(reqIn, CHARSET))
rspFlow = ReadiableReader(InputStreamReader(rspIn, CHARSET))
}
}
}
fun start() {
val ns = ""
val commandFlow = Flowable.create(FlowableOnSubscribe<Talk> { emitter ->
while (!emitter.isCancelled) {
try {
val command = when (type) {
MessageType.PROTOCOL, MessageType.STRING ->
Talk((reqFlow as CommandInputStream).readCommand(), emptyReply)
MessageType.ROW -> Talk((reqFlow as ReadiableReader).readLine(), ns)
}
while (emitter.requested() == 0L) {
if (emitter.isCancelled) {
break
}
}
emitter.onNext(command)
} catch (e: Exception) {
LOG.error("RxWorker.commandFlow", e)
emitter.onError(e)
}
}
reqFlow.close()
emitter.onComplete()
}, BackpressureStrategy.ERROR)
.subscribeOn(Schedulers.io())
val replyFlow = Flowable.create(FlowableOnSubscribe<Talk> {emitter ->
while (!emitter.isCancelled) {
try {
val reply = when (type) {
MessageType.PROTOCOL, MessageType.STRING -> Talk(emptyCommand, (rspFlow as ReplyInputStream).readReply())
MessageType.ROW -> Talk(ns, (rspFlow as ReadiableReader).readLine())
}
while (emitter.requested() == 0L) {
if (emitter.isCancelled) {
break
}
}
emitter.onNext(reply)
}catch (e: Exception) {
LOG.error("RxWorker.commandFlow", e)
emitter.onError(e)
}
}
rspFlow.close()
emitter.onComplete()
}, BackpressureStrategy.ERROR)
.subscribeOn(Schedulers.io())//.observeOn(Schedulers.newThread())
var join = when(type) {
MessageType.PROTOCOL, MessageType.STRING -> {
Flowable.zip(commandFlow, replyFlow,
BiFunction<Talk, Talk, Talk> { first, second -> Talk(first.command, second.reply) })
// .subscribeOn(Schedulers.newThread())
// .observeOn(Schedulers.newThread())
}
MessageType.ROW -> {
Flowable.mergeDelayError(commandFlow, replyFlow)
// .subscribeOn(Schedulers.newThread())
// .observeOn(Schedulers.newThread())
}
}
senders.forEach { join.subscribe(it) }
}
}
| 0 | Kotlin | 0 | 0 | 66a7768df9043e1edc1432e0c875c03ee9f433e7 | 4,434 | redis-remoteback | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.