path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apps/server/src/test/kotlin/com/github/arhor/simple/expense/tracker/web/error/ErrorCodeSerializerTest.kt | arhor | 498,306,626 | false | {"Kotlin": 209602, "TypeScript": 73005, "JavaScript": 2928, "HTML": 959, "CSS": 372, "Procfile": 124, "Dockerfile": 118} | package com.github.arhor.simple.expense.tracker.web.error
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.SerializerProvider
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import io.mockk.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
internal class ErrorCodeSerializerTest {
private val errorCodeSerializer = ErrorCodeSerializer()
private val generator = mockk<JsonGenerator>()
private val provider = mockk<SerializerProvider>()
private val serializedValue = slot<String>()
@BeforeEach
fun setUp() {
serializedValue.clear()
every { generator.writeString(any<String>()) } just runs
}
@ParameterizedTest
@EnumSource(ErrorCode::class)
fun `each error code should be correctly serialized to string`(
// given
errorCode: ErrorCode
) {
// when
errorCodeSerializer.serialize(errorCode, generator, provider)
// then
verify(exactly = 1) { generator.writeString(capture(serializedValue)) }
assertThat(serializedValue.captured)
.isNotBlank
.contains(
errorCode.type.toString(),
errorCode.value.toString(),
)
}
}
| 0 | Kotlin | 0 | 0 | 5d0a7dd48f2107550db0913a6ba03867f409dcc1 | 1,448 | simple-expense-tracker | Apache License 2.0 |
native/objcexport-header-generator/testData/headers/simpleEnumClass/Foo.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | enum class Foo {
A, B, C
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 30 | kotlin | Apache License 2.0 |
JazzCode/app/src/main/java/piano/activities/SetNewPwActivity.kt | yiar | 299,867,080 | false | {"Kotlin": 11005} | package piano.activities
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.example.nfinderc.R
import piano.classes.DiffList
class SetNewPwActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_resetpw)
var handler = DiffList()
val resetBtn = findViewById<Button>(R.id.resetInputID)
resetBtn.setOnClickListener()
{
handler.clearPw(handler.keysList)
}
val confirmBtn = findViewById<Button>(R.id.confirmPWId)
confirmBtn.setOnClickListener()
{
if(handler.userList.size in 4..14) {
handler.confirmPw(handler.userList)
// Log.d("Gil", "save pw: " + handler.keysList.toString())
handler.savePassword(applicationContext, handler.keysList)
val intent = Intent(this, LogInActivity::class.java)
startActivity(intent)
}
else handler.clearPw(handler.keysList)
}
// btn 1 buttonNoteC2s
val C2sBtn = findViewById<Button>(R.id.buttonNoteC2s)
C2sBtn.setOnClickListener()
{
handler.userList.add("C")
}
val D2sBtn = findViewById<Button>(R.id.buttonNoteD2s)
D2sBtn.setOnClickListener()
{
handler.userList.add("C#")
}
val E2sBtn = findViewById<Button>(R.id.buttonNoteE2s)
E2sBtn.setOnClickListener()
{
handler.userList.add("D")
}
val F2sBtn = findViewById<Button>(R.id.buttonNoteF2s)
F2sBtn.setOnClickListener()
{
handler.userList.add("D#")
}
val G2sBtn = findViewById<Button>(R.id.buttonNoteG2s)
G2sBtn.setOnClickListener()
{
handler.userList.add("E")
}
val A2sBtn = findViewById<Button>(R.id.buttonNoteA2s)
A2sBtn.setOnClickListener()
{
handler.userList.add("F")
}
val B2sBtn = findViewById<Button>(R.id.buttonNoteB2s)
B2sBtn.setOnClickListener()
{
handler.userList.add("F#")
}
val Cs2sBtn = findViewById<Button>(R.id.buttonNoteCs2s)
Cs2sBtn.setOnClickListener()
{
handler.userList.add("G")
}
val Gs2sBtn = findViewById<Button>(R.id.buttonNoteGs2s)
Gs2sBtn.setOnClickListener()
{
handler.userList.add("G#")
}
val Ds2sBtn = findViewById<Button>(R.id.buttonNoteDs2s)
Ds2sBtn.setOnClickListener()
{
handler.userList.add("A")
}
val Fs2sBtn = findViewById<Button>(R.id.buttonNoteFs2s)
Fs2sBtn.setOnClickListener()
{
handler.userList.add("A#")
}
val As2sBtn = findViewById<Button>(R.id.buttonNoteAs2s)
As2sBtn.setOnClickListener()
{
handler.userList.add("B")
}
}
}
| 0 | Kotlin | 0 | 0 | 333ff3f4849c91c53d2b22fdf4a6509911a184c9 | 3,134 | Jazzcode | MIT License |
src/main/kotlin/azmalent/backportedflora/common/world/WorldGenNetherFlowers.kt | juraj-hrivnak | 448,651,550 | true | {"Kotlin": 127296} | package azmalent.backportedflora.common.world
import azmalent.backportedflora.common.block.flower.AbstractFlower
import net.minecraft.init.Blocks
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.ChunkPos
import net.minecraft.world.World
import java.util.*
class WorldGenNetherFlowers(flower: AbstractFlower) : WorldGenCustomFlowers(flower) {
override fun getGenerationPos(world: World, rand: Random, chunkPos: ChunkPos): BlockPos {
val x = rand.nextInt(16) + 8
val z = rand.nextInt(16) + 8
val y = rand.nextInt(64) + 32
return chunkPos.getBlock(0, 0, 0).add(x, y, z)
}
override fun canGenerateInWorld(world: World): Boolean {
return world.provider.dimension == -1
}
override fun canGenerateOnBlock(world: World, pos: BlockPos): Boolean {
return world.getBlockState(pos.down()).block == Blocks.SOUL_SAND
}
} | 2 | Kotlin | 2 | 1 | ca7654251c36ac1f4756449a49d38ba955bcd8b0 | 930 | underdog-flora | Do What The F*ck You Want To Public License |
app/src/main/kotlin/net/ketc/numeri/presentation/presenter/activity/CreateDisplayGroupPresenter.kt | KetcKtsD | 75,272,615 | false | null | package net.ketc.numeri.presentation.presenter.activity
import net.ketc.numeri.domain.inject
import net.ketc.numeri.domain.service.TweetsDisplayService
import net.ketc.numeri.presentation.view.activity.CreateDisplayGroupActivityInterface
import javax.inject.Inject
class CreateDisplayGroupPresenter(override val activity: CreateDisplayGroupActivityInterface) : Presenter<CreateDisplayGroupActivityInterface> {
@Inject
lateinit var displayService: TweetsDisplayService
init {
inject()
}
fun addGroup(name: String) {
displayService.createGroup(name)
}
} | 0 | Kotlin | 0 | 0 | ea3b007ab7875ea6d1bc1c5c1cec871eee2685a5 | 595 | numeri3 | MIT License |
keel-core/src/main/kotlin/com/netflix/spinnaker/keel/persistence/AssetRepository.kt | cfieber | 118,950,910 | true | {"Kotlin": 182428, "Shell": 2094} | /*
* Copyright 2018 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.spinnaker.keel.persistence
import com.netflix.spinnaker.keel.api.ApiVersion
import com.netflix.spinnaker.keel.api.Asset
import com.netflix.spinnaker.keel.api.AssetName
import java.time.Instant
interface AssetRepository {
/**
* Invokes [callback] once with each registered asset.
*/
fun allAssets(callback: (Triple<AssetName, ApiVersion, String>) -> Unit)
/**
* Retrieves a single asset by its unique [com.netflix.spinnaker.keel.api.AssetMetadata.uid].
*
* @return The asset represented by [uid] or `null` if [uid] is unknown.
* @throws NoSuchAssetException if [uid] does not map to an asset in the repository.
*/
fun <T: Any> get(name: AssetName, specType: Class<T>): Asset<T>
/**
* Persists an asset.
*
* @return the `uid` of the stored asset.
*/
fun store(asset: Asset<*>)
/**
* Retrieves the last known state of an asset.
*
* @return The last known state of the asset represented by [name] or `null` if
* [name] is unknown.
*/
fun lastKnownState(name: AssetName): Pair<AssetState, Instant>?
/**
* Updates the last known state of the asset represented by [name].
*/
fun updateState(name: AssetName, state: AssetState)
/**
* Deletes the asset represented by [name].
*/
fun delete(name: AssetName)
}
inline fun <reified T: Any> AssetRepository.get(name: AssetName): Asset<T> = get(name, T::class.java)
class NoSuchAssetException(val name: AssetName) : RuntimeException("No asset named $name exists in the repository")
| 0 | Kotlin | 0 | 0 | 24bb735c8e1f12c806c91ba051a3ae59fe1fe224 | 2,128 | keel | Apache License 2.0 |
compiler/testData/codegen/box/inlineClasses/callableReferences/boundInlineClassExtensionValGeneric.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
// WORKS_WHEN_VALUE_CLASS
// LANGUAGE: +ValueClasses, +GenericInlineClassParameter
OPTIONAL_JVM_INLINE_ANNOTATION
value class Z<T: Int>(val x: T)
OPTIONAL_JVM_INLINE_ANNOTATION
value class L<T: Long>(val x: T)
OPTIONAL_JVM_INLINE_ANNOTATION
value class S<T: String>(val x: T)
val Z<Int>.xx get() = x
val L<Long>.xx get() = x
val S<String>.xx get() = x
fun box(): String {
if (Z(42)::xx.get() != 42) throw AssertionError()
if (L(1234L)::xx.get() != 1234L) throw AssertionError()
if (S("abcdef")::xx.get() != "abcdef") throw AssertionError()
return "OK"
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 590 | kotlin | Apache License 2.0 |
src/test/kotlin/com/github/pyracantha/coccinea/replication/ReplicatorImplTest.kt | pyracantha | 159,024,111 | false | null | package com.github.pyracantha.coccinea.replication
import com.github.pyracantha.coccinea.bucket.Document
import com.github.pyracantha.coccinea.bucket.document
import com.github.pyracantha.coccinea.database.DatabaseId
import com.github.pyracantha.coccinea.database.databaseId
import com.github.pyracantha.coccinea.journal.Action
import com.github.pyracantha.coccinea.journal.Action.DELETE
import com.github.pyracantha.coccinea.journal.Action.SAVE
import com.github.pyracantha.coccinea.journal.Change
import com.github.pyracantha.coccinea.journal.ChangeId
import com.github.pyracantha.coccinea.journal.change
import com.github.pyracantha.coccinea.journal.changeId
import com.github.pyracantha.coccinea.replication.ReplicationDirection.INBOUND
import com.github.pyracantha.coccinea.replication.ReplicationDirection.OUTBOUND
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers.trampoline
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class ReplicatorImplTest {
companion object {
private val databaseIdSource = databaseId("source")
private val databaseIdDestination = databaseId("destination")
}
private lateinit var transferLog: TransferLog
private lateinit var source: ReplicationPeer
private lateinit var destination: ReplicationPeer
private lateinit var replicator: Replicator
@BeforeEach
fun setUp() {
transferLog = mock()
source = mock {
on { databaseId() } doReturn Single.just(databaseIdSource)
}
destination = mock {
on { databaseId() } doReturn Single.just(databaseIdDestination)
}
replicator = ReplicatorImpl(transferLog, trampoline())
}
@Test
fun delegatesReplicate() {
whenever(source.changes()).doReturn(Observable.empty())
whenever(destination.changes()).doReturn(Observable.empty())
whenever(transferLog.get(any(), any())).doReturn(Maybe.empty())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult()
verify(source).changes()
verify(destination).changes()
verify(source).changes()
verify(transferLog, times(2)).get(any(), any())
}
@Test
fun transfersOutbound() {
val change1 = change()
val change2 = change()
val change3 = change()
val document1 = document()
val document2 = document()
val document3 = document()
whenever(source.changes()).doReturn(Observable.fromArray(change1, change2, change3))
whenever(source.get(change1.documentId, change1.version)).doReturn(Maybe.just(document1))
whenever(source.get(change2.documentId, change2.version)).doReturn(Maybe.just(document2))
whenever(source.get(change3.documentId, change3.version)).doReturn(Maybe.just(document3))
whenever(destination.changes()).doReturn(Observable.empty())
whenever(destination.exists(any(), any())).doReturn(Single.just(false))
whenever(destination.put(any(), any(), any(), any())).doReturn(Completable.complete())
whenever(transferLog.get(any(), any())).doReturn(Maybe.empty())
whenever(transferLog.put(any(), any(), any())).doReturn(Completable.complete())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult()
verifyExists(destination, change1)
verifyExists(destination, change2)
verifyExists(destination, change3)
verifyPut(destination, change1, SAVE, document1)
verifyPut(destination, change2, SAVE, document2)
verifyPut(destination, change3, SAVE, document3)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change1.changeId)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change2.changeId)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change3.changeId)
}
@Test
fun transfersOutboundDelete() {
val change1 = change(action = DELETE)
val document1 = document()
whenever(source.changes()).doReturn(Observable.just(change1))
whenever(source.get(change1.documentId, change1.version)).doReturn(Maybe.just(document1))
whenever(destination.changes()).doReturn(Observable.empty())
whenever(destination.exists(any(), any())).doReturn(Single.just(false))
whenever(destination.put(any(), any(), any(), anyOrNull())).doReturn(Completable.complete())
whenever(transferLog.get(any(), any())).doReturn(Maybe.empty())
whenever(transferLog.put(any(), any(), any())).doReturn(Completable.complete())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult()
verifyPut(destination, change1, DELETE)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change1.changeId)
}
@Test
fun transfersInbound() {
val change1 = change()
val change2 = change()
val change3 = change()
val document1 = document()
val document2 = document()
val document3 = document()
whenever(destination.changes()).doReturn(Observable.fromArray(change1, change2, change3))
whenever(destination.get(change1.documentId, change1.version)).doReturn(Maybe.just(document1))
whenever(destination.get(change2.documentId, change2.version)).doReturn(Maybe.just(document2))
whenever(destination.get(change3.documentId, change3.version)).doReturn(Maybe.just(document3))
whenever(source.changes()).doReturn(Observable.empty())
whenever(source.exists(any(), any())).doReturn(Single.just(false))
whenever(source.put(any(), any(), any(), any())).doReturn(Completable.complete())
whenever(transferLog.get(any(), any())).doReturn(Maybe.empty())
whenever(transferLog.put(any(), any(), any())).doReturn(Completable.complete())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult(
replicationEvent(change1.documentId, SAVE),
replicationEvent(change2.documentId, SAVE),
replicationEvent(change3.documentId, SAVE)
)
verifyExists(source, change1)
verifyExists(source, change2)
verifyExists(source, change3)
verifyPut(source, change1, SAVE, document1)
verifyPut(source, change2, SAVE, document2)
verifyPut(source, change3, SAVE, document3)
verifyPutTransferLog(transferLog, databaseIdDestination, INBOUND, change1.changeId)
verifyPutTransferLog(transferLog, databaseIdDestination, INBOUND, change2.changeId)
verifyPutTransferLog(transferLog, databaseIdDestination, INBOUND, change3.changeId)
}
@Test
fun skipsExistingDocuments() {
val change1 = change()
val change2 = change()
val document = document()
whenever(source.changes()).doReturn(Observable.fromArray(change1, change2))
whenever(destination.changes()).doReturn(Observable.empty())
whenever(destination.exists(change1.documentId, change1.version)).doReturn(Single.just(true))
whenever(destination.exists(change2.documentId, change2.version)).doReturn(Single.just(false))
whenever(source.get(change2.documentId, change2.version)).doReturn(Maybe.just(document))
whenever(destination.put(any(), any(), any(), any())).doReturn(Completable.complete())
whenever(transferLog.get(any(), any())).doReturn(Maybe.empty())
whenever(transferLog.put(any(), any(), any())).doReturn(Completable.complete())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult()
verifyPut(destination, change2, SAVE, document)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change2.changeId)
}
@Test
fun skipsKnownChanges() {
val changeId = changeId()
val change = change()
val document = document()
whenever(source.changes(changeId)).doReturn(Observable.just(change))
whenever(destination.changes()).doReturn(Observable.empty())
whenever(destination.exists(any(), any())).doReturn(Single.just(false))
whenever(source.get(change.documentId, change.version)).doReturn(Maybe.just(document))
whenever(destination.put(any(), any(), any(), any())).doReturn(Completable.complete())
whenever(transferLog.get(databaseIdDestination, OUTBOUND)).doReturn(Maybe.just(changeId))
whenever(transferLog.get(databaseIdDestination, INBOUND)).doReturn(Maybe.empty())
whenever(transferLog.put(any(), any(), any())).doReturn(Completable.complete())
val observer = replicator.replicate(source, destination).test()
observer.await()
observer.assertResult()
verifyPut(destination, change, SAVE, document)
verifyPutTransferLog(transferLog, databaseIdDestination, OUTBOUND, change.changeId)
}
private fun verifyExists(database: ReplicationPeer, change: Change) =
verify(database).exists(change.documentId, change.version)
private fun verifyPut(database: ReplicationPeer, change: Change, action: Action, document: Document? = null) =
verify(database).put(change.documentId, change.version, action, document)
private fun verifyPutTransferLog(transferLog: TransferLog, databaseId: DatabaseId, direction: ReplicationDirection, changeId: ChangeId) =
verify(transferLog).put(databaseId, direction, changeId)
} | 0 | Kotlin | 0 | 0 | 504328eff3d6fbc6bb2e54c491bc4fa87d93ffe2 | 10,087 | coccinea | MIT License |
src/main/kotlin/io/datawire/loom/kops/cluster/ClusterContext.kt | datawire | 92,783,521 | false | null | package io.datawire.loom.kops.cluster
data class ClusterContext(val name: String, val endpoint: ClusterEndpoint, val user: ClusterUser)
| 0 | Kotlin | 0 | 0 | b7208a9bbb673d4fa87b436c125227a55d9f2049 | 138 | loomctl | Apache License 2.0 |
compiler/tests-spec/testData/codegen/box/linked/expressions/comparison-expressions/p-1/pos/2.3.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
/*
* KOTLIN CODEGEN BOX SPEC TEST (POSITIVE)
*
* SPEC VERSION: 0.1-218
* MAIN LINK: expressions, comparison-expressions -> paragraph 1 -> sentence 2
* PRIMARY LINKS: expressions, comparison-expressions -> paragraph 1 -> sentence 1
* expressions, comparison-expressions -> paragraph 2 -> sentence 3
* expressions, comparison-expressions -> paragraph 3 -> sentence 1
* expressions, comparison-expressions -> paragraph 4 -> sentence 1
* overloadable-operators -> paragraph 4 -> sentence 1
* NUMBER: 3
* DESCRIPTION: These operators are overloadable (A <= B)
*/
//A <= B is exactly the same as !integerLess(A.compareTo(B),0)
fun box(): String {
val a1 = A(1)
val a2 = A(3)
val aa1 = A(0)
val aa2 = A(0)
if (a1 <= a2 && a1.isCompared && !a2.isCompared)
if (aa1 <= aa2 && aa1.isCompared && !aa2.isCompared)
return "OK"
return "NOK"
}
class A(val a: Int) {
var isCompared = false
operator fun compareTo(other: A): Int = run {
isCompared = true
this.a - other.a
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,062 | kotlin | Apache License 2.0 |
paper/src/main/kotlin/nl/chimpgamer/ultimatemobcoins/paper/models/menu/action/CommandAction.kt | ChimpGamer | 629,216,580 | false | {"Kotlin": 151489, "Java": 2095} | package nl.chimpgamer.ultimatemobcoins.paper.models.menu.action
import nl.chimpgamer.ultimatemobcoins.paper.utils.Utils
import org.bukkit.entity.Player
class CommandAction : ActionType() {
override fun executeAction(player: Player, action: Any) {
val command = action.toString()
Utils.executeCommand(Utils.applyPlaceholders(command, player))
}
override val names: Array<String> = arrayOf("command", "consolecommand")
} | 0 | Kotlin | 0 | 2 | dae15f531b26652023b1fa21d02d1e8258a375d6 | 449 | UltimateMobCoins | MIT License |
idea/idea-completion/testData/smart/MethodCallArgument.kt | android | 263,405,600 | true | null | val s = ""
fun f(p1: Any, p2: String) {
foo(<caret>)
}
fun foo(p1: String, p2: Any) : String{
}
// ABSENT: p1
// EXIST: p2
// EXIST: s
// EXIST: foo
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 156 | kotlin | Apache License 2.0 |
compiler/testData/codegen/box/coroutines/featureIntersection/funInterface/kt47549_1.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
fun interface I {
fun f(): String
suspend fun s() {}
}
fun box(): String =
I { "OK" }.f()
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 120 | kotlin | Apache License 2.0 |
compiler/testData/loadJava/compiledKotlin/prop/Const.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | //ALLOW_AST_ACCESS
package test
const private val topLevel = 1
object A {
const internal val inObject = 2
}
class B {
companion object {
const val inCompanion = 3
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 190 | kotlin | Apache License 2.0 |
compiler/testData/ir/irText/firProblems/deprecated.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// WITH_STDLIB
fun create() = "OK"
@Deprecated("Use create() instead()", replaceWith = ReplaceWith("create()"))
fun create(s: String) = create()
@Deprecated("Use create() instead()")
fun create(b: Boolean) = create()
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 237 | kotlin | Apache License 2.0 |
src/main/kotlin/de/pflugradts/passbird/domain/model/transfer/Output.kt | christianpflugradt | 522,173,174 | false | {"Kotlin": 536357} | package de.pflugradts.passbird.domain.model.transfer
import de.pflugradts.passbird.domain.model.shell.Shell
import de.pflugradts.passbird.domain.model.shell.Shell.Companion.emptyShell
import de.pflugradts.passbird.domain.model.shell.Shell.Companion.shellOf
import de.pflugradts.passbird.domain.model.transfer.OutputFormatting.DEFAULT
class Output private constructor(val shell: Shell, val formatting: OutputFormatting?) {
override fun equals(other: Any?): Boolean = when {
(this === other) -> true
(javaClass != other?.javaClass) -> false
else -> shell == (other as Output).shell
}
override fun hashCode() = shell.hashCode()
companion object {
fun outputOf(shell: Shell, formatting: OutputFormatting = DEFAULT) = Output(shell, formatting)
fun outputOf(byteArray: ByteArray, formatting: OutputFormatting = DEFAULT) = outputOf(shellOf(byteArray), formatting)
fun emptyOutput() = outputOf(emptyShell())
}
}
enum class OutputFormatting {
DEFAULT,
ERROR_MESSAGE,
EVENT_HANDLED,
HIGHLIGHT,
NEST,
OPERATION_ABORTED,
SPECIAL,
}
| 1 | Kotlin | 0 | 0 | e1faab37e532276d98e74974ff16d0912ab09e44 | 1,121 | Passbird | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/kt-57531-KotlinNativeLink-with-cycle-in-dependency-constraints/p1/build.gradle.kts | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
`maven-publish`
}
group = "org.jetbrains.sample"
version = "1.0.0"
publishing {
repositories {
maven(rootProject.buildDir.resolve("repo"))
}
}
@OptIn(ExperimentalKotlinGradlePluginApi::class)
kotlin {
jvm()
linuxX64()
linuxArm64()
applyDefaultHierarchyTemplate()
}
dependencies {
constraints {
kotlin.sourceSets.all {
val apiConfiguration = configurations.getByName(apiConfigurationName)
apiConfiguration(project(":p2"))
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 688 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/dora/BindingAdapters.kt | dora4 | 321,392,715 | false | {"Kotlin": 30909, "Java": 10200} | package com.example.dora
import android.view.View
import android.view.View.OnClickListener
import androidx.databinding.BindingAdapter
/**
* 绑定自定义属性。
*/
class BindingAdapters {
companion object {
@JvmStatic
@BindingAdapter("android:click")
fun bindClick(view: View, listener: OnClickListener) {
view.setOnClickListener(listener)
}
}
} | 0 | Kotlin | 0 | 16 | 66830ee689bd20d949d6ca66f809e5fdf326ea48 | 407 | dora_samples | Apache License 2.0 |
src/main/kotlin/com/example/sample/controller/GreetingController.kt | CristianSur | 594,490,930 | false | null | package com.example.sample.controller
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class GreetingController {
@GetMapping("/home")
fun greet(): ResponseEntity<String> = ResponseEntity.ok("Hello, welcome to secured endpoint.")
}
| 0 | Kotlin | 2 | 5 | 49806ecf8d0ac686748b6215348d6aa51b4e24a4 | 379 | kotlin-jwt-spring-security-6 | MIT License |
src/main/kotlin/com/netcracker/jspclass/Constants.kt | garbarick | 492,213,245 | false | {"Kotlin": 28842, "Java": 7121} | package com.netcracker.jspclass
/**
* SEBY0408
*/
object Constants {
val JAVA = "java"
val JSP = "jsp"
val PROTOCOL = "jspclass"
val NEW_LINE = "\r\n"
} | 0 | Kotlin | 0 | 0 | ffcfbe51bf33ba955bebec81de39ad9ceac56a79 | 171 | SBJspClass | Apache License 2.0 |
app/src/main/java/com/example/wingstofly/utils/Resource.kt | CharlesMuvaka | 587,970,858 | false | null | package com.example.wingstofly.utils
sealed class Resource<T>(val newsData: T? = null, val questMessage:String? = null) {
class Success<T>(private val data: T): Resource<T>(data)
class Failure<T>(private val data: T? = null, private val message: String): Resource<T>(data, message)
class Loading<T>: Resource<T>()
} | 0 | Kotlin | 2 | 0 | e0dd5dbdb3cfa0c203c7a088cd70ac4c21618cc0 | 328 | EquiFly | MIT License |
app/src/main/java/club/gitmad/mathgame/fragments/GameFragment.kt | git-mad | 239,557,023 | false | null | package club.gitmad.mathgame.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import club.gitmad.mathgame.R
import kotlinx.android.synthetic.main.fragment_game.*
class GameFragment : Fragment() {
private var numQuestions = 0
private var numCorrect = 0
private var currQuestion = 0
private var startTime = System.currentTimeMillis()
private val args: GameFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_game, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
numQuestions = args.numQuestions
setQuestion()
}
private fun setQuestion() {
tvQuestionNumber.text = "Question: $currQuestion/$numQuestions"
val firstTerm = (0..10).random()
val secondTerm = (0..10).random()
val question = "$firstTerm + $secondTerm"
tvQuestion.text = question
btnAnswer.setOnClickListener {
val userAnswer = Integer.parseInt(etAnswer.text.toString())
if (firstTerm + secondTerm == userAnswer) {
Toast.makeText(context, "Correct!", Toast.LENGTH_SHORT).show()
numCorrect++
} else {
Toast.makeText(context, "Incorrect!", Toast.LENGTH_SHORT).show()
}
currQuestion++
if (currQuestion == numQuestions) {
this.findNavController().navigate(
GameFragmentDirections.actionGameFragmentToResultsFragment(
numCorrect,
numQuestions,
System.currentTimeMillis() - startTime
)
)
}
etAnswer.setText("")
setQuestion()
}
}
}
| 0 | Kotlin | 0 | 0 | 64527191d896aa053e75f748a77d1433e7e59a00 | 2,209 | MathGame | MIT License |
waypoint-core/src/test/java/com/squaredcandy/waypoint/core/semantics/Finders.kt | squaredcandy | 638,860,321 | false | {"Kotlin": 174587} | package com.squaredcandy.waypoint.core.semantics
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.SemanticsNodeInteractionCollection
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
//region Waypoint Holder
fun SemanticsNodeInteractionsProvider.onWaypointHolderNode(
useUnmergedTree: Boolean = false,
): SemanticsNodeInteraction {
return onNode(
matcher = hasWaypointHolder(),
useUnmergedTree = useUnmergedTree,
)
}
fun SemanticsNodeInteractionsProvider.onWaypointHolderNodes(
useUnmergedTree: Boolean = false,
): SemanticsNodeInteractionCollection {
return onAllNodes(
matcher = hasWaypointHolder(),
useUnmergedTree = useUnmergedTree,
)
}
//endregion
//region Waypoint Action
fun SemanticsNodeInteractionsProvider.onWaypointActionProviderNode(
useUnmergedTree: Boolean = false,
): SemanticsNodeInteraction {
return onNode(
matcher = hasWaypointActionProvider(),
useUnmergedTree = useUnmergedTree,
)
}
fun SemanticsNodeInteractionsProvider.onWaypointActionProviderNodes(
useUnmergedTree: Boolean = false,
): SemanticsNodeInteractionCollection {
return onAllNodes(
matcher = hasWaypointActionProvider(),
useUnmergedTree = useUnmergedTree,
)
}
//endregion
//region Waypoint Route
fun SemanticsNodeInteractionsProvider.onWaypointRouteNode(
useUnmergedTree: Boolean = false,
): SemanticsNodeInteraction {
return onNode(
matcher = hasWaypointRoute(),
useUnmergedTree = useUnmergedTree,
)
}
//endregion
| 0 | Kotlin | 0 | 0 | a067f6a1a88f53e402d0359688b83ca2b0fbb373 | 1,600 | waypoint | Apache License 2.0 |
app/src/main/java/com/example/intelligent_shopping_cart/utils/TencentMapUtils.kt | cxp-13 | 629,093,945 | false | null | package com.example.intelligent_shopping_cart.utils
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer
object TencentMapUtils {
/**
* 设置用户是否同意隐私协议
* 需要在初始化地图之前完成,传入true后才能正常使用地图功能
* @param isAgree 是否同意隐私协议
*/
fun setAgreePrivacy() {
TencentLocationManager.setUserAgreePrivacy(true)
TencentMapInitializer.setAgreePrivacy(true)
}
} | 0 | Kotlin | 0 | 0 | 6a003112f1b1b1f67e191cf5ed59d3942afc1d25 | 543 | Intelligent-Shopping-Cart-APP | Apache License 2.0 |
app/src/main/java/com/example/nbaapp/di/modules/AppModule.kt | grishaster80 | 256,464,746 | false | null | package com.example.nbaapp.di.modules
import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.room.Room
import com.example.nbaapp.data.source.local.Database
import com.example.nbaapp.data.source.local.NbaDao
import com.example.nbaapp.utils.Constants
import com.example.nbaapp.utils.Utils
import com.example.nbaapp.presentation.nba.NbaViewModelFactory
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule(val app: Application) {
@Provides
@Singleton
fun provideApplication(): Application = app
@Provides
@Singleton
fun provideNbaDatabase(app: Application): Database = Room.databaseBuilder(app,
Database::class.java, Constants.DATABASE_NAME)
.fallbackToDestructiveMigration()
.build()
@Provides
@Singleton
fun provideNbaDao(
database: Database): NbaDao = database.nbaDao()
@Provides
@Singleton
fun provideNbaViewModelFactory(
factory: NbaViewModelFactory
): ViewModelProvider.Factory = factory
@Provides
@Singleton
fun provideUtils(): Utils = Utils(app)
} | 0 | Kotlin | 0 | 0 | db9035add7dd5636b197b62b02db89fb27dfd0d6 | 1,148 | NbaApp | MIT License |
src/main/java/domain/enums/InvoiceGenerationType.kt | s61-austria | 123,896,740 | false | null | package domain.enums
enum class InvoiceGenerationType {
AUTO,
MANUAL
}
| 0 | Kotlin | 0 | 0 | baf4e0543739265d6b8315a67bd39cedc76e6823 | 80 | kontofahren | MIT License |
LeetCode/Kotlin/src/common/Assert.kt | TaylorKunZhang | 352,502,846 | false | null | package common
fun <T> assertEquals(expected: List<T>, actual: List<T>) {
if (expected.size != actual.size) {
throw Exception("Comparison Failure.")
}
expected.indices.forEach {
if (expected[it] != actual[it]) {
throw Exception("Comparison Failure.")
}
}
} | 0 | Kotlin | 0 | 0 | c94c65c6db9f739ae5156150bb00f179b7e5307b | 310 | algorithm | Apache License 2.0 |
app/src/main/java/com/ban2apps/me/database/dao/StoryDao.kt | bandacode | 139,271,517 | false | {"Kotlin": 23933, "Java": 1073} | package com.ban2apps.me.database.dao
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import com.ban2apps.me.database.data.Story
@Dao
interface StoryDao {
@Query("SELECT * FROM stories WHERE id = :id")
fun getStory(id: Int): LiveData<Story>
@Query("SELECT * FROM stories ORDER BY timestamp DESC")
fun getStories(): LiveData<List<Story>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(story: Story)
@Query("DELETE FROM stories WHERE id = :id")
fun delete(id: Int)
@Query("DELETE FROM stories")
fun deleteAll()
} | 0 | Kotlin | 0 | 0 | 3905a1bea8b338ba6e1144d476e35cbde9f6dd0a | 598 | Me-ALCwithGoogle-FinalChallenge | MIT License |
src/main/kotlin/agreement/coordinator/PhaseOutcome.kt | muratovv | 193,386,673 | false | null | package agreement.coordinator
import agreement.CommitCertificate
import agreement.RejectCertificate
import agreement.UndecidedCertificate
/**
* Outcome of the first phase of the agreement
*/
sealed class FirstPhaseOutcome {
/**
* Means that some hash was agreed
*/
class CommitOutcome(val commitCertificate: CommitCertificate) : FirstPhaseOutcome()
/**
* Means that no one in the network had collected a [CommitOutcome]
*/
class RejectOutcome(val rejectCertificate: RejectCertificate) : FirstPhaseOutcome()
/**
* Means that another peer may collect commit or reject
*/
class UndecidedOutcome(val undecidedCertificate: UndecidedCertificate) : FirstPhaseOutcome()
}
/**
* Outcome of second phase of the agreement
*/
sealed class SecondPhaseOutcome {
/**
* Same as [FirstPhaseOutcome.CommitOutcome]
*/
class CommitOutcome(val commitCertificate: CommitCertificate) :
SecondPhaseOutcome()
/**
* Same as [FirstPhaseOutcome.RejectOutcome]
*/
class RejectOutcome(val rejectSertificate: RejectCertificate) : SecondPhaseOutcome()
}
| 0 | Kotlin | 0 | 1 | 37c6a14df9b4723bfa7133584576ff1d1c76279a | 1,131 | yet_another_consensus | MIT License |
kgl-vulkan/src/commonMain/kotlin/com/kgl/vulkan/enums/QueryPipelineStatistic.kt | NikkyAI | 168,431,916 | true | {"Kotlin": 1894114, "C": 1742775} | /**
* Copyright [2019] [<NAME>]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kgl.vulkan.enums
import com.kgl.vulkan.utils.VkFlag
expect enum class QueryPipelineStatistic : VkFlag<QueryPipelineStatistic> {
INPUT_ASSEMBLY_VERTICES,
INPUT_ASSEMBLY_PRIMITIVES,
VERTEX_SHADER_INVOCATIONS,
GEOMETRY_SHADER_INVOCATIONS,
GEOMETRY_SHADER_PRIMITIVES,
CLIPPING_INVOCATIONS,
CLIPPING_PRIMITIVES,
FRAGMENT_SHADER_INVOCATIONS,
TESSELLATION_CONTROL_SHADER_PATCHES,
TESSELLATION_EVALUATION_SHADER_INVOCATIONS,
COMPUTE_SHADER_INVOCATIONS
}
| 0 | Kotlin | 0 | 0 | 51dfa8a4c655ff8bcf017d8d4a2eb660e14473ed | 1,082 | kgl | Apache License 2.0 |
compiler/testData/codegen/bytecodeText/defaultMethodBody.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | fun test(a: Int, z: String = try{"1"} catch (e: Exception) {"2"}) {
"Default body"
}
//1 ILOAD 0\s*ALOAD 1\s*INVOKESTATIC DefaultMethodBodyKt\.test \(ILjava/lang/String;\)V
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 178 | kotlin | Apache License 2.0 |
src/test/java/dev/blachut/svelte/lang/SvelteTestSuite.kt | tomblachut | 184,821,501 | false | {"JavaScript": 467590, "Kotlin": 421793, "Java": 81911, "Lex": 16310, "Svelte": 14923, "HTML": 2052, "TypeScript": 709} | package dev.blachut.svelte.lang
import dev.blachut.svelte.lang.codeInsight.*
import dev.blachut.svelte.lang.editor.SvelteBraceTypedTest
import dev.blachut.svelte.lang.editor.SvelteCommenterTest
import dev.blachut.svelte.lang.editor.SvelteEditorTest
import dev.blachut.svelte.lang.editor.SvelteEmmetTest
import dev.blachut.svelte.lang.format.SvelteFormatterTest
import dev.blachut.svelte.lang.parsing.html.*
import dev.blachut.svelte.lang.service.SvelteServiceCompletionTest
import dev.blachut.svelte.lang.service.SvelteServiceDocumentationTest
import dev.blachut.svelte.lang.service.SvelteServiceTest
import org.junit.runner.RunWith
import org.junit.runners.Suite
@RunWith(Suite::class)
@Suite.SuiteClasses(
SvelteServiceTest::class,
SvelteServiceCompletionTest::class,
SvelteServiceDocumentationTest::class,
)
class SvelteServiceTestSuite
@RunWith(Suite::class)
@Suite.SuiteClasses(
// Parsing
SvelteHtmlRegressionParsingTest::class,
SvelteHighlightingLexerTest::class,
SvelteHtmlParserTest::class,
SvelteDirectiveLexerTest::class,
SvelteDirectiveParserTest::class,
// Editing
SvelteFormatterTest::class,
SvelteBraceTypedTest::class,
SvelteCommenterTest::class,
SvelteEditorTest::class,
SvelteEmmetTest::class,
// Code insight
SvelteAutoPopupTest::class,
SvelteCompletionTest::class,
SvelteHighlightingTest::class,
SvelteRenameTest::class,
SvelteResolveTest::class,
SvelteNavigationTest::class,
SvelteTypeScriptCompletionTest::class,
SvelteTypeScriptHighlightingTest::class,
SvelteCopyPasteTest::class,
SvelteCreateVariableTest::class,
SvelteCreateFunctionTest::class,
SvelteCreateImportTest::class,
SvelteKitTest::class,
// Service
SvelteServiceTestSuite::class,
)
class SvelteTestSuite
| 0 | JavaScript | 38 | 467 | 4115acf10e697dd45f90d7e0cabe54a8b10d4e83 | 1,810 | svelte-intellij | MIT License |
android/app/src/main/kotlin/com/example/covstats/MainActivity.kt | PatrickNiyogitare28 | 374,115,940 | false | {"Dart": 22853, "HTML": 3695, "Swift": 404, "Kotlin": 125, "Objective-C": 38} | package com.example.covstats
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 5 | 7b856e5cc1a99cf52bf6e933f78e328bcff72090 | 125 | covastats | MIT License |
android_sdk/src/main/java/co/optable/android_sdk/Config.kt | Optable | 295,526,133 | false | null | /*
* Copyright © 2020 Optable Technologies Inc. All rights reserved.
* See LICENSE for details.
*/
package co.optable.android_sdk
import android.util.Base64
class Config(val host: String, val app: String, val insecure: Boolean = false) {
fun edgeBaseURL(): String {
var proto = "https://"
if (this.insecure) {
proto = "http://"
}
return proto + this.host + "/"
}
fun passportKey(): String {
return key("PASS")
}
fun targetingKey(): String {
return key("TGT")
}
private fun key(kind: String): String {
val sfx = this.host + "/" + this.app
return "OPTABLE_" + kind + "_" + Base64.encodeToString(sfx.toByteArray(), 0)
}
} | 2 | Kotlin | 0 | 0 | 7e9eaee97740eadca55434248967d2d04b560175 | 737 | optable-android-sdk | Apache License 2.0 |
src/main/kotlin/dev/isagood/caiogg/klassics/models/Klassics.kt | DevCaioGG | 599,681,486 | false | null | package dev.isagood.caiogg.klassics.models
class Klassics {
} | 2 | Kotlin | 1 | 0 | fa0e042edeac81b31b4be436c5d40eb4706c6438 | 62 | Klassics | MIT License |
kotter/src/commonMain/kotlin/com/varabyte/kotter/platform/internal/concurrent/annotations/ThreadSafe.kt | varabyte | 397,769,020 | false | {"Kotlin": 418737} | package com.varabyte.kotter.platform.internal.concurrent.annotations
// This is a fork of https://jcip.net/annotations/doc/net/jcip/annotations/ThreadSafe.html, done in service of migrating
// Kotter over to a multiplatform world.
@MustBeDocumented
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
internal annotation class ThreadSafe
| 15 | Kotlin | 16 | 498 | 62173802985117c8e6e53dc2b7b533cbdcf7daf2 | 360 | kotter | Apache License 2.0 |
data/src/main/java/lucassales/com/data/entities/Suit.kt | lucassales2 | 181,433,644 | false | null | package lucassales.com.data.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "suits")
data class Suit(@PrimaryKey override val id: Long) : GameEntity | 0 | Kotlin | 0 | 0 | fc6db5e6de890e075fcb8a215721b8ca7bc2f8ad | 191 | CardGame | MIT License |
src/main/kotlin/com/jetbrains/snakecharm/stringLanguage/lang/SmkSLElementVisitor.kt | JetBrains-Research | 165,259,818 | false | {"Python": 1277216, "Kotlin": 836545, "Gherkin": 584412, "Java": 15215, "HTML": 8352, "Lex": 2408, "Roff": 74} | package com.jetbrains.snakecharm.stringLanguage.lang
import com.jetbrains.python.psi.PyElementVisitor
import com.jetbrains.snakecharm.stringLanguage.lang.psi.SmkSLReferenceExpression
import com.jetbrains.snakecharm.stringLanguage.lang.psi.SmkSLSubscriptionExpression
import com.jetbrains.snakecharm.stringLanguage.lang.psi.SmkSLSubscriptionIndexKeyExpression
interface SmkSLElementVisitor {
/**
* Adapter instead of inheritance for to python specific methods
*/
val pyElementVisitor: PyElementVisitor
fun visitSmkSLReferenceExpression(expr: SmkSLReferenceExpression) {
pyElementVisitor.visitPyElement(expr)
}
fun visitSmkSLSubscriptionExpressionKey(expr: SmkSLSubscriptionIndexKeyExpression) {
pyElementVisitor.visitPyElement(expr)
}
fun visitSmkSLSubscriptionExpression(expr: SmkSLSubscriptionExpression) {
pyElementVisitor.visitPyElement(expr)
}
} | 108 | Python | 7 | 58 | ac0d9c4a246b287f99b857865a24378eeaad5419 | 920 | snakecharm | MIT License |
src/main/kotlin/org/t246osslab/easybuggy4kt/exceptions/IllegalArgumentExceptionController.kt | k-tamura | 107,135,934 | false | null | package org.t246osslab.easybuggy4kt.exceptions
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.servlet.ModelAndView
import java.util.*
@Controller
class IllegalArgumentExceptionController {
@RequestMapping(value = "/iae")
fun process(mav: ModelAndView) {
mav.addObject(ArrayList<Any>(-1))
}
}
| 8 | Kotlin | 4 | 3 | 837775d00038e482647a6fcbe1c8ddfed0ef906f | 410 | easybuggy4kt | Apache License 2.0 |
_src/Chapter03/AnnotationBasedConfiguration/src/autowiredAnnotation/UserDetails.kt | paullewallencom | 319,169,129 | false | null | package autowiredAnnotation
class UserDetails{
init {
println("This class has all the details of the user")
}
fun getDetails(){
println("Name: <NAME>")
println("Village: Konohagakure")
}
} | 0 | Kotlin | 0 | 1 | 7f70b39ec3926fe712617984974b13e6039df5c0 | 238 | android-spring-978-1-7893-4925-2 | Apache License 2.0 |
typesafe-datastore/src/main/java/com/jasjeet/typesafe_datastore/DataStoreSerializer.kt | 07jasjeet | 748,229,921 | false | {"Kotlin": 35719} | package com.jasjeet.typesafe_datastore
/** @property T Object or higher type.
* @property R Primitive or serializable type.*/
interface DataStoreSerializer<T, R> {
/** Convert from Primitive [R] to Object [T].*/
fun from(value: R): T
/** Convert to Primitive [T] from Object [R].*/
fun to(value: T): R
/** Default value for errors and null values.*/
fun default(): T
companion object {
/** Default Serializer if T and R are same in [DataStoreSerializer].*/
fun <T> defaultSerializer(defaultValue: T): DataStoreSerializer<T, T> =
object: DataStoreSerializer<T, T> {
override fun from(value: T): T = value
override fun to(value: T): T = value
override fun default(): T = defaultValue
}
}
} | 0 | Kotlin | 0 | 0 | f57d3c0c81f71d5ee2658560ef80307116d7e4d7 | 825 | typesafe-datastore | Apache License 2.0 |
src/main/kotlin/com/github/flagshipio/jetbrain/dataClass/Goal.kt | flagship-io | 691,142,277 | false | {"Kotlin": 285234} | package com.github.flagshipio.jetbrain.dataClass
data class Goal(
var id: String?,
var label: String?,
var type: String?,
var operator: String?,
var value: String?,
) {
} | 4 | Kotlin | 0 | 0 | dc22095f5573b9384fee09c816e3b6869cebf0b3 | 191 | flagship-jetbrain | Apache License 2.0 |
compiler/testData/codegen/box/reified/callableReferenceInlinedFunFromOtherModule.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
inline fun <reified T> baz(value: T): String = "OK" + value
fun test(): String {
val f: (Any) -> String = ::baz
return f(1)
}
object Foo {
val log = "123"
}
public inline fun <reified T> Foo.foo(value: T): String =
log + value
val test2 = { "OK".let(Foo::foo) }
object Bar {
val log = "321"
public inline fun <reified T> bar(value: T): String =
log + value
}
val test3 = { "OK".let(Bar::bar) }
class C {
inline fun <reified T: String> qux(value: T): String = "OK" + value
}
fun test4(): String {
val c = C()
val cr: (String) -> String = c::qux
return cr("456")
}
inline fun <reified T: Any> ((Any) -> String).cux(value: T): String = this(value)
fun test5(): String {
val foo: (Any) -> String = ({ b: Any ->
val a: (Any) -> String = ::baz
a(b)
})::cux
return foo(3)
}
inline fun <reified T, K, reified S> bak(value1: T, value2: K, value3: S): String = "OK" + value1 + value2 + value3
fun test6(): String {
val f: (Any, Int, String) -> String = ::bak
return f(1, 37, "joo")
}
inline fun <reified T, K> bal(value1: Array<K>, value2: Array<T>): String = "OK" + value1.joinToString() + value2.joinToString()
fun test7(): String {
val f: (Array<Any>, Array<Int>) -> String = ::bal
return f(arrayOf("mer", "nas"), arrayOf(73, 37))
}
class E<T>
public inline fun <reified T> E<T>.foo(value: T): String = "OK" + value
class F<T1> {
inline fun <reified T2> foo(x: T1, y: T2): Any? = "OK" + x + y
}
inline fun <reified T, K> bam(value1: K?, value2: T?): String = "OK" + value1.toString() + value2.toString()
fun <T> test10(): String {
val f: (T?, String?) -> String = ::bam
return f(null, "abc")
}
inline fun <T> test11Impl() : String {
val f: (T?, String?) -> String = ::bam
return f(null, "def")
}
fun <T> test11() = test11Impl<T>()
fun box(): String {
val test1 = test()
if (test1 != "OK1") return "fail1: $test1"
val test2 = test2()
if (test2 != "123OK") return "fail2: $test2"
val test3 = test3()
if (test3 != "321OK") return "fail3: $test3"
val test4 = test4()
if (test4 != "OK456") return "fail4: $test4"
val test5 = test5()
if (test5 != "OK3") return "fail5: $test5"
val test6 = test6()
if (test6 != "OK137joo") return "fail6: $test6"
val test7 = test7()
if (test7 != "OKmer, nas73, 37") return "fail7: $test7"
val test8 = E<Int>().foo(56)
if (test8 != "OK56") return "fail8: $test8"
val test9 = F<Int>().foo(65, "hello")
if (test9 != "OK65hello") return "fail9: $test9"
val test10 = test10<Int>()
if (test10 != "OKnullabc") return "fail10: $test10"
val test11 = test11<Int>()
if (test11 != "OKnulldef") return "fail11: $test11"
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,784 | kotlin | Apache License 2.0 |
PRACTICE_JETPACK/app/src/main/java/nlab/practice/jetpack/util/recyclerview/touch/ItemViewTouchHelperUsecase.kt | skaengus2012 | 153,380,376 | false | null | /*
* Copyright (C) 2007 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 nlab.practice.jetpack.util.recyclerview.touch
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
/**
* @author Doohyun
* @since 2019. 02. 25
*/
@AutoFactory
class ItemViewTouchHelperUsecase(
@Provided private val viewHolder: RecyclerView.ViewHolder,
private val itemViewTouchHelper: ItemTouchHelper
) {
fun startDrag() {
itemViewTouchHelper.startDrag(viewHolder)
}
} | 2 | Kotlin | 0 | 0 | 6c742e0888f5e01e0d7f0f1dd3d57707c62716b0 | 1,160 | Practice-Jetpack | Apache License 2.0 |
src/main/kotlin/com/github/fantom/codeowners/util/Constants.kt | fan-tom | 325,829,611 | false | {"Kotlin": 257763, "Lex": 5866, "HTML": 966} | package com.github.fantom.codeowners.util
import org.jetbrains.annotations.NonNls
/**
* Class containing common constant variables.
*/
object Constants {
/** New line character. */
@NonNls
val NEWLINE = "\n"
/** Hash sign. */
@NonNls
val HASH = "#"
/** Dollar sign separator. */
@NonNls
val DOLLAR = "$"
/** Star sign. */
@NonNls
val STAR = "*"
/** Stars sign. */
@NonNls
val DOUBLESTAR = "**"
}
| 22 | Kotlin | 4 | 15 | f898c1113f2f81b25aaeb6ba87f8e570da0ba08e | 470 | intellij-codeowners | MIT License |
src/test/kotlin/com/example/springwebflux/unit/service/UserServiceTest.kt | rsvinicius | 524,813,193 | false | null | package com.example.springwebflux.unit.service
import com.example.springwebflux.mock.UserMock.updatedUser
import com.example.springwebflux.mock.UserMock.validUserOne
import com.example.springwebflux.mock.UserMock.validUserThree
import com.example.springwebflux.mock.UserMock.validUserTwo
import com.example.springwebflux.model.request.UpdateUserRequest
import com.example.springwebflux.repository.UserRepository
import com.example.springwebflux.service.UserService
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.test.StepVerifier
@ExtendWith(MockKExtension::class)
class UserServiceTest {
@InjectMockKs
private lateinit var userService: UserService
@MockK
private lateinit var userRepository: UserRepository
@Test
@DisplayName("Create user successfully")
fun testCreateUser() {
every {
userRepository.save(any())
} returns Mono.just(validUserOne())
val user = userService.createUser(validUserOne())
StepVerifier
.create(user)
.consumeNextWith { u ->
assert(u.id == "1")
assert(u.name == "<NAME>")
assert(u.age == 25)
assert(u.salary == 16000.0)
assert(u.department == "IT")
}
.expectNextCount(0)
.verifyComplete()
}
@Test
@DisplayName("Get all users successfully")
fun getAllUsersTest() {
every {
userRepository.findAll()
} returns Flux.just(validUserOne(), validUserTwo(), validUserThree())
val users = userService.getAllUsers()
StepVerifier
.create(users)
.consumeNextWith { u ->
assert(u.id == "1")
assert(u.name == "<NAME>")
}
.consumeNextWith { u ->
assert(u.id == "2")
assert(u.name == "<NAME>")
}
.consumeNextWith { u ->
assert(u.id == "3")
assert(u.name == "<NAME>")
}
.expectNextCount(0)
.verifyComplete()
}
@Test
@DisplayName("Find user by ID successfully")
fun findUserByIdTest() {
every {
userRepository.findById("2")
} returns Mono.just(validUserTwo())
val user = userService.findUserById("2")
StepVerifier
.create(user)
.consumeNextWith { u ->
assert(u.id == "2")
assert(u.name == "<NAME>")
assert(u.age == 23)
assert(u.salary == 10000.0)
assert(u.department == "HR")
}
.expectNextCount(0)
.verifyComplete()
}
@Test
@DisplayName("Delete user successfully")
fun deleteUserTest() {
every {
userRepository.deleteById("1")
} returns Mono.empty()
val deletedUser = userService.deleteUser("1")
StepVerifier
.create(deletedUser)
.expectNextCount(0)
.verifyComplete()
}
@Test
@DisplayName("Update user successfully")
fun updateUserTest() {
every {
userRepository.findById("3")
} returns Mono.just(validUserThree())
every {
userRepository.save(any())
} returns Mono.just(updatedUser())
val user = userService.updateUser("3", UpdateUserRequest(salary = 14000.0))
StepVerifier
.create(user)
.consumeNextWith { u ->
assert(u.id == "3")
assert(u.name == "<NAME>")
assert(u.age == 20)
assert(u.salary == 14000.0)
assert(u.department == "IT")
}
.expectNextCount(0)
.verifyComplete()
}
@Test
@DisplayName("Fetch all users containing name John ordered by age ascended successfully")
fun fetchUsersTest() {
every {
userRepository.findAllByNameContainsOrderByAgeAsc(any())
} returns Flux.just(validUserThree(), validUserOne())
val users = userService.fetchUsers("John")
StepVerifier
.create(users)
.consumeNextWith { u ->
assert(u.id == "3")
assert(u.name == "<NAME>")
assert(u.age == 20)
}
.consumeNextWith { u ->
assert(u.id == "1")
assert(u.name == "<NAME>")
assert(u.age == 25)
}
.expectNextCount(0)
.verifyComplete()
}
} | 0 | Kotlin | 0 | 0 | 3a0b539a6d0d823bc25b6e827e335e0e6c324de7 | 4,940 | spring-webflux | MIT License |
src/main/kotlin/com/qd/portal/common/exceptions/rest/ServerException.kt | XPlay1990 | 227,670,002 | false | null | package com.qd.portal.common.exceptions.rest
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
/**
* Created by <NAME> on 26.06.2019.
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
class ServerException : RuntimeException {
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
}
| 0 | Kotlin | 0 | 0 | 20830a88a91495c249720f6cabcecce2050c208a | 423 | QD-Software-Backend | MIT License |
network/android/src/main/kotlin/co/yml/network/android/engine/cache/disklrucache/DiskLruCache.kt | codeandtheory | 504,124,065 | false | {"Kotlin": 381865} | package co.yml.network.android.engine.cache.disklrucache
import androidx.annotation.VisibleForTesting
import co.yml.network.android.engine.cache.disklrucache.DiskLruCache.Editor
import java.io.BufferedWriter
import java.io.Closeable
import java.io.EOFException
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.FilterOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.io.Writer
import java.nio.charset.StandardCharsets.US_ASCII
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.Callable
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
/**
* A cache that uses a bounded amount of space on a filesystem. Each cache
* entry has a string key and a fixed number of values. Each key must match
* the regex **[a-z0-9_-]{1,64}**. Values are byte sequences,
* accessible as streams or files. Each value must be between `0` and
* `Integer.MAX_VALUE` bytes in length.
*
*
* The cache stores its data in a directory on the filesystem. This
* directory must be exclusive to the cache; the cache may delete or overwrite
* files from its directory. It is an error for multiple processes to use the
* same cache directory at the same time.
*
*
* This cache limits the number of bytes that it will store on the
* filesystem. When the number of stored bytes exceeds the limit, the cache will
* remove entries in the background until the limit is satisfied. The limit is
* not strict: the cache may temporarily exceed it while waiting for files to be
* deleted. The limit does not include filesystem overhead or the cache
* journal so space-sensitive applications should set a conservative limit.
*
*
* Clients call [.edit] to create or update the values of an entry. An
* entry may have only one editor at one time; if a value is not available to be
* edited then [.edit] will return null.
*
* * When an entry is being **created** it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* * When an entry is being **edited**, it is not necessary
* to supply data for every value; values default to their previous
* value.
*
* Every [edit] call must be matched by a call to [Editor.commit]
* or [Editor.abort]. Committing is atomic: a read observes the full set
* of values as they were before or after the commit, but never a mix of values.
*
*
* Clients call [.get] to read a snapshot of an entry. The read will
* observe the value at the time that [.get] was called. Updates and
* removals after the call do not impact ongoing reads.
*
*
* This class is tolerant of some I/O errors. If files are missing from the
* filesystem, the corresponding entries will be dropped from the cache. If
* an error occurs while writing a cache value, the edit will fail silently.
* Callers should handle other problems by catching `IOException` and
* responding appropriately.
*
* inspired by https://github.com/JakeWharton/DiskLruCache
*/
class DiskLruCache private constructor(
/** Returns the directory where this cache stores its data. */
/**
* This cache uses a journal file named "journal". A typical journal file
* looks like this:
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the
* constant string "libcore.io.DiskLruCache", the disk cache's version,
* the application's version, the value count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a
* cache entry. Each line contains space-separated values: a state, a key,
* and optional state-specific values.
* o DIRTY lines track that an entry is actively being created or updated.
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
* temporary files may need to be deleted.
* o CLEAN lines track a cache entry that has been successfully published
* and may be read. A publish line is followed by the lengths of each of
* its values.
* o READ lines track accesses for LRU.
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may
* occasionally be compacted by dropping redundant lines. A temporary file named
* "journal.tmp" will be used during compaction; that file should be deleted if
* it exists when the cache is opened.
*
* inspired by https://github.com/JakeWharton/DiskLruCache
*/
val directory: File,
private val appVersion: Int,
private val valueCount: Int,
maxSize: Long
) : Closeable {
private val journalFile = File(directory, JOURNAL_FILE)
private val journalFileTmp = File(directory, JOURNAL_FILE_TEMP)
private val journalFileBackup = File(directory, JOURNAL_FILE_BACKUP)
private var journalWriter: Writer? = null
private val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true)
private var redundantOpCount = 0
/** Returns true if this cache has been closed. */
val isClosed: Boolean
@Synchronized get() = journalWriter == null
/**
* Store the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
var size: Long = 0
@Synchronized get
private set
/**
* Store the maximum number of bytes that this cache should use to store its data.
*/
var maxSize = maxSize
@Synchronized get
@Synchronized set(value) {
field = value
executorService.submit(cleanupCallable)
}
/**
* To differentiate between old and current snapshots, each entry is given
* a sequence number each time an edit is committed. A snapshot is stale if
* its sequence number is not equal to its entry's sequence number.
*/
private var nextSequenceNumber: Long = 0
/** This cache uses a single background thread to evict entries. */
internal var executorService =
ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, LinkedBlockingQueue())
@VisibleForTesting internal set
internal val cleanupCallable: Callable<Void> = Callable {
synchronized(this@DiskLruCache) {
if (journalWriter == null) {
return@Callable null // Closed.
}
trimToSize()
if (journalRebuildRequired()) {
rebuildJournal()
redundantOpCount = 0
}
}
return@Callable null
}
@VisibleForTesting get
@Throws(DiskLruCacheException::class)
private fun readJournal() {
val reader = StrictLineReader(FileInputStream(journalFile), US_ASCII)
try {
val magic = reader.readLine()
val version = reader.readLine()
val appVersionString = reader.readLine()
val valueCountString = reader.readLine()
val blank = reader.readLine()
if (MAGIC != magic
|| VERSION_1 != version
|| appVersion.toString() != appVersionString
|| valueCount.toString() != valueCountString
|| "" != blank
) {
throw DiskLruCacheException(
ErrorCode.UNEXPECTED_JOURNAL_HEADER,
"unexpected journal header: expected [\"$MAGIC\", \"$VERSION_1\", \"$appVersion\", \"$valueCount\", \"$blank\"], actual [\"$magic\", \"$version\", \"$appVersionString\", \"$valueCountString\", \"$blank\"]"
)
}
var lineCount = 0
while (true) {
try {
readJournalLine(reader.readLine())
lineCount++
} catch (endOfJournal: EOFException) {
break
}
}
redundantOpCount = lineCount - lruEntries.size
// If we ended on a truncated line, rebuild the journal before appending to it.
if (reader.hasUnterminatedLine()) {
rebuildJournal()
} else {
journalWriter = BufferedWriter(
OutputStreamWriter(
FileOutputStream(journalFile, true),
US_ASCII
)
)
}
} finally {
closeQuietly(reader)
}
}
@Throws(DiskLruCacheException::class)
private fun readJournalLine(line: String) {
val firstSpace = line.indexOf(' ')
if (firstSpace == -1) {
throw DiskLruCacheException(
ErrorCode.INVALID_JOURNAL_LINE,
"Invalid journal line: $line"
)
}
val keyBegin = firstSpace + 1
val secondSpace = line.indexOf(' ', keyBegin)
val key: String
if (secondSpace == -1) {
key = line.substring(keyBegin)
if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) {
lruEntries.remove(key)
return
}
} else {
key = line.substring(keyBegin, secondSpace)
}
val entry = lruEntries.getOrPut(key) { Entry(key) }
if (secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN)) {
val parts = line.substring(secondSpace + 1).split(" ").toTypedArray()
entry.apply {
readable = true
currentEditor = null
setLengths(parts)
}
} else if (secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY)) {
entry.currentEditor = Editor(entry)
} else if (secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ)) {
// This work was already done by calling lruEntries.get().
} else {
throw DiskLruCacheException(
ErrorCode.INVALID_JOURNAL_LINE,
"Invalid journal line: $line"
)
}
}
/**
* Computes the initial size and collects garbage as a part of opening the
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
*/
@Throws(DiskLruCacheException::class)
private fun processJournal() {
deleteIfExists(journalFileTmp)
val iterator = lruEntries.values.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
if (entry.currentEditor == null) {
for (index in 0 until valueCount) {
size += entry.lengths[index]
}
} else {
entry.currentEditor = null
for (index in 0 until valueCount) {
deleteIfExists(entry.getCleanFile(index))
deleteIfExists(entry.getDirtyFile(index))
}
iterator.remove()
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the
* current journal if it exists.
*/
@Synchronized
@Throws(IOException::class)
private fun rebuildJournal() {
journalWriter?.close()
val bufferedWriter = BufferedWriter(
OutputStreamWriter(FileOutputStream(journalFileTmp), US_ASCII)
)
bufferedWriter.use { writer ->
writer.write("$MAGIC\n$VERSION_1\n$appVersion\n$valueCount\n\n")
lruEntries.values.forEach {
if (it.currentEditor != null) {
writer.write("$DIRTY ${it.key}\n")
} else {
writer.write("$CLEAN ${it.key}${it.getLengths()}\n")
}
}
}
if (journalFile.exists()) {
renameTo(journalFile, journalFileBackup, true)
}
renameTo(journalFileTmp, journalFile, false)
journalFileBackup.delete()
journalWriter =
BufferedWriter(OutputStreamWriter(FileOutputStream(journalFile, true), US_ASCII))
}
/**
* Returns a snapshot of the entry named [key], or null if it doesn't
* exist is not currently readable. If a value is returned, it is moved to
* the head of the LRU queue.
*/
@Synchronized
@Throws(IOException::class)
operator fun get(key: String): Snapshot? {
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return null
if (!entry.readable) {
return null
}
// Open all streams eagerly to guarantee that we see a single published
// snapshot. If we opened streams lazily then the streams could come
// from different edits.
val inputStream = arrayOfNulls<InputStream>(valueCount)
try {
for (index in 0 until valueCount) {
inputStream[index] = FileInputStream(entry.getCleanFile(index))
}
} catch (e: FileNotFoundException) {
// A file must have been deleted manually!
inputStream.forEach { closeQuietly(it) }
return null
}
redundantOpCount++
journalWriter?.append("$READ $key\n")
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable)
}
return Snapshot(key, entry.sequenceNumber, inputStream, entry.lengths)
}
/**
* Returns an editor for the entry named [key], or null if another
* edit is in progress.
*/
@Synchronized
@Throws(IOException::class)
internal fun edit(key: String, expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER): Editor? {
checkNotClosed()
validateKey(key)
var entry = lruEntries[key]
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && entry?.sequenceNumber != expectedSequenceNumber) {
return null // Snapshot is stale.
}
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
} else if (entry.currentEditor != null) {
return null // Another edit is in progress.
}
val editor = Editor(entry)
entry.currentEditor = editor
// Flush the journal before creating files to prevent file leaks.
journalWriter?.apply {
write("$DIRTY $key\n")
flush()
}
return editor
}
/**
* Returns the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
@Synchronized
fun size(): Long {
return size
}
@Synchronized
@Throws(IOException::class)
private fun completeEdit(editor: Editor, success: Boolean) {
val entry = editor.entry
check(entry.currentEditor == editor)
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (i in 0 until valueCount) {
editor.written?.get(i)?.let { written ->
if (!written) {
editor.abort()
throw DiskLruCacheException(
ErrorCode.NO_VALUE_AT_INDEX,
"Newly created entry didn't create value for index $i"
)
}
}
if (!entry.getDirtyFile(i).exists()) {
editor.abort()
return
}
}
}
for (i in 0 until valueCount) {
val dirty = entry.getDirtyFile(i)
if (success) {
if (dirty.exists()) {
val clean = entry.getCleanFile(i)
dirty.renameTo(clean)
val oldLength = entry.lengths[i]
val newLength = clean.length()
entry.lengths[i] = newLength
size = size - oldLength + newLength
}
} else {
deleteIfExists(dirty)
}
}
redundantOpCount++
entry.currentEditor = null
if (entry.readable || success) {
entry.readable = true
journalWriter?.write("$CLEAN ${entry.key}${entry.getLengths()}\n")
if (success) {
entry.sequenceNumber = nextSequenceNumber++
}
} else {
lruEntries.remove(entry.key)
journalWriter?.write("$REMOVE ${entry.key}\n")
}
journalWriter?.flush()
if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable)
}
}
/**
* We only rebuild the journal when it will halve the size of the journal
* and eliminate at least 2000 ops.
*/
private fun journalRebuildRequired(): Boolean {
val redundantOpCompactThreshold = 2000
return (redundantOpCount >= redundantOpCompactThreshold && redundantOpCount >= lruEntries.size)
}
/**
* Drops the entry for [key] if it exists and can be removed. Entries
* actively being edited cannot be removed.
*
* @return true if an entry was removed.
*/
@Synchronized
@Throws(IOException::class)
fun remove(key: String): Boolean {
checkNotClosed()
validateKey(key)
val entry = lruEntries[key]
if (entry == null || entry.currentEditor != null) {
return false
}
for (i in 0 until valueCount) {
val file = entry.getCleanFile(i)
if (file.exists() && !file.delete()) {
throw DiskLruCacheException(ErrorCode.DELETE_FILE_FAILED, "failed to delete $file")
}
size -= entry.lengths[i]
entry.lengths[i] = 0
}
redundantOpCount++
journalWriter?.append("$REMOVE $key\n")
lruEntries.remove(key)
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable)
}
return true
}
private fun checkNotClosed() {
checkNotNull(journalWriter) { "cache is closed" }
}
/** Force buffered operations to the filesystem. */
@Synchronized
@Throws(IOException::class)
fun flush() {
checkNotClosed()
trimToSize()
journalWriter?.flush()
}
/** Closes this cache. Stored values will remain on the filesystem. */
@Synchronized
@Throws(IOException::class)
override fun close() {
if (journalWriter == null) {
return // Already closed.
}
lruEntries.values.forEach { it.currentEditor?.abort() }
trimToSize()
journalWriter?.close()
journalWriter = null
}
@Throws(IOException::class)
private fun trimToSize() {
while (size > maxSize) {
remove(lruEntries.entries.first().key)
}
}
/**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/
@Throws(IOException::class)
fun delete() {
close()
deleteContents(directory)
}
private fun validateKey(key: String) {
require(STRING_KEY_PATTERN.matcher(key).matches())
{ "keys must match regex $STRING_KEY_PATTERN: \"$key\"" }
}
/** A snapshot of the values for an entry. */
inner class Snapshot(
private val key: String,
private val sequenceNumber: Long,
private val inputStreams: Array<InputStream?>,
private val lengths: LongArray
) : Closeable {
/**
* Returns an editor for this snapshot's entry, or null if either the
* entry has changed since this snapshot was created or if another edit
* is in progress.
*/
@Throws(IOException::class)
fun edit(): Editor? = [email protected](key, sequenceNumber)
/** Returns the unbuffered stream with the value for `index`. */
fun getInputStream(index: Int) = inputStreams[index]
/** Returns the string value for `index`. */
@Throws(IOException::class)
fun getString(index: Int) =
getInputStream(index)?.let { inputStreamToString(it) }
/** Returns the byte length of the value for `index`. */
fun getLength(index: Int) = lengths[index]
override fun close(): Unit = inputStreams.forEach { closeQuietly(it) }
}
/** Edits the values for an entry. */
inner class Editor internal constructor(val entry: Entry) {
val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount)
private var hasErrors = false
private var committed = false
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
@Throws(IOException::class)
fun newInputStream(index: Int): InputStream? {
synchronized(this@DiskLruCache) {
check(entry.currentEditor == this)
return if (!entry.readable) {
null
} else try {
FileInputStream(entry.getCleanFile(index))
} catch (e: FileNotFoundException) {
null
}
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
@Throws(IOException::class)
fun getString(index: Int): String? = newInputStream(index)?.let { inputStreamToString(it) }
/**
* @return a new unbuffered output stream to write the value at
* [index]. If the underlying output stream encounters errors
* when writing to the filesystem, this edit will be aborted when
* [commit] is called. The returned output stream does not throw
* IOExceptions.
*/
@Throws(IOException::class)
fun newOutputStream(index: Int): OutputStream {
require(!(index < 0 || index >= valueCount)) {
"Expected index $index to be greater than 0 and less than the maximum value count of $valueCount"
}
synchronized(this@DiskLruCache) {
check(entry.currentEditor == this)
written?.set(index, true)
val dirtyFile = entry.getDirtyFile(index)
val outputStream = try {
FileOutputStream(dirtyFile)
} catch (e: FileNotFoundException) {
// Attempt to recreate the cache directory.
directory.mkdirs()
try {
FileOutputStream(dirtyFile)
} catch (e2: FileNotFoundException) {
// We are unable to recover. Silently eat the writes.
return NULL_OUTPUT_STREAM
}
}
return FaultHidingOutputStream(outputStream)
}
}
/** Sets the value at [index] to [value]. */
@Throws(IOException::class)
operator fun set(index: Int, value: String?) {
require(value != null) { "Value cannot be null" }
var writer: Writer? = null
try {
writer = OutputStreamWriter(newOutputStream(index), UTF_8)
writer.write(value)
} finally {
closeQuietly(writer)
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
@Throws(IOException::class)
fun commit() {
if (hasErrors) {
completeEdit(this, false)
remove(entry.key) // The previous entry is stale.
} else {
completeEdit(this, true)
}
committed = true
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
@Throws(IOException::class)
fun abort() {
completeEdit(this, false)
}
fun abortUnlessCommitted() {
if (!committed) {
try {
abort()
} catch (ignored: IOException) {
}
}
}
private inner class FaultHidingOutputStream(out: OutputStream) : FilterOutputStream(out) {
override fun write(oneByte: Int) {
try {
out.write(oneByte)
} catch (e: IOException) {
hasErrors = true
}
}
override fun write(buffer: ByteArray, offset: Int, length: Int) {
try {
out.write(buffer, offset, length)
} catch (e: IOException) {
hasErrors = true
}
}
override fun close() {
try {
out.close()
} catch (e: IOException) {
hasErrors = true
}
}
override fun flush() {
try {
out.flush()
} catch (e: IOException) {
hasErrors = true
}
}
}
}
inner class Entry constructor(val key: String) {
/** Lengths of this entry's files. */
val lengths: LongArray = LongArray(valueCount)
/** True if this entry has ever been published. */
var readable = false
/** The ongoing edit or null if this entry is not being edited. */
var currentEditor: Editor? = null
/** The sequence number of the most recently committed edit to this entry. */
var sequenceNumber: Long = 0
@Throws(IOException::class)
fun getLengths(): String {
val result = StringBuilder()
for (size in lengths) {
result.append(' ').append(size)
}
return result.toString()
}
/** Set lengths using decimal numbers like "10123". */
@Throws(IOException::class)
fun setLengths(strings: Array<String>) {
if (strings.size != valueCount) {
throw DiskLruCacheException(
ErrorCode.UNEXPECTED_JOURNAL_LINE,
"unexpected journal line: " + strings.contentToString()
)
}
try {
for (i in strings.indices) {
lengths[i] = strings[i].toLong()
}
} catch (e: NumberFormatException) {
throw DiskLruCacheException(
ErrorCode.UNEXPECTED_JOURNAL_LINE,
"unexpected journal line: " + strings.contentToString()
)
}
}
fun getCleanFile(i: Int): File {
return File(directory, "$key.$i")
}
fun getDirtyFile(i: Int): File {
return File(directory, "$key.$i.tmp")
}
}
companion object {
const val JOURNAL_FILE = "journal"
const val JOURNAL_FILE_TEMP = "journal.tmp"
const val JOURNAL_FILE_BACKUP = "journal.bkp"
const val MAGIC = "libcore.io.DiskLruCache"
const val VERSION_1 = "1"
const val ANY_SEQUENCE_NUMBER: Long = -1
val STRING_KEY_PATTERN: Pattern = Pattern.compile("[a-z0-9_-]{1,120}")
@VisibleForTesting
internal const val CLEAN = "CLEAN"
@VisibleForTesting
internal const val DIRTY = "DIRTY"
@VisibleForTesting
internal const val REMOVE = "REMOVE"
@VisibleForTesting
internal const val READ = "READ"
/**
* Opens the cache in `directory`, creating a cache if none exists
* there.
*
* @param directory a writable directory
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
* @throws IOException if reading or writing the cache directory fails
*/
@Throws(IOException::class)
fun open(directory: File, appVersion: Int, valueCount: Int, maxSize: Long): DiskLruCache {
require(maxSize > 0) { "maxSize <= 0" }
require(valueCount > 0) { "valueCount <= 0" }
// If a bkp file exists, use it instead.
val backupFile = File(directory, JOURNAL_FILE_BACKUP)
if (backupFile.exists()) {
val journalFile = File(directory, JOURNAL_FILE)
// If journal file also exists just delete backup file.
if (journalFile.exists()) {
backupFile.delete()
} else {
renameTo(backupFile, journalFile, false)
}
}
// Prefer to pick up where we left off.
var cache = DiskLruCache(
directory,
appVersion,
valueCount,
maxSize
)
if (cache.journalFile.exists()) {
try {
cache.readJournal()
cache.processJournal()
cache.journalWriter =
OutputStreamWriter(FileOutputStream(cache.journalFile, true), US_ASCII)
return cache
} catch (journalIsCorrupt: DiskLruCacheException) {
println("DiskLruCache $directory is corrupt: $journalIsCorrupt, removing")
cache.delete()
} catch (journalIsCorrupt: IOException) {
println("DiskLruCache $directory is corrupt: $journalIsCorrupt, removing")
cache.delete()
}
}
// Create a new empty cache.
directory.mkdirs()
cache = DiskLruCache(
directory,
appVersion,
valueCount,
maxSize
)
cache.rebuildJournal()
return cache
}
@Throws(IOException::class)
private fun deleteIfExists(file: File) {
if (file.exists() && !file.delete()) {
throw DiskLruCacheException(
ErrorCode.DELETE_FILE_FAILED,
"existing file could not be deleted"
)
}
}
@Throws(IOException::class)
private fun renameTo(from: File, to: File, deleteDestination: Boolean) {
if (deleteDestination) {
deleteIfExists(to)
}
if (!from.renameTo(to)) {
throw DiskLruCacheException(
ErrorCode.RENAME_FILE_FAILED,
"existing file could not be deleted"
)
}
}
@Throws(IOException::class)
private fun inputStreamToString(inputStream: InputStream): String =
readFully(InputStreamReader(inputStream, UTF_8))
private val NULL_OUTPUT_STREAM: OutputStream = object : OutputStream() {
@Throws(IOException::class)
override fun write(b: Int) {
// Eat all writes silently. Nom nom.
}
}
}
} | 1 | Kotlin | 2 | 5 | 2b5162b3e687d81546d9c7ce7a666b3a2b6df889 | 32,545 | ynetwork-android | Apache License 2.0 |
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/localWhitelist/LocalWhitelistGroupConfiguration.kt | putitforward | 251,632,199 | true | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.actions.localWhitelist
import com.google.gson.JsonSyntaxException
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.actions.TestParseEventLogWhitelistDialog
import com.intellij.internal.statistic.eventLog.FeatureUsageData.Companion.platformDataKeys
import com.intellij.internal.statistic.eventLog.validator.persistence.EventLogTestWhitelistPersistence
import com.intellij.internal.statistic.eventLog.validator.rules.beans.WhiteListGroupContextData
import com.intellij.internal.statistic.eventLog.validator.rules.utils.WhiteListSimpleRuleFactory
import com.intellij.internal.statistic.eventLog.whitelist.LocalWhitelistGroup
import com.intellij.internal.statistic.service.fus.FUStatisticsWhiteListGroupsService
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.layout.*
import com.intellij.util.IncorrectOperationException
import com.intellij.util.TextFieldCompletionProviderDumbAware
import com.intellij.util.ThrowableRunnable
import com.intellij.util.textCompletion.TextFieldWithCompletion
import com.intellij.util.ui.JBUI
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class LocalWhitelistGroupConfiguration(private val project: Project,
private val productionGroups: FUStatisticsWhiteListGroupsService.WLGroups,
initialGroup: LocalWhitelistGroup,
groupIdChangeListener: ((LocalWhitelistGroup) -> Unit)? = null) : Disposable {
val panel: JPanel
val groupIdTextField: TextFieldWithCompletion
private val log = logger<LocalWhitelistGroupConfiguration>()
private var currentGroup: LocalWhitelistGroup = initialGroup
private val addCustomRuleCheckBox: JBCheckBox = JBCheckBox(StatisticsBundle.message("stats.use.custom.validation.rules"),
initialGroup.useCustomRules)
private val validationRulesEditorComponent: JComponent
private val validationRulesDescription: JLabel
private val tempFile: PsiFile
private val validationRulesEditor: EditorEx
init {
val completionProvider = object : TextFieldCompletionProviderDumbAware() {
override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) {
result.addAllElements(productionGroups.groups.mapNotNull { it.id }.map(LookupElementBuilder::create))
}
}
groupIdTextField = TextFieldWithCompletion(project, completionProvider, initialGroup.groupId, true, true, false)
tempFile = TestParseEventLogWhitelistDialog.createTempFile(project, "event-log-validation-rules", currentGroup.customRules)!!
validationRulesEditor = createEditor(project, tempFile)
validationRulesEditor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) {
currentGroup.customRules = validationRulesEditor.document.text
}
})
validationRulesEditorComponent = validationRulesEditor.component
validationRulesEditorComponent.minimumSize = JBUI.size(200, 100)
groupIdTextField.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) {
currentGroup.groupId = groupIdTextField.text
if (groupIdChangeListener != null) {
groupIdChangeListener(currentGroup)
}
}
})
addCustomRuleCheckBox.addChangeListener { updateRulesOption() }
validationRulesDescription = ComponentPanelBuilder.createCommentComponent(
StatisticsBundle.message("stats.validation.rules.format"), true)
panel = panel {
row {
cell {
label(StatisticsBundle.message("stats.group.id"))
groupIdTextField(growX)
}
}
row {
cell {
addCustomRuleCheckBox()
ContextHelpLabel.create(StatisticsBundle.message("stats.local.whitelist.custom.rules.help"))()
}
}
row {
validationRulesEditorComponent(growX)
}
row {
validationRulesDescription()
}
}
.withBorder(JBUI.Borders.empty(2))
updateRulesOption()
}
private fun createEditor(project: Project, file: PsiFile): EditorEx {
var document = PsiDocumentManager.getInstance(project).getDocument(file)
if (document == null) {
document = EditorFactory.getInstance().createDocument(currentGroup.customRules)
}
val editor = EditorFactory.getInstance().createEditor(document, project, file.virtualFile, false) as EditorEx
editor.setFile(file.virtualFile)
editor.settings.isLineMarkerAreaShown = false
editor.settings.isFoldingOutlineShown = false
val fileType = FileTypeManager.getInstance().findFileTypeByName("JSON")
val lightFile = LightVirtualFile("Dummy.json", fileType, "")
val highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, lightFile)
try {
editor.highlighter = highlighter
}
catch (e: Throwable) {
log.warn(e)
}
return editor
}
fun updatePanel(newGroup: LocalWhitelistGroup?) {
if (newGroup == null) return
currentGroup = newGroup
groupIdTextField.text = newGroup.groupId
groupIdTextField.requestFocusInWindow()
addCustomRuleCheckBox.isSelected = newGroup.useCustomRules
WriteAction.run<Throwable> { validationRulesEditor.document.setText(newGroup.customRules) }
}
private fun updateRulesOption() {
val useCustomRules = addCustomRuleCheckBox.isSelected
validationRulesEditorComponent.isVisible = useCustomRules
validationRulesDescription.isVisible = useCustomRules
currentGroup.useCustomRules = useCustomRules
}
fun getFocusedComponent(): JComponent = groupIdTextField
override fun dispose() {
WriteCommandAction.writeCommandAction(project).run(
ThrowableRunnable<RuntimeException> {
try {
tempFile.delete()
}
catch (e: IncorrectOperationException) {
log.warn(e)
}
})
if (!validationRulesEditor.isDisposed) {
EditorFactory.getInstance().releaseEditor(validationRulesEditor)
}
}
fun validate(): List<ValidationInfo> {
return validateWhitelistGroup(currentGroup, productionGroups.rules, groupIdTextField)
}
companion object {
fun validateWhitelistGroup(localWhitelistGroup: LocalWhitelistGroup,
productionRules: FUStatisticsWhiteListGroupsService.WLRule?,
groupIdTextField: JComponent): List<ValidationInfo> {
val groupId: String = localWhitelistGroup.groupId
val validationInfo = mutableListOf<ValidationInfo>()
if (groupId.isEmpty()) {
validationInfo.add(ValidationInfo(StatisticsBundle.message("stats.specify.group.id"), groupIdTextField))
}
if (localWhitelistGroup.useCustomRules) {
validationInfo.addAll(validateEventData(groupId, localWhitelistGroup.customRules, productionRules))
}
return validationInfo
}
internal fun validateEventData(groupId: String,
customRules: String,
productionRules: FUStatisticsWhiteListGroupsService.WLRule?): List<ValidationInfo> {
val rules = parseRules(groupId, customRules)
?: return listOf(ValidationInfo(StatisticsBundle.message("stats.unable.to.parse.validation.rules")))
val eventData = rules.event_data
if (eventData == null || productionRules == null) return emptyList()
val contextData = WhiteListGroupContextData.create(rules.enums, productionRules.enums, rules.regexps,
productionRules.regexps)
val validationInfo = ArrayList<ValidationInfo>()
val eventIds = rules.event_id
if (eventIds != null) {
for (eventId in eventIds) {
val eventRule = WhiteListSimpleRuleFactory.createRule(eventId!!, contextData)
if (!eventRule.isValidRule) {
validationInfo.add(ValidationInfo(StatisticsBundle.message("stats.unable.to.parse.event.id.0", eventId)))
}
}
}
for ((key, value) in eventData) {
if (platformDataKeys.contains(key)) continue
for (rule in value) {
val fusRule = WhiteListSimpleRuleFactory.createRule(rule!!, contextData)
if (!fusRule.isValidRule) {
validationInfo.add(ValidationInfo(StatisticsBundle.message("stats.unable.to.parse.validation.rule.0", rule)))
}
}
}
return validationInfo
}
private fun parseRules(groupId: String, customRules: String): FUStatisticsWhiteListGroupsService.WLRule? {
val whitelistRules: FUStatisticsWhiteListGroupsService.WLGroup = try {
EventLogTestWhitelistPersistence.createGroupWithCustomRules(groupId, customRules)
}
catch (e: JsonSyntaxException) {
return null
}
return whitelistRules.rules
}
}
}
| 12 | null | 0 | 0 | 6e3b1a7052017d17d1d33c24cdb2bdf1ce0248a1 | 10,186 | intellij-community | Apache License 2.0 |
src/main/kotlin/net/rentalhost/plugins/php/hammer/inspections/codeSmell/SenselessArrayUnpackingInspection.kt | hammer-tools | 509,864,102 | false | {"Kotlin": 295432, "PHP": 235029, "HTML": 21942, "Java": 1887} | package net.rentalhost.plugins.php.hammer.inspections.codeSmell
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.refactoring.suggested.createSmartPointer
import com.jetbrains.php.config.PhpLanguageLevel
import com.jetbrains.php.lang.inspections.PhpInspection
import com.jetbrains.php.lang.psi.elements.ArrayCreationExpression
import com.jetbrains.php.lang.psi.elements.PhpTypedElement
import com.jetbrains.php.lang.psi.elements.impl.ArrayCreationExpressionImpl
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor
import net.rentalhost.plugins.php.hammer.extensions.psi.hasInterface
import net.rentalhost.plugins.php.hammer.extensions.psi.isVariadicPreceded
import net.rentalhost.plugins.php.hammer.services.ClassService
import net.rentalhost.plugins.php.hammer.services.ProblemsHolderService
import net.rentalhost.plugins.php.hammer.services.QuickFixService
class SenselessArrayUnpackingInspection : PhpInspection() {
override fun buildVisitor(problemsHolder: ProblemsHolder, isOnTheFly: Boolean): PhpElementVisitor = object : PhpElementVisitor() {
override fun visitPhpArrayCreationExpression(expression: ArrayCreationExpression) {
val expressionElements = (expression as ArrayCreationExpressionImpl).values().toList()
if (expressionElements.size != 1)
return
val expressionElement = expressionElements.first()
if (expressionElement !is PhpTypedElement ||
expressionElement is ArrayCreationExpression ||
!expressionElement.isVariadicPreceded())
return
val expressionType = expressionElement.globalType
expressionType.types.forEach {
if (PhpType.isArray(it) ||
PhpType.isPluralType(it))
return@forEach
if (it.equals("\\Generator") || !it.startsWith("\\"))
return
val expressionClass = ClassService.findFQN(it, expression.project) ?: return
if (!expressionClass.hasInterface("\\Traversable"))
return
}
val expressionElementPointer = expressionElement.createSmartPointer()
ProblemsHolderService.instance.registerProblem(
problemsHolder,
expression,
"unnecessary array unpacking",
QuickFixService.instance.simpleReplace("Replace with own variable", expressionElementPointer)
)
}
}
override fun getMinimumSupportedLanguageLevel(): PhpLanguageLevel = PhpLanguageLevel.PHP740
}
| 5 | Kotlin | 0 | 56 | e6a4aac518dc8f306fd2171a0355f15a0547e52f | 2,481 | php-hammer | Apache License 2.0 |
src/test/kotlin/SpielTest.kt | zeitlinger | 194,141,884 | false | null | @file:Suppress("NonAsciiCharacters")
import io.kotest.core.datatest.forAll
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.doubles.shouldBeGreaterThan
import io.kotest.matchers.doubles.shouldBeLessThan
import io.kotest.matchers.shouldBe
import javafx.scene.paint.Color
import kotlin.math.sqrt
class SpielTest : FreeSpec({
val sanitäter = EinheitenTyp(
name = "Sanitäter",
reichweite = 40.01,
leben = 80.0,
schaden = 12.0,
laufweite = 0.7,
kristalle = 1100,
kuerzel = "SAN",
panzerung = 0.0,
kannAngreifen = KannAngreifen.heilen,
gebäudeTyp = kaserne,
techGebäude = weltraumAkademie,
hotkey = "s",
einheitenArt = EinheitenArt.biologisch,
zivileEinheit = true,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
val infantrie = EinheitenTyp(
name = "Infantrie",
reichweite = 150.0,
leben = 100.0,
schaden = 7.0,
laufweite = 0.5,
kristalle = 500,
kuerzel = "INF",
panzerung = 1.0,
kannAngreifen = KannAngreifen.alles,
gebäudeTyp = kaserne,
hotkey = "q",
einheitenArt = EinheitenArt.biologisch,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
val berserker = EinheitenTyp(
name = "Berserker",
reichweite = 40.01,
leben = 200.0,
schaden = 25.0,
laufweite = 0.5,
kristalle = 1000,
kuerzel = "BER",
panzerung = 2.0,
kannAngreifen = KannAngreifen.boden,
gebäudeTyp = kaserne,
techGebäude = schmiede,
hotkey = "e",
einheitenArt = EinheitenArt.biologisch,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
val panzer = EinheitenTyp(
name = "Panzer",
reichweite = 350.0,
leben = 1000.0,
schaden = 30.0,
laufweite = 4.0,
kristalle = 2500,
kuerzel = "PAN",
panzerung = 0.4,
kannAngreifen = KannAngreifen.boden,
gebäudeTyp = fabrik,
techGebäude = reaktor,
hotkey = "t",
einheitenArt = EinheitenArt.mechanisch,
flächenschaden = 25.0,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
val jäger = EinheitenTyp(
name = "Jäger",
reichweite = 120.0,
leben = 80.0,
schaden = 20.0,
laufweite = 0.8,
kristalle = 1800,
kuerzel = "JÄG",
panzerung = 2.0,
kannAngreifen = KannAngreifen.alles,
luftBoden = LuftBoden.luft,
gebäudeTyp = raumhafen,
hotkey = "a",
einheitenArt = EinheitenArt.mechanisch,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
val arbeiter = EinheitenTyp(
name = "Arbeiter",
reichweite = 0.0,
leben = 80.0,
schaden = 0.0,
laufweite = 0.7,
kristalle = 1000,
kuerzel = "ARB",
panzerung = 0.0,
kannAngreifen = KannAngreifen.alles,
gebäudeTyp = null,
hotkey = "f",
einheitenArt = EinheitenArt.biologisch,
zivileEinheit = true,
durchschlag = 0.0,
firstShotDelay = 0.0,
)
"Heiler soll automatisch heilen und Zustände entfernen" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
leben = 10.0
zuletztGetroffen = 2.0
verlangsamt = 2.0
}
neueEinheit(x = 20.0, y = 0.0, einheitenTyp = sanitäter)
upgrades.vertärkteHeilmittel = true
}
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBe 22.0
spiel.mensch.einheiten[1].verlangsamt shouldBe 0.0
}
"Heiler soll nur heilen wenn die Einheit nicht angegriffen wird" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
leben = 10.0
zuletztGetroffen = 1.0
}
neueEinheit(x = 20.0, y = 0.0, einheitenTyp = sanitäter)
}
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBe 10.0
}
"Einheit soll nur von einen Heiler geheilt werden" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
leben = 10.0
zuletztGetroffen = 2.0
}
neueEinheit(x = 20.0, y = 0.0, einheitenTyp = sanitäter)
neueEinheit(x = 20.0, y = 0.0, einheitenTyp = sanitäter)
}
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBe 22.0
}
"nur ein Heiler geht zum Ziel" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
leben = 10.0
zuletztGetroffen = 2.0
}
neueEinheit(x = 200.0, y = 0.0, einheitenTyp = sanitäter)
neueEinheit(x = 200.0, y = 0.0, einheitenTyp = sanitäter)
}
spielen(spiel)
spiel.mensch.einheiten[2].punkt.x shouldBe 199.3
spiel.mensch.einheiten[3].punkt.x shouldBe 200.0
}
"beschützen" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
neueEinheit(x = 300.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
}
spielen(spiel)
spiel.mensch.einheiten[2].punkt shouldBe Punkt(x = 299.55278640450007, y = 0.22360679774997896)
}
"hold Position" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(
x = 200.0,
y = 0.0,
einheitenTyp = infantrie
).apply { kommandoQueue.add(HoldPosition()) }
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt shouldBe Punkt(x = 200.0, y = 0.0)
}
"Einheiten in Reichweite angreifen" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie).apply {
letzterAngriff = spiel.mensch.einheiten[1]
}
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBeLessThan 100.0
spiel.gegner.einheiten[1].leben shouldBeLessThan 100.0
}
"Heilungsmodifikator" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie).apply {
wirdGeheilt = 2
letzterAngriff = spiel.mensch.einheiten[1]
}
upgrades.strahlungsheilung = true
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBeGreaterThan spiel.mensch.einheiten[1].leben
}
"vergiftung" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply { vergiftet = 1.0 }
}
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBe 95.0
}
"verlangsamerung" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
verlangsamt = 1.0
kommandoQueue.add(Bewegen(Punkt(x = 0.5, y = 0.0)))
}
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt.x shouldBe 0.25
}
"Nicht in einer Runde laufen und angreifen" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 150.5, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
}
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBe 100.0
}
"Schusscooldown" {
val spiel = neuesSpiel()
spiel.mensch.apply {
einheitenTypen.getValue(infantrie.name).schusscooldown = 0.03
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie).apply {
letzterAngriff = spiel.mensch.einheiten[1]
}
}
val ziel = spiel.gegner.einheiten[1]
spiel.mensch.einheiten[1].letzterAngriff = ziel
spielen(spiel)
ziel.leben shouldBeLessThan 100.0
val l = ziel.leben
spielen(spiel)
ziel.leben shouldBe l
spielen(spiel)
ziel.leben shouldBeLessThan l
}
"Flächenschaden" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = panzer)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
neueEinheit(x = 25.0, y = 150.0, einheitenTyp = infantrie)
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBeLessThan 100.0
spiel.gegner.einheiten[2].leben shouldBeLessThan 100.0
}
"schadensupgrade" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
upgrades.schadensUpgrade = 1
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBeLessThan spiel.mensch.einheiten[1].leben
}
"panzerugsupgrade" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
upgrades.panzerungsUprade = 1
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBeGreaterThan spiel.mensch.einheiten[1].leben
}
"einheit stirbt" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie).apply { leben = 0.1 }
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 0.0,
einheitenTyp = infantrie
).apply { kommandoQueue.add(Angriff(spiel.gegner.einheiten[1])) }
}
spielen(spiel)
spiel.gegner.einheiten.size shouldBe 1
spiel.mensch.einheiten[0].kommandoQueue.size shouldBe 0
}
"zum Zielpunkt laufen" - {
data class TestFall(val start: Punkt, val ziel: Punkt)
forAll(
TestFall(
start = Punkt(x = 1000.0, y = 0.0),
ziel = Punkt(x = 999.6464466094068, y = 0.35355339059327373)
),
TestFall(start = Punkt(x = 0.0, y = 1000.0), ziel = Punkt(x = 0.0, y = 1000.0)),
TestFall(start = Punkt(x = 0.0, y = 999.0), ziel = Punkt(x = 0.0, y = 999.5)),
TestFall(start = Punkt(x = 0.0, y = 999.999), ziel = Punkt(x = 0.0, y = 1000.0))
) { testFall ->
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(
x = testFall.start.x,
y = testFall.start.y,
einheitenTyp = infantrie
).apply { kommandoQueue.add(Bewegen(Punkt(0.0, 1000.0))) }
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt shouldBe testFall.ziel
}
}
"attackmove laufen" - {
data class TestFall(val start: Punkt, val ziel: Punkt)
forAll(
TestFall(start = Punkt(x = 1000.0, y = 0.0), ziel = Punkt(x = 999.6464466094068, y = 0.35355339059327373)),
TestFall(start = Punkt(x = 0.0, y = 1000.0), ziel = Punkt(x = 0.0, y = 1000.0)),
TestFall(start = Punkt(x = 0.0, y = 999.0), ziel = Punkt(x = 0.0, y = 999.5)),
TestFall(start = Punkt(x = 0.0, y = 999.999), ziel = Punkt(x = 0.0, y = 1000.0))
) { testFall ->
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = testFall.start.x, y = testFall.start.y, einheitenTyp = infantrie).apply {
kommandoQueue.add(Attackmove(Punkt(0.0, 1000.0)))
}
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt shouldBe testFall.ziel
}
}
"attackmove angreifen" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
kommandoQueue.add(Attackmove(Punkt(0.0, 1000.0)))
}
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.mensch.einheiten[1].punkt shouldBe Punkt(x = 0.0, y = 0.0)
spiel.gegner.einheiten[1].leben shouldBeLessThan 100.0
}
"computer greift nächste einheit an" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 200.0, einheitenTyp = infantrie)
}
spielen(spiel)
spiel.gegner.einheiten[1].punkt shouldBe Punkt(x = 0.0, y = 199.5)
}
"springen" - {
data class TestFall(
val start: Double,
val ziel: Double,
val leben: Double,
val `alter cooldown`: Double,
val `neuer cooldown`: Double
)
forAll(
TestFall(start = 140.0, ziel = 40.0, leben = 25.0, `alter cooldown` = 0.0, `neuer cooldown` = 9.985),
TestFall(start = 141.0, ziel = 140.5, leben = 100.0, `alter cooldown` = 0.0, `neuer cooldown` = 0.0),
TestFall(start = 139.0, ziel = 40.0, leben = 25.0, `alter cooldown` = 0.0, `neuer cooldown` = 9.985),
TestFall(start = 140.0, ziel = 139.5, leben = 100.0, `alter cooldown` = 34.0, `neuer cooldown` = 33.985)
) { testFall ->
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie)
}
spiel.mensch.apply {
neueEinheit(x = 0.0, y = testFall.start, einheitenTyp = berserker).apply {
typ.springen = 100
`springen cooldown` = testFall.`alter cooldown`
}
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt shouldBe Punkt(x = 0.0, y = testFall.ziel)
spiel.gegner.einheiten[1].leben shouldBe testFall.leben
spiel.mensch.einheiten[1].`springen cooldown` shouldBe testFall.`neuer cooldown`
}
}
"zu ziel laufen" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 150.0, einheitenTyp = infantrie)
neueEinheit(x = 0.0, y = 1334.0, einheitenTyp = infantrie)
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 500.0,
einheitenTyp = infantrie
).apply { kommandoQueue.add(Angriff(spiel.gegner.einheiten[2])) }
}
spielen(spiel)
spiel.gegner.einheiten[1].leben shouldBe 100.0
spiel.mensch.einheiten[1].punkt shouldBe Punkt(x = 0.0, y = 500.5)
}
"kommando entfernen (bewegen)" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply {
kommandoQueue.add(
Bewegen(
Punkt(
0.0,
0.5
)
)
)
}
}
spielen(spiel)
spiel.mensch.einheiten[1].kommandoQueue.size shouldBe 0
}
"kommando entfernen (attackmove)" {
val spiel = neuesSpiel()
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 0.0,
einheitenTyp = infantrie
).apply { kommandoQueue.add(Attackmove(Punkt(0.0, 0.5))) }
}
spielen(spiel)
spiel.mensch.einheiten[1].kommandoQueue.size shouldBe 0
}
"kommando entfernen (angreifen)" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = infantrie).apply { leben = 0.1 }
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 0.0,
einheitenTyp = infantrie
).apply { kommandoQueue.add(Angriff(spiel.gegner.einheiten[1])) }
}
spielen(spiel)
spiel.mensch.einheiten[1].kommandoQueue.size shouldBe 0
}
"ziel angreifen" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 510.0, einheitenTyp = infantrie)
neueEinheit(x = 0.0, y = 520.0, einheitenTyp = infantrie)
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 500.0,
einheitenTyp = infantrie
).apply {
kommandoQueue.add(Angriff(spiel.gegner.einheiten[2]))
}
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten[2].leben shouldBeLessThan 100.0
}
"höchste Priorität die in reichweite ist angreifen" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 510.0, einheitenTyp = arbeiter)
neueEinheit(x = 0.0, y = 520.0, einheitenTyp = berserker)
neueEinheit(x = 0.0, y = 530.0, einheitenTyp = berserker)
neueEinheit(x = 0.0, y = 660.0, einheitenTyp = infantrie)
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 500.0,
einheitenTyp = jäger
)
}
spiel.mensch.einheiten[1].letzterAngriff = spiel.gegner.einheiten[1]
spielen(spiel)
spiel.gegner.einheiten.map { it.leben } shouldBe listOf(3000.0, 80.0, 182.0, 200.0, 100.0)
}
"gebäudeBauenKI" {
val spiel = neuesSpiel()
spiel.gegner.apply { kristalle = 1500.0 }
spielen(spiel)
spiel.gegner.gebäude.values.single().typ shouldBe fabrik
}
"zu Einheit mit höchster Priorität laufen" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 510.0, einheitenTyp = arbeiter)
neueEinheit(x = 0.0, y = 660.0, einheitenTyp = panzer)
}
spiel.mensch.apply {
neueEinheit(
x = 0.0,
y = 500.0,
einheitenTyp = infantrie
)
}
spielen(spiel)
spiel.mensch.einheiten[1].punkt.y shouldBe 500.5
}
"kann Lufteinheit nicht angreifen" {
val spiel = neuesSpiel()
spiel.gegner.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = panzer)
}
spiel.mensch.apply {
neueEinheit(x = 0.0, y = 0.0, einheitenTyp = jäger)
}
spielen(spiel)
spiel.mensch.einheiten[1].leben shouldBe 80.0
}
"gegenüberliegenden punkt finden" - {
data class TestFall(val einheit: Punkt, val gegner: Punkt, val entfernung: Double, val ergebnis: Punkt)
forAll(
TestFall(
einheit = Punkt(x = 0.0, y = 0.0), gegner = Punkt(x = 1.0, y = 1.0),
entfernung = sqrt(2.0), ergebnis = Punkt(-1.0, -1.0)
),
TestFall(
einheit = Punkt(x = 1.0, y = 1.0), gegner = Punkt(x = 0.0, y = 0.0),
entfernung = sqrt(2.0), ergebnis = Punkt(2.0, 2.0)
),
TestFall(
einheit = Punkt(x = 1.0, y = 1.0), gegner = Punkt(x = 0.0, y = 0.0),
entfernung = 2 * sqrt(2.0), ergebnis = Punkt(3.0, 3.0)
),
) { testFall ->
gegenüberliegendenPunktFinden(
testFall.einheit,
testFall.gegner,
testFall.entfernung
) shouldBe testFall.ergebnis
}
}
"Einheiten Mittelpunkt finden" - {
data class TestFall(val einheiten: List<Punkt>, val ergebnis: Punkt)
forAll(
TestFall(
einheiten = listOf(Punkt(0.0, 0.0), Punkt(2.0, 2.0), Punkt(2.0, 0.0)),
ergebnis = Punkt(4.0 / 3.0, 2.0 / 3.0),
),
) { testFall ->
val spiel = neuesSpiel()
val einheiten = spiel.gegner.run {
testFall.einheiten.map { neueEinheit(it, einheitenTyp = panzer) }
}
einheitenMittelpunkt(einheiten) shouldBe testFall.ergebnis
}
}
})
private fun spielen(spiel: Spiel) {
spiel.runde()
}
private fun neuesSpiel(): Spiel {
val computer = Spieler(
kristalle = 0.0,
minen = 0,
startpunkt = Punkt(x = 900.0, y = 115.0),
farbe = Color.RED,
spielerTyp = SpielerTyp.computer,
upgrades = SpielerUpgrades(
angriffspunkte = 20,
verteidiegungspunkte = 10,
schadensUpgrade = 0,
panzerungsUprade = 0
)
).apply {
neueEinheit(x = 900.0, y = 970.0, einheitenTyp = gebäudeEinheitenTyp(basis))
}
val mensch = Spieler(
kristalle = 0.0,
minen = 0,
startpunkt = Punkt(x = 900.0, y = 905.0),
farbe = Color.BLUE,
spielerTyp = SpielerTyp.mensch,
upgrades = SpielerUpgrades(
angriffspunkte = 20,
verteidiegungspunkte = 10,
schadensUpgrade = 0,
panzerungsUprade = 0
)
).apply {
neueEinheit(x = 900.0, y = 970.0, einheitenTyp = gebäudeEinheitenTyp(basis))
}
return Spiel(mensch, computer, rundenLimit = 1, multiplayer = Multiplayer(null, null))
}
| 0 | Kotlin | 0 | 0 | aa02a9d4f882e00c2a62dba6eaed9a543df90d8b | 24,019 | starcraft-III | MIT License |
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/mongo/CollationOptions.kt | yeikel | 471,845,103 | true | {"Kotlin": 1466595, "Java": 28771} | /*
* Copyright 2019 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.kotlin.ext.mongo
import io.vertx.ext.mongo.CollationOptions
import com.mongodb.client.model.CollationStrength
/**
* A function providing a DSL for building [io.vertx.ext.mongo.CollationOptions] objects.
*
* Options used to configure collation options.
*
* @param backwards Optional. Flag that determines whether strings with diacritics sort from back of the string, such as with some French dictionary ordering. <p> If true, compare from back to front. If false, compare from front to back. <p> The default value is false.
* @param caseLevel Optional. Flag that determines whether to include case comparison at strength level 1 or 2. <p> If true, include case comparison; i.e. <p> When used with strength:1, collation compares base characters and case. When used with strength:2, collation compares base characters, diacritics (and possible other secondary differences) and case. If false, do not include case comparison at level 1 or 2. The default is false.
* @param locale The ICU locale. See <a href="https://docs.mongodb.com/manual/reference/collation-locales-defaults/#std-label-collation-languages-locales">Supported Languages and Locales</a> for a list of supported locales. <p> The default value is <code>simple</code> which specifies simple binary comparison.
* @param normalization Optional. Flag that determines whether to check if text require normalization and to perform normalization. Generally, majority of text does not require this normalization processing. <p> If true, check if fully normalized and perform normalization to compare text. If false, does not check. <p> The default value is false.
* @param numericOrdering Optional. Flag that determines whether to compare numeric strings as numbers or as strings. <p> If true, compare as numbers; i.e. "10" is greater than "2". If false, compare as strings; i.e. "10" is less than "2". <p> Default is false.
* @param strength Optional. The level of comparison to perform. Corresponds to ICU Comparison Levels. Possible values are: <p> Value Description 1 Primary level of comparison. Collation performs comparisons of the base characters only, ignoring other differences such as diacritics and case. 2 Secondary level of comparison. Collation performs comparisons up to secondary differences, such as diacritics. That is, collation performs comparisons of base characters (primary differences) and diacritics (secondary differences). Differences between base characters takes precedence over secondary differences. 3 Tertiary level of comparison. Collation performs comparisons up to tertiary differences, such as case and letter variants. That is, collation performs comparisons of base characters (primary differences), diacritics (secondary differences), and case and variants (tertiary differences). Differences between base characters takes precedence over secondary differences, which takes precedence over tertiary differences. This is the default level. <p> 4 Quaternary Level. Limited for specific use case to consider punctuation when levels 1-3 ignore punctuation or for processing Japanese text. 5 Identical Level. Limited for specific use case of tie breaker.
*
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.mongo.CollationOptions original] using Vert.x codegen.
*/
fun collationOptionsOf(
backwards: Boolean? = null,
caseLevel: Boolean? = null,
locale: String? = null,
normalization: Boolean? = null,
numericOrdering: Boolean? = null,
strength: CollationStrength? = null): CollationOptions = io.vertx.ext.mongo.CollationOptions().apply {
if (backwards != null) {
this.setBackwards(backwards)
}
if (caseLevel != null) {
this.setCaseLevel(caseLevel)
}
if (locale != null) {
this.setLocale(locale)
}
if (normalization != null) {
this.setNormalization(normalization)
}
if (numericOrdering != null) {
this.setNumericOrdering(numericOrdering)
}
if (strength != null) {
this.setStrength(strength)
}
}
| 0 | null | 0 | 0 | e405f03fbf31144a9707eb2e07ad87fb08816e3b | 4,535 | vertx-lang-kotlin | Apache License 2.0 |
app/src/main/java/cn/sskbskdrin/record/opengl/GLView.kt | sskbskdrin | 179,249,401 | false | {"C++": 3560091, "Java": 257858, "Kotlin": 50162, "C": 38126, "CMake": 4860} | package cn.sskbskdrin.record.opengl
import android.content.Context
import android.opengl.GLSurfaceView
import android.util.AttributeSet
import android.util.Log
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class GLView : GLSurfaceView, GLSurfaceView.Renderer {
private val TAG = "GLView"
var render: Renderer? = null
constructor(context: Context?) : this(context, null)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
setRenderer(this)
renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
Log.d(TAG, "onSurfaceCreated:")
gl!!
gl.glClear(GL10.GL_COLOR_BUFFER_BIT)
// Set the background color to black ( rgba ).
gl.glClearColor(0f, 0f, 0f, 1.0f)
// Enable Smooth Shading, default not really needed.
gl.glShadeModel(GL10.GL_SMOOTH)
// Depth buffer setup.
gl.glClearDepthf(1.0f)
// Enables depth testing.
gl.glEnable(GL10.GL_DEPTH_TEST)
// The type of depth testing to do.
gl.glDepthFunc(GL10.GL_LEQUAL)
// Really nice perspective calculations.
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST)
render?.onSurfaceCreated(gl, config)
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
gl?.glViewport(0, 0, width, height)
render?.onSurfaceChanged(gl, width, height)
}
override fun onDrawFrame(gl: GL10?) {
gl!!
gl.glClear(GL10.GL_COLOR_BUFFER_BIT or GL10.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
render?.onDrawFrame(gl)
}
} | 0 | C++ | 1 | 0 | 612219433faeec74a36c08c9f8f61d3e4078da20 | 1,738 | AudioVideo | Apache License 2.0 |
core/src/main/java/com/prodev/muslimq/core/data/repository/DoaRepo.kt | dapoi | 522,927,477 | false | {"Kotlin": 326223} | package com.prodev.muslimq.core.data.repository
import com.prodev.muslimq.core.data.source.local.model.DoaEntity
import com.prodev.muslimq.core.utils.JsonHelper
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DoaRepositoryImpl @Inject constructor(
private val jsonHelper: JsonHelper
) : DoaRepository {
override fun getDoa(): Flow<List<DoaEntity>> = flow {
emit(jsonHelper.getDoa())
}
}
interface DoaRepository {
fun getDoa(): Flow<List<DoaEntity>>
} | 1 | Kotlin | 5 | 27 | 2a516b4adf9bcfe6faf3c4eb0a213f2fb1576724 | 577 | Muslim-Q | MIT License |
app/src/main/kotlin/com/muedsa/compose/tv/widget/player/PlayerControl.kt | muedsa | 713,334,832 | false | {"Kotlin": 298439} | package com.muedsa.compose.tv.widget.player
import android.icu.text.SimpleDateFormat
import android.view.KeyEvent
import androidx.annotation.OptIn
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ArrowBack
import androidx.compose.material.icons.outlined.ArrowForward
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.graphics.Color
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.Player
import androidx.media3.common.Tracks
import androidx.media3.common.util.UnstableApi
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Icon
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
import com.muedsa.compose.tv.widget.OutlinedIconBox
import kotlinx.coroutines.delay
import java.util.Date
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit
import kotlin.time.toDuration
@kotlin.OptIn(ExperimentalTvMaterial3Api::class)
@OptIn(UnstableApi::class)
@Composable
fun PlayerControl(
debug: Boolean = false,
player: Player,
state: MutableState<Int> = remember { mutableIntStateOf(0) },
) {
var leftArrowBtnPressed by remember { mutableStateOf(false) }
var rightArrowBtnPressed by remember { mutableStateOf(false) }
var playBtnPressed by remember { mutableStateOf(false) }
var videoInfo by remember { mutableStateOf("") }
LaunchedEffect(key1 = Unit) {
while (true) {
delay(1.seconds)
if (state.value > 0) {
state.value--
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.focusable()
.onPreviewKeyEvent {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_UP
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_DOWN
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_CENTER
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MENU
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MEDIA_PLAY
|| it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
) {
state.value = 5
}
}
if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
leftArrowBtnPressed = true
} else if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
leftArrowBtnPressed = false
player.seekBack()
}
} else if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
rightArrowBtnPressed = true
} else if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
rightArrowBtnPressed = false
player.seekForward()
}
} else if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
playBtnPressed = true
} else if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
playBtnPressed = false
if (player.isPlaying) {
player.pause()
} else {
player.play()
}
}
} else if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
playBtnPressed = true
} else if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
playBtnPressed = false
if (!player.isPlaying) {
player.play()
}
}
} else if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
if (it.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {
playBtnPressed = true
} else if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
playBtnPressed = false
if (player.isPlaying) {
player.pause()
}
}
}
return@onPreviewKeyEvent false
}
) {
AnimatedVisibility(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.75f)),
visible = state.value > 0,
enter = fadeIn(),
exit = fadeOut()
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(40.dp)
) {
Text(
text = "视频信息",
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.titleSmall
)
Text(
text = videoInfo,
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.bodySmall
)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
verticalArrangement = Arrangement.Bottom,
) {
PlayerProgressIndicator(player)
Spacer(modifier = Modifier.height(20.dp))
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.Bottom
) {
OutlinedIconBox(scaleUp = leftArrowBtnPressed) {
Icon(Icons.Outlined.ArrowBack, contentDescription = "后退")
}
Spacer(modifier = Modifier.width(20.dp))
OutlinedIconBox(
scaleUp = playBtnPressed,
inverse = true
) {
if (player.isPlaying) {
Icon(
Icons.Outlined.Pause,
contentDescription = "暂停"
)
} else {
Icon(Icons.Outlined.PlayArrow, contentDescription = "播放")
}
}
Spacer(modifier = Modifier.width(20.dp))
OutlinedIconBox(scaleUp = rightArrowBtnPressed) {
Icon(Icons.Outlined.ArrowForward, contentDescription = "前进")
}
}
if (debug) {
Spacer(modifier = Modifier.height(20.dp))
Text(text = "show: $state", color = Color.Red)
}
}
}
}
LaunchedEffect(key1 = player) {
player.addListener(object : Player.Listener {
override fun onTracksChanged(tracks: Tracks) {
var newVideoInfo = ""
for (trackGroup in tracks.groups) {
if (trackGroup.isSelected) {
var groupInfo = "group [ type=${groupTypeToString(trackGroup)}\n"
for (i in 0 until trackGroup.length) {
val isSelected = trackGroup.isTrackSelected(i)
if (isSelected) {
val trackFormat = trackGroup.getTrackFormat(i)
groupInfo += " Track ${Format.toLogString(trackFormat)}\n"
}
}
groupInfo += "]\n"
newVideoInfo += groupInfo
}
}
videoInfo = newVideoInfo
}
})
}
}
@kotlin.OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun PlayerProgressIndicator(player: Player) {
val dateTimeFormat = remember { SimpleDateFormat.getDateTimeInstance() }
val systemStr = dateTimeFormat.format(Date())
val currentStr = if (player.duration > 0L) {
player.currentPosition.toDuration(DurationUnit.MILLISECONDS)
.toComponents { hours, minutes, seconds, _ ->
String.format(
"%02d:%02d:%02d",
hours,
minutes,
seconds,
)
}
} else {
"--:--:--"
}
val totalStr = if (player.duration > 0L) {
player.duration.toDuration(DurationUnit.MILLISECONDS)
.toComponents { hours, minutes, seconds, _ ->
String.format(
"%02d:%02d:%02d",
hours,
minutes,
seconds,
)
}
} else {
"--:--:--"
}
Column(
modifier = Modifier.fillMaxWidth(),
) {
if (player.duration > 0L) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
progress = player.currentPosition.toFloat() / player.duration,
)
} else {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
Spacer(modifier = Modifier.height(4.dp))
Text(
modifier = Modifier.fillMaxWidth(),
text = "$systemStr $currentStr / $totalStr",
textAlign = TextAlign.Right,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1
)
}
}
fun groupTypeToString(group: Tracks.Group): String {
return when (group.type) {
C.TRACK_TYPE_NONE -> "NONE"
C.TRACK_TYPE_UNKNOWN -> "UNKNOWN"
C.TRACK_TYPE_DEFAULT -> "DEFAULT"
C.TRACK_TYPE_AUDIO -> "AUDIO"
C.TRACK_TYPE_VIDEO -> "VIDEO"
C.TRACK_TYPE_TEXT -> "TEXT"
C.TRACK_TYPE_IMAGE -> "IMAGE"
C.TRACK_TYPE_METADATA -> "METADATA"
C.TRACK_TYPE_CAMERA_MOTION -> "CAMERA_MOTION"
else -> "OTHER"
}
} | 2 | Kotlin | 1 | 2 | 28293dcb11da552a274ecc00ccf4cfb697ff029f | 12,449 | AGETV | MIT License |
domain/src/test/java/com/wiseassblog/domain/RegisteredNoteSourceTest.kt | BracketCove | 156,004,997 | false | null | package com.wiseassblog.domain
import com.wiseassblog.domain.domainmodel.*
import com.wiseassblog.domain.error.SpaceNotesError
import com.wiseassblog.domain.interactor.RegisteredNoteSource
import com.wiseassblog.domain.repository.IRemoteNoteRepository
import com.wiseassblog.domain.repository.ITransactionRepository
import com.wiseassblog.domain.servicelocator.NoteServiceLocator
import io.mockk.*
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Registered Note Source is for users which have authenticated via appropriate sign in functions.
* Registered users have access to:
* - A remote repository to share notes across devices, which is the source of truth for state
* - A local repository to cache the most recent snap shot of the remote data, and to store offline
* transactions to be pushed to the remote database.
*/
class RegisteredNoteSourceTest {
val source = RegisteredNoteSource()
//Stores transactions (NoteTransaction Cache) to be pushed to Remote eventually
val transactionRepository: ITransactionRepository = mockk()
//Contains Remote (SoT) and Local (State Cache)
val noteRepository: IRemoteNoteRepository = mockk()
val locator: NoteServiceLocator = mockk()
fun getNote(creationDate: String = "28/10/2018",
contents: String = "When I understand that this glass is already broken, every moment with it becomes precious.",
upVotes: Int = 0,
imageUrl: String = "",
creator: User? = User(
"8675309",
"<NAME>",
""
)
) = Note(
creationDate = creationDate,
contents = contents,
upVotes = upVotes,
imageUrl = imageUrl,
creator = creator
)
fun getTransaction(
creationDate: String = "28/10/2018",
contents: String = "When I understand that this glass is already broken, every moment with it becomes precious.",
upVotes: Int = 0,
imageUrl: String = "",
creator: User? = User(
"8675309",
"<NAME>",
""
),
transactionType: TransactionType = TransactionType.DELETE
) = NoteTransaction(
creationDate = creationDate,
contents = contents,
upVotes = upVotes,
imageUrl = imageUrl,
creator = creator,
transactionType = transactionType
)
@BeforeEach
fun setUpRedundantMocks() {
clearAllMocks()
}
/**
* Upon requesting Notes, multiple steps must occur:
* 1. Check transactionRepo Cache for items:
* a. Empty: Proceed 3
* b. Not Empty: Proceed 2
*
* 2. Attempt to synchronize Remote with stored transactions:
* c. Successful: Delete all transactions from transactionRepo; Proceed 3
* d. Fail: Proceed 3
*
* 3. Get data from IRemoteNoteSource and return
* e. Success: return data
* f. Fail: return error
*
*
* successful communication with the remote datasource, and
*
*/
@Test
fun `On Get Notes a, e`() = runBlocking {
val testNotes = listOf(getNote(), getNote(), getNote())
every { locator.transactionReg } returns transactionRepository
every { locator.remoteReg } returns noteRepository
coEvery { transactionRepository.getTransactions() } returns Result.build {
emptyList<NoteTransaction>()
}
coEvery { noteRepository.getNotes() } returns Result.build {
testNotes
}
val result = source.getNotes(locator)
coVerify { transactionRepository.getTransactions() }
coVerify { noteRepository.getNotes() }
if (result is Result.Value) assertEquals(result.value, testNotes)
else assertTrue { false }
}
/**
* b - transactions not empty
* c - successfully synchronized remote
* e - successfully returned data form remote
*/
@Test
fun `On Get Notes b, c, e`() = runBlocking {
val testNotes = listOf(getNote(), getNote(), getNote())
val testTransactions = listOf(getTransaction(), getTransaction(), getTransaction())
every { locator.transactionReg } returns transactionRepository
every { locator.remoteReg } returns noteRepository
coEvery { transactionRepository.getTransactions() } returns Result.build {
testTransactions
}
coEvery { transactionRepository.deleteTransactions() } returns Result.build {
Unit
}
coEvery { noteRepository.getNotes() } returns Result.build {
testNotes
}
coEvery { noteRepository.synchronizeTransactions(testTransactions) } returns Result.build {
Unit
}
val result = source.getNotes(locator)
coVerify { transactionRepository.getTransactions() }
coVerify { noteRepository.synchronizeTransactions(testTransactions) }
coVerify { transactionRepository.deleteTransactions() }
coVerify { noteRepository.getNotes() }
if (result is Result.Value) assertEquals(result.value, testNotes)
else assertTrue { false }
}
/**
* Attempt to retrieve a note from remote repository.
* a. Success
* b. Fail
*
* a:
* 1. Request Note from Remote: success
* 2. return data
*
*/
@Test
fun `On Get Note a`() = runBlocking {
val testId = getNote().creationDate
every { locator.remoteReg } returns noteRepository
coEvery { noteRepository.getNote(testId) } returns Result.build {
getNote()
}
val result = source.getNoteById(testId, locator)
coVerify { noteRepository.getNote(testId) }
if (result is Result.Value) assertEquals(result.value, getNote())
else assertTrue { false }
}
/**
* b:
* 1. Request Note from Remote: fail
* 2. return error
*/
@Test
fun `On Get Note b`() = runBlocking {
val testId = getNote().creationDate
every { locator.remoteReg } returns noteRepository
coEvery { noteRepository.getNote(testId) } returns Result.build {
throw SpaceNotesError.RemoteIOException
}
val result = source.getNoteById(testId, locator)
coVerify { noteRepository.getNote(testId) }
assertTrue { result is Result.Error }
}
/**
* Attempt to delete a note from remote repository. Failing that, store a transaction object
* in transaction database. Failing that, return error.
* a. Success
* b. Delete Fail
* c. Transaction Fail
*
* a:
* 1. Delete Note from Remote: success
* 2. return Success
*
*/
@Test
fun `On Delete Note a`() = runBlocking {
val testNote = getNote()
every { locator.remoteReg } returns noteRepository
coEvery { noteRepository.deleteNote(testNote) } returns Result.build {
Unit
}
val result = source.deleteNote(testNote, locator)
coVerify { noteRepository.deleteNote(testNote) }
if (result is Result.Value) {
//assert the value as being "true"
assertTrue { true }
} else {
assertTrue { false }
}
}
/**
* b:
* 1. Delete Note from Remote: fail
* 2. Map to NoteTransaction and store in transactionRepository: success
* 3. return Success
*/
@Test
fun `On Delete Note b`() = runBlocking {
val testNote = getNote()
val testTransaction = getNote().toTransaction(TransactionType.DELETE)
every { locator.remoteReg } returns noteRepository
every { locator.transactionReg } returns transactionRepository
coEvery { noteRepository.deleteNote(testNote) } returns Result.build {
throw SpaceNotesError.RemoteIOException
}
coEvery { transactionRepository.updateTransactions(testTransaction) } returns Result.build {
Unit
}
val result = source.deleteNote(testNote, locator)
coVerify { noteRepository.deleteNote(testNote) }
coVerify { transactionRepository.updateTransactions(testTransaction) }
if (result is Result.Value) {
//assert the value as being "false"
assertTrue { true }
} else {
assertTrue { false }
}
}
/**
* c:
* 1. Delete Note from Remote: fail
* 2. Map to NoteTransaction and store in transactionRepository: fail
* 3. return error
*/
@Test
fun `On Delete Note c`() = runBlocking {
val testNote = getNote()
val testTransaction = getNote().toTransaction(TransactionType.DELETE)
every { locator.remoteReg } returns noteRepository
every { locator.transactionReg } returns transactionRepository
coEvery { noteRepository.deleteNote(testNote) } returns Result.build {
throw SpaceNotesError.RemoteIOException
}
coEvery { transactionRepository.updateTransactions(testTransaction) } returns Result.build {
throw SpaceNotesError.TransactionIOException
}
val result = source.deleteNote(testNote, locator)
coVerify { noteRepository.deleteNote(testNote) }
coVerify { transactionRepository.updateTransactions(testTransaction) }
assertTrue { result is Result.Error }
}
/**
* Attempt to update a note in remote repository. Failing that, store a transaction object
* in transaction database. Failing that, return error.
* a. Success
* b. Update Fail
* c. Transaction Fail
*
* a:
* 1. Update Note from Remote: success
* 2. return Success
*
*/
@Test
fun `On Update Note a`() = runBlocking {
val testNote = getNote()
every { locator.remoteReg } returns noteRepository
coEvery { noteRepository.updateNote(testNote) } returns Result.build {
Unit
}
val result = source.updateNote(testNote, locator)
coVerify { noteRepository.updateNote(testNote) }
if (result is Result.Value) {
//assert the value as being "true"
assertTrue { true }
} else {
assertTrue { false }
}
}
/**
* b:
* 1. Delete Note from Remote: fail
* 2. Map to NoteTransaction and store in transactionRepository: success
* 3. return Success
*/
@Test
fun `On Update Note b`() = runBlocking {
val testNote = getNote()
val testTransaction = getNote().toTransaction(TransactionType.UPDATE)
every { locator.remoteReg } returns noteRepository
every { locator.transactionReg } returns transactionRepository
coEvery { noteRepository.updateNote(testNote) } returns Result.build {
throw SpaceNotesError.RemoteIOException
}
coEvery { transactionRepository.updateTransactions(testTransaction) } returns Result.build {
Unit
}
val result = source.updateNote(testNote, locator)
coVerify { noteRepository.updateNote(testNote) }
coVerify { transactionRepository.updateTransactions(testTransaction) }
if (result is Result.Value) {
//assert the value as being "false"
assertTrue { true }
} else {
assertTrue { false }
}
}
/**
* c:
* 1. Delete Note from Remote: fail
* 2. Map to NoteTransaction and store in transactionRepository: fail
* 3. return error
*/
@Test
fun `On Update Note c`() = runBlocking {
val testNote = getNote()
val testTransaction = getNote().toTransaction(TransactionType.UPDATE)
every { locator.remoteReg } returns noteRepository
every { locator.transactionReg } returns transactionRepository
coEvery { noteRepository.updateNote(testNote) } returns Result.build {
throw SpaceNotesError.RemoteIOException
}
coEvery { transactionRepository.updateTransactions(testTransaction) } returns Result.build {
throw SpaceNotesError.TransactionIOException
}
val result = source.updateNote(testNote, locator)
coVerify { noteRepository.updateNote(testNote) }
coVerify { transactionRepository.updateTransactions(testTransaction) }
assertTrue { result is Result.Error }
}
@AfterEach
fun confirm() {
excludeRecords {
locator.transactionReg
locator.remoteReg
}
confirmVerified(
transactionRepository,
noteRepository,
locator
)
}
}
| 2 | Kotlin | 113 | 195 | d799560fbb942c0d349afac53520913b7157c2ef | 13,041 | SpaceNotes | Apache License 2.0 |
app/src/main/kotlin/com/tanyayuferova/lifestylenews/ui/list/ArticlesAdapter.kt | TanyaYu | 114,388,222 | false | {"Kotlin": 91914} | package com.tanyayuferova.lifestylenews.ui.list
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.tanyayuferova.lifestylenews.databinding.ItemArticleBinding
/**
* Author: <NAME>
* Date: 7/29/19
*/
class ArticlesAdapter(
private val actionsHandler: ActionsHandler
) : ListAdapter<ArticleListItem, ArticlesAdapter.ViewHolder>(
object : DiffUtil.ItemCallback<ArticleListItem>() {
override fun areItemsTheSame(old: ArticleListItem, new: ArticleListItem): Boolean {
return old.id == new.id
}
override fun areContentsTheSame(old: ArticleListItem, new: ArticleListItem): Boolean {
return old == new
}
override fun getChangePayload(old: ArticleListItem, new: ArticleListItem): Any? {
return if (old.isFavorite != new.isFavorite)
IS_FAVORITE_PAYLOAD
else super.getChangePayload(old, new)
}
}
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val itemBinding = ItemArticleBinding.inflate(layoutInflater, parent, false)
return ViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
if (payloads.contains(IS_FAVORITE_PAYLOAD)) {
holder.bindFavorite(getItem(position).isFavorite)
} else {
onBindViewHolder(holder, position)
}
}
inner class ViewHolder(
private val binding: ItemArticleBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: ArticleListItem) {
binding.item = item
binding.handler = actionsHandler
bindFavorite(item.isFavorite)
}
fun bindFavorite(isFavorite: Boolean) {
binding.isFavorite = isFavorite
}
}
interface ActionsHandler {
fun onArticleClick(id: Int)
fun onFavoriteClick(id: Int, isFavorite: Boolean)
fun onReadClick(id: Int)
}
companion object {
const val IS_FAVORITE_PAYLOAD = "IS_FAVORITE_PAYLOAD"
}
} | 1 | Kotlin | 0 | 0 | 2f078d3fa116bee3236104511e5868868d89acc9 | 2,450 | LifestyleNews | Apache License 2.0 |
app/src/main/java/com/qty/quickdischarge/NetworkConnection.kt | xiaotuan | 407,385,173 | false | {"Kotlin": 30686} | package com.qty.quickdischarge
import android.content.Context
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
class NetworkConnection(
private val context: Context
) {
private var mNetworkConnectionThread: Thread? = null
private var isStarted = false
fun start() {
if (!isStarted) {
isStarted = true
mNetworkConnectionThread = Thread {
while (isStarted) {
try {
val baidu = URL(context.resources.getString(R.string.network_connection_url))
val connection = baidu.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.useCaches = false
connection.doInput = true
connection.doOutput = false
connection.connect()
Log.d(TAG, "start=>response code: ${connection.responseCode}")
if (connection.responseCode == HttpURLConnection.HTTP_OK) {
val sb = StringBuilder()
val reader = BufferedReader(InputStreamReader(connection.inputStream))
var line = reader.readLine()
while (line != null) {
sb.append(line)
line = reader.readLine()
}
Log.d(TAG, "start=>response: $sb")
}
connection.disconnect()
Thread.sleep(context.resources.getInteger(R.integer.network_request_interval).toLong())
} catch (e: Exception) {
Log.e(TAG, "start=>error: $e")
}
}
}
mNetworkConnectionThread!!.start()
}
}
fun stop() {
if (isStarted) {
isStarted = false
try {
mNetworkConnectionThread?.interrupt()
} catch (e: Exception) {
Log.e(TAG, "stop=> $e")
}
}
}
companion object {
const val TAG = "NetworkConnection"
}
} | 0 | Kotlin | 2 | 0 | 60eadcbecbaada92ea85d8971b8eee2b346b5dc7 | 2,406 | QuickDischarge | Apache License 2.0 |
dexfile/src/main/kotlin/org/tinygears/bat/dexfile/value/visitor/EncodedArrayVisitor.kt | TinyGearsOrg | 562,774,371 | false | {"Kotlin": 1879358, "Smali": 712514, "ANTLR": 26362, "Shell": 12090} | /*
* Copyright (c) 2020-2022 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinygears.bat.dexfile.value.visitor
import org.tinygears.bat.dexfile.DexFile
import org.tinygears.bat.dexfile.value.EncodedArrayValue
import org.tinygears.bat.dexfile.value.EncodedValue
fun filterByStartIndex(startIndex: Int, visitor: EncodedValueVisitor): EncodedArrayVisitor {
return EncodedArrayVisitor { dexFile, _, index, value ->
if (index >= startIndex) {
value.accept(dexFile, visitor)
}
}
}
fun interface EncodedArrayVisitor {
fun visitEncodedValue(dexFile: DexFile, array: EncodedArrayValue, index: Int, value: EncodedValue)
} | 0 | Kotlin | 0 | 0 | 50083893ad93820f9cf221598692e81dda05d150 | 1,211 | bat | Apache License 2.0 |
compiler/test/data/cli/request/https.https.module_node.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | @file:JsModule("https")
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
package https
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.*
external interface `T$0` {
var rejectUnauthorized: Boolean?
get() = definedExternally
set(value) = definedExternally
var servername: String?
get() = definedExternally
set(value) = definedExternally
}
external interface AgentOptions : http.AgentOptions, tls.ConnectionOptions {
var rejectUnauthorized: Boolean?
get() = definedExternally
set(value) = definedExternally
var maxCachedSessions: Number?
get() = definedExternally
set(value) = definedExternally
}
external open class Agent(options: AgentOptions? = definedExternally /* null */) : http.Agent {
open var options: AgentOptions
}
external open class Server(requestListener: http.RequestListener? = definedExternally /* null */) : tls.Server {
constructor(options: tls.SecureContextOptions, requestListener: http.RequestListener?)
open fun setTimeout(callback: () -> Unit): Server /* this */
open fun setTimeout(msecs: Number? = definedExternally /* null */, callback: (() -> Unit)? = definedExternally /* null */): Server /* this */
open var maxHeadersCount: Number?
open var timeout: Number
open var headersTimeout: Number
open var keepAliveTimeout: Number
}
external fun createServer(requestListener: http.RequestListener? = definedExternally /* null */): Server
external fun createServer(options: tls.SecureContextOptions /* tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions */, requestListener: http.RequestListener? = definedExternally /* null */): Server
external fun request(options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun request(options: String, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun request(options: URL, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun request(url: String, options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun request(url: URL, options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun get(options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun get(options: String, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun get(options: URL, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun get(url: String, options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external fun get(url: URL, options: http.RequestOptions /* http.RequestOptions & tls.SecureContextOptions & `T$0` */, callback: ((res: http.IncomingMessage) -> Unit)? = definedExternally /* null */): http.ClientRequest
external var globalAgent: Agent | 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 3,941 | dukat | Apache License 2.0 |
src/controller/java/generated/java/matter/controller/cluster/clusters/NetworkCommissioningCluster.kt | project-chip | 244,694,174 | false | {"C++": 24146071, "Kotlin": 8227006, "Java": 7134698, "Python": 3866042, "C": 2280568, "Objective-C": 1373765, "ZAP": 824658, "Objective-C++": 764141, "Shell": 298232, "CMake": 175247, "Jinja": 144691, "Dockerfile": 72039, "Swift": 29310, "JavaScript": 2484, "Emacs Lisp": 1042, "Tcl": 311} | /*
*
* Copyright (c) 2023 Project CHIP 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
*
* 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 matter.controller.cluster.clusters
import java.time.Duration
import java.util.logging.Level
import java.util.logging.Logger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.transform
import matter.controller.BooleanSubscriptionState
import matter.controller.InvokeRequest
import matter.controller.InvokeResponse
import matter.controller.MatterController
import matter.controller.ReadData
import matter.controller.ReadRequest
import matter.controller.SubscribeRequest
import matter.controller.SubscriptionState
import matter.controller.UByteSubscriptionState
import matter.controller.UIntSubscriptionState
import matter.controller.UShortSubscriptionState
import matter.controller.WriteRequest
import matter.controller.WriteRequests
import matter.controller.WriteResponse
import matter.controller.cluster.structs.*
import matter.controller.model.AttributePath
import matter.controller.model.CommandPath
import matter.tlv.AnonymousTag
import matter.tlv.ContextSpecificTag
import matter.tlv.TlvReader
import matter.tlv.TlvWriter
class NetworkCommissioningCluster(
private val controller: MatterController,
private val endpointId: UShort
) {
class ScanNetworksResponse(
val networkingStatus: UByte,
val debugText: String?,
val wiFiScanResults: List<NetworkCommissioningClusterWiFiInterfaceScanResultStruct>?,
val threadScanResults: List<NetworkCommissioningClusterThreadInterfaceScanResultStruct>?
)
class NetworkConfigResponse(
val networkingStatus: UByte,
val debugText: String?,
val networkIndex: UByte?,
val clientIdentity: ByteArray?,
val possessionSignature: ByteArray?
)
class ConnectNetworkResponse(
val networkingStatus: UByte,
val debugText: String?,
val errorValue: Int?
)
class QueryIdentityResponse(val identity: ByteArray, val possessionSignature: ByteArray?)
class NetworksAttribute(val value: List<NetworkCommissioningClusterNetworkInfoStruct>)
sealed class NetworksAttributeSubscriptionState {
data class Success(val value: List<NetworkCommissioningClusterNetworkInfoStruct>) :
NetworksAttributeSubscriptionState()
data class Error(val exception: Exception) : NetworksAttributeSubscriptionState()
object SubscriptionEstablished : NetworksAttributeSubscriptionState()
}
class LastNetworkingStatusAttribute(val value: UByte?)
sealed class LastNetworkingStatusAttributeSubscriptionState {
data class Success(val value: UByte?) : LastNetworkingStatusAttributeSubscriptionState()
data class Error(val exception: Exception) : LastNetworkingStatusAttributeSubscriptionState()
object SubscriptionEstablished : LastNetworkingStatusAttributeSubscriptionState()
}
class LastNetworkIDAttribute(val value: ByteArray?)
sealed class LastNetworkIDAttributeSubscriptionState {
data class Success(val value: ByteArray?) : LastNetworkIDAttributeSubscriptionState()
data class Error(val exception: Exception) : LastNetworkIDAttributeSubscriptionState()
object SubscriptionEstablished : LastNetworkIDAttributeSubscriptionState()
}
class LastConnectErrorValueAttribute(val value: Int?)
sealed class LastConnectErrorValueAttributeSubscriptionState {
data class Success(val value: Int?) : LastConnectErrorValueAttributeSubscriptionState()
data class Error(val exception: Exception) : LastConnectErrorValueAttributeSubscriptionState()
object SubscriptionEstablished : LastConnectErrorValueAttributeSubscriptionState()
}
class SupportedWiFiBandsAttribute(val value: List<UByte>?)
sealed class SupportedWiFiBandsAttributeSubscriptionState {
data class Success(val value: List<UByte>?) : SupportedWiFiBandsAttributeSubscriptionState()
data class Error(val exception: Exception) : SupportedWiFiBandsAttributeSubscriptionState()
object SubscriptionEstablished : SupportedWiFiBandsAttributeSubscriptionState()
}
class GeneratedCommandListAttribute(val value: List<UInt>)
sealed class GeneratedCommandListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : GeneratedCommandListAttributeSubscriptionState()
data class Error(val exception: Exception) : GeneratedCommandListAttributeSubscriptionState()
object SubscriptionEstablished : GeneratedCommandListAttributeSubscriptionState()
}
class AcceptedCommandListAttribute(val value: List<UInt>)
sealed class AcceptedCommandListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : AcceptedCommandListAttributeSubscriptionState()
data class Error(val exception: Exception) : AcceptedCommandListAttributeSubscriptionState()
object SubscriptionEstablished : AcceptedCommandListAttributeSubscriptionState()
}
class EventListAttribute(val value: List<UInt>)
sealed class EventListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : EventListAttributeSubscriptionState()
data class Error(val exception: Exception) : EventListAttributeSubscriptionState()
object SubscriptionEstablished : EventListAttributeSubscriptionState()
}
class AttributeListAttribute(val value: List<UInt>)
sealed class AttributeListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : AttributeListAttributeSubscriptionState()
data class Error(val exception: Exception) : AttributeListAttributeSubscriptionState()
object SubscriptionEstablished : AttributeListAttributeSubscriptionState()
}
suspend fun scanNetworks(
ssid: ByteArray?,
breadcrumb: ULong?,
timedInvokeTimeout: Duration? = null
): ScanNetworksResponse {
val commandId: UInt = 0u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_SSID_REQ: Int = 0
ssid?.let { tlvWriter.put(ContextSpecificTag(TAG_SSID_REQ), ssid) }
val TAG_BREADCRUMB_REQ: Int = 1
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_WI_FI_SCAN_RESULTS: Int = 2
var wiFiScanResults_decoded: List<NetworkCommissioningClusterWiFiInterfaceScanResultStruct>? =
null
val TAG_THREAD_SCAN_RESULTS: Int = 3
var threadScanResults_decoded:
List<NetworkCommissioningClusterThreadInterfaceScanResultStruct>? =
null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_WI_FI_SCAN_RESULTS)) {
wiFiScanResults_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
buildList<NetworkCommissioningClusterWiFiInterfaceScanResultStruct> {
tlvReader.enterArray(tag)
while (!tlvReader.isEndOfContainer()) {
add(
NetworkCommissioningClusterWiFiInterfaceScanResultStruct.fromTlv(
AnonymousTag,
tlvReader
)
)
}
tlvReader.exitContainer()
}
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_THREAD_SCAN_RESULTS)) {
threadScanResults_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
buildList<NetworkCommissioningClusterThreadInterfaceScanResultStruct> {
tlvReader.enterArray(tag)
while (!tlvReader.isEndOfContainer()) {
add(
NetworkCommissioningClusterThreadInterfaceScanResultStruct.fromTlv(
AnonymousTag,
tlvReader
)
)
}
tlvReader.exitContainer()
}
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return ScanNetworksResponse(
networkingStatus_decoded,
debugText_decoded,
wiFiScanResults_decoded,
threadScanResults_decoded
)
}
suspend fun addOrUpdateWiFiNetwork(
ssid: ByteArray,
credentials: ByteArray,
breadcrumb: ULong?,
networkIdentity: ByteArray?,
clientIdentifier: ByteArray?,
possessionNonce: ByteArray?,
timedInvokeTimeout: Duration? = null
): NetworkConfigResponse {
val commandId: UInt = 2u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_SSID_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_SSID_REQ), ssid)
val TAG_CREDENTIALS_REQ: Int = 1
tlvWriter.put(ContextSpecificTag(TAG_CREDENTIALS_REQ), credentials)
val TAG_BREADCRUMB_REQ: Int = 2
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
val TAG_NETWORK_IDENTITY_REQ: Int = 3
networkIdentity?.let {
tlvWriter.put(ContextSpecificTag(TAG_NETWORK_IDENTITY_REQ), networkIdentity)
}
val TAG_CLIENT_IDENTIFIER_REQ: Int = 4
clientIdentifier?.let {
tlvWriter.put(ContextSpecificTag(TAG_CLIENT_IDENTIFIER_REQ), clientIdentifier)
}
val TAG_POSSESSION_NONCE_REQ: Int = 5
possessionNonce?.let {
tlvWriter.put(ContextSpecificTag(TAG_POSSESSION_NONCE_REQ), possessionNonce)
}
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_NETWORK_INDEX: Int = 2
var networkIndex_decoded: UByte? = null
val TAG_CLIENT_IDENTITY: Int = 3
var clientIdentity_decoded: ByteArray? = null
val TAG_POSSESSION_SIGNATURE: Int = 4
var possessionSignature_decoded: ByteArray? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_NETWORK_INDEX)) {
networkIndex_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getUByte(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_CLIENT_IDENTITY)) {
clientIdentity_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_POSSESSION_SIGNATURE)) {
possessionSignature_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return NetworkConfigResponse(
networkingStatus_decoded,
debugText_decoded,
networkIndex_decoded,
clientIdentity_decoded,
possessionSignature_decoded
)
}
suspend fun addOrUpdateThreadNetwork(
operationalDataset: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeout: Duration? = null
): NetworkConfigResponse {
val commandId: UInt = 3u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_OPERATIONAL_DATASET_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_OPERATIONAL_DATASET_REQ), operationalDataset)
val TAG_BREADCRUMB_REQ: Int = 1
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_NETWORK_INDEX: Int = 2
var networkIndex_decoded: UByte? = null
val TAG_CLIENT_IDENTITY: Int = 3
var clientIdentity_decoded: ByteArray? = null
val TAG_POSSESSION_SIGNATURE: Int = 4
var possessionSignature_decoded: ByteArray? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_NETWORK_INDEX)) {
networkIndex_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getUByte(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_CLIENT_IDENTITY)) {
clientIdentity_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_POSSESSION_SIGNATURE)) {
possessionSignature_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return NetworkConfigResponse(
networkingStatus_decoded,
debugText_decoded,
networkIndex_decoded,
clientIdentity_decoded,
possessionSignature_decoded
)
}
suspend fun removeNetwork(
networkID: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeout: Duration? = null
): NetworkConfigResponse {
val commandId: UInt = 4u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_NETWORK_I_D_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID)
val TAG_BREADCRUMB_REQ: Int = 1
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_NETWORK_INDEX: Int = 2
var networkIndex_decoded: UByte? = null
val TAG_CLIENT_IDENTITY: Int = 3
var clientIdentity_decoded: ByteArray? = null
val TAG_POSSESSION_SIGNATURE: Int = 4
var possessionSignature_decoded: ByteArray? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_NETWORK_INDEX)) {
networkIndex_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getUByte(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_CLIENT_IDENTITY)) {
clientIdentity_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_POSSESSION_SIGNATURE)) {
possessionSignature_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return NetworkConfigResponse(
networkingStatus_decoded,
debugText_decoded,
networkIndex_decoded,
clientIdentity_decoded,
possessionSignature_decoded
)
}
suspend fun connectNetwork(
networkID: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeout: Duration? = null
): ConnectNetworkResponse {
val commandId: UInt = 6u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_NETWORK_I_D_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID)
val TAG_BREADCRUMB_REQ: Int = 1
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_ERROR_VALUE: Int = 2
var errorValue_decoded: Int? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_ERROR_VALUE)) {
errorValue_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (!tlvReader.isNull()) {
tlvReader.getInt(tag)
} else {
tlvReader.getNull(tag)
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return ConnectNetworkResponse(networkingStatus_decoded, debugText_decoded, errorValue_decoded)
}
suspend fun reorderNetwork(
networkID: ByteArray,
networkIndex: UByte,
breadcrumb: ULong?,
timedInvokeTimeout: Duration? = null
): NetworkConfigResponse {
val commandId: UInt = 8u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_NETWORK_I_D_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_NETWORK_I_D_REQ), networkID)
val TAG_NETWORK_INDEX_REQ: Int = 1
tlvWriter.put(ContextSpecificTag(TAG_NETWORK_INDEX_REQ), networkIndex)
val TAG_BREADCRUMB_REQ: Int = 2
breadcrumb?.let { tlvWriter.put(ContextSpecificTag(TAG_BREADCRUMB_REQ), breadcrumb) }
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_NETWORKING_STATUS: Int = 0
var networkingStatus_decoded: UByte? = null
val TAG_DEBUG_TEXT: Int = 1
var debugText_decoded: String? = null
val TAG_NETWORK_INDEX: Int = 2
var networkIndex_decoded: UByte? = null
val TAG_CLIENT_IDENTITY: Int = 3
var clientIdentity_decoded: ByteArray? = null
val TAG_POSSESSION_SIGNATURE: Int = 4
var possessionSignature_decoded: ByteArray? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_NETWORKING_STATUS)) {
networkingStatus_decoded = tlvReader.getUByte(tag)
}
if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
debugText_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getString(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_NETWORK_INDEX)) {
networkIndex_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getUByte(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_CLIENT_IDENTITY)) {
clientIdentity_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
}
if (tag == ContextSpecificTag(TAG_POSSESSION_SIGNATURE)) {
possessionSignature_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (networkingStatus_decoded == null) {
throw IllegalStateException("networkingStatus not found in TLV")
}
tlvReader.exitContainer()
return NetworkConfigResponse(
networkingStatus_decoded,
debugText_decoded,
networkIndex_decoded,
clientIdentity_decoded,
possessionSignature_decoded
)
}
suspend fun queryIdentity(
keyIdentifier: ByteArray,
possessionNonce: ByteArray?,
timedInvokeTimeout: Duration? = null
): QueryIdentityResponse {
val commandId: UInt = 9u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
val TAG_KEY_IDENTIFIER_REQ: Int = 0
tlvWriter.put(ContextSpecificTag(TAG_KEY_IDENTIFIER_REQ), keyIdentifier)
val TAG_POSSESSION_NONCE_REQ: Int = 1
possessionNonce?.let {
tlvWriter.put(ContextSpecificTag(TAG_POSSESSION_NONCE_REQ), possessionNonce)
}
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_IDENTITY: Int = 0
var identity_decoded: ByteArray? = null
val TAG_POSSESSION_SIGNATURE: Int = 1
var possessionSignature_decoded: ByteArray? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_IDENTITY)) {
identity_decoded = tlvReader.getByteArray(tag)
}
if (tag == ContextSpecificTag(TAG_POSSESSION_SIGNATURE)) {
possessionSignature_decoded =
if (tlvReader.isNull()) {
tlvReader.getNull(tag)
null
} else {
if (tlvReader.isNextTag(tag)) {
tlvReader.getByteArray(tag)
} else {
null
}
}
} else {
tlvReader.skipElement()
}
}
if (identity_decoded == null) {
throw IllegalStateException("identity not found in TLV")
}
tlvReader.exitContainer()
return QueryIdentityResponse(identity_decoded, possessionSignature_decoded)
}
suspend fun readMaxNetworksAttribute(): UByte {
val ATTRIBUTE_ID: UInt = 0u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Maxnetworks attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte = tlvReader.getUByte(AnonymousTag)
return decodedValue
}
suspend fun subscribeMaxNetworksAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UByteSubscriptionState> {
val ATTRIBUTE_ID: UInt = 0u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UByteSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Maxnetworks attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte = tlvReader.getUByte(AnonymousTag)
emit(UByteSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UByteSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readNetworksAttribute(): NetworksAttribute {
val ATTRIBUTE_ID: UInt = 1u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Networks attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<NetworkCommissioningClusterNetworkInfoStruct> =
buildList<NetworkCommissioningClusterNetworkInfoStruct> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(NetworkCommissioningClusterNetworkInfoStruct.fromTlv(AnonymousTag, tlvReader))
}
tlvReader.exitContainer()
}
return NetworksAttribute(decodedValue)
}
suspend fun subscribeNetworksAttribute(
minInterval: Int,
maxInterval: Int
): Flow<NetworksAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 1u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
NetworksAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Networks attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<NetworkCommissioningClusterNetworkInfoStruct> =
buildList<NetworkCommissioningClusterNetworkInfoStruct> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(NetworkCommissioningClusterNetworkInfoStruct.fromTlv(AnonymousTag, tlvReader))
}
tlvReader.exitContainer()
}
emit(NetworksAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(NetworksAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readScanMaxTimeSecondsAttribute(): UByte? {
val ATTRIBUTE_ID: UInt = 2u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Scanmaxtimeseconds attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUByte(AnonymousTag)
} else {
null
}
return decodedValue
}
suspend fun subscribeScanMaxTimeSecondsAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UByteSubscriptionState> {
val ATTRIBUTE_ID: UInt = 2u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UByteSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Scanmaxtimeseconds attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUByte(AnonymousTag)
} else {
null
}
decodedValue?.let { emit(UByteSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(UByteSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readConnectMaxTimeSecondsAttribute(): UByte? {
val ATTRIBUTE_ID: UInt = 3u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Connectmaxtimeseconds attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUByte(AnonymousTag)
} else {
null
}
return decodedValue
}
suspend fun subscribeConnectMaxTimeSecondsAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UByteSubscriptionState> {
val ATTRIBUTE_ID: UInt = 3u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UByteSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Connectmaxtimeseconds attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUByte(AnonymousTag)
} else {
null
}
decodedValue?.let { emit(UByteSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(UByteSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readInterfaceEnabledAttribute(): Boolean {
val ATTRIBUTE_ID: UInt = 4u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Interfaceenabled attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: Boolean = tlvReader.getBoolean(AnonymousTag)
return decodedValue
}
suspend fun writeInterfaceEnabledAttribute(value: Boolean, timedWriteTimeout: Duration? = null) {
val ATTRIBUTE_ID: UInt = 4u
val tlvWriter = TlvWriter()
tlvWriter.put(AnonymousTag, value)
val writeRequests: WriteRequests =
WriteRequests(
requests =
listOf(
WriteRequest(
attributePath =
AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID),
tlvPayload = tlvWriter.getEncoded()
)
),
timedRequest = timedWriteTimeout
)
val response: WriteResponse = controller.write(writeRequests)
when (response) {
is WriteResponse.Success -> {
logger.log(Level.FINE, "Write command succeeded")
}
is WriteResponse.PartialWriteFailure -> {
val aggregatedErrorMessage =
response.failures.joinToString("\n") { failure ->
"Error at ${failure.attributePath}: ${failure.ex.message}"
}
response.failures.forEach { failure ->
logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}")
}
throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage")
}
}
}
suspend fun subscribeInterfaceEnabledAttribute(
minInterval: Int,
maxInterval: Int
): Flow<BooleanSubscriptionState> {
val ATTRIBUTE_ID: UInt = 4u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
BooleanSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Interfaceenabled attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: Boolean = tlvReader.getBoolean(AnonymousTag)
emit(BooleanSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(BooleanSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readLastNetworkingStatusAttribute(): LastNetworkingStatusAttribute {
val ATTRIBUTE_ID: UInt = 5u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Lastnetworkingstatus attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (!tlvReader.isNull()) {
tlvReader.getUByte(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
return LastNetworkingStatusAttribute(decodedValue)
}
suspend fun subscribeLastNetworkingStatusAttribute(
minInterval: Int,
maxInterval: Int
): Flow<LastNetworkingStatusAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 5u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
LastNetworkingStatusAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Lastnetworkingstatus attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (!tlvReader.isNull()) {
tlvReader.getUByte(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(LastNetworkingStatusAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(LastNetworkingStatusAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readLastNetworkIDAttribute(): LastNetworkIDAttribute {
val ATTRIBUTE_ID: UInt = 6u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Lastnetworkid attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: ByteArray? =
if (!tlvReader.isNull()) {
tlvReader.getByteArray(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
return LastNetworkIDAttribute(decodedValue)
}
suspend fun subscribeLastNetworkIDAttribute(
minInterval: Int,
maxInterval: Int
): Flow<LastNetworkIDAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 6u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
LastNetworkIDAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Lastnetworkid attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: ByteArray? =
if (!tlvReader.isNull()) {
tlvReader.getByteArray(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(LastNetworkIDAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(LastNetworkIDAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readLastConnectErrorValueAttribute(): LastConnectErrorValueAttribute {
val ATTRIBUTE_ID: UInt = 7u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Lastconnecterrorvalue attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: Int? =
if (!tlvReader.isNull()) {
tlvReader.getInt(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
return LastConnectErrorValueAttribute(decodedValue)
}
suspend fun subscribeLastConnectErrorValueAttribute(
minInterval: Int,
maxInterval: Int
): Flow<LastConnectErrorValueAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 7u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
LastConnectErrorValueAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Lastconnecterrorvalue attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: Int? =
if (!tlvReader.isNull()) {
tlvReader.getInt(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(LastConnectErrorValueAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(LastConnectErrorValueAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readSupportedWiFiBandsAttribute(): SupportedWiFiBandsAttribute {
val ATTRIBUTE_ID: UInt = 8u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Supportedwifibands attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UByte>? =
if (tlvReader.isNextTag(AnonymousTag)) {
buildList<UByte> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUByte(AnonymousTag))
}
tlvReader.exitContainer()
}
} else {
null
}
return SupportedWiFiBandsAttribute(decodedValue)
}
suspend fun subscribeSupportedWiFiBandsAttribute(
minInterval: Int,
maxInterval: Int
): Flow<SupportedWiFiBandsAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 8u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
SupportedWiFiBandsAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Supportedwifibands attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UByte>? =
if (tlvReader.isNextTag(AnonymousTag)) {
buildList<UByte> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUByte(AnonymousTag))
}
tlvReader.exitContainer()
}
} else {
null
}
decodedValue?.let { emit(SupportedWiFiBandsAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(SupportedWiFiBandsAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readSupportedThreadFeaturesAttribute(): UShort? {
val ATTRIBUTE_ID: UInt = 9u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Supportedthreadfeatures attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUShort(AnonymousTag)
} else {
null
}
return decodedValue
}
suspend fun subscribeSupportedThreadFeaturesAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UShortSubscriptionState> {
val ATTRIBUTE_ID: UInt = 9u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UShortSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Supportedthreadfeatures attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUShort(AnonymousTag)
} else {
null
}
decodedValue?.let { emit(UShortSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(UShortSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readThreadVersionAttribute(): UShort? {
val ATTRIBUTE_ID: UInt = 10u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Threadversion attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUShort(AnonymousTag)
} else {
null
}
return decodedValue
}
suspend fun subscribeThreadVersionAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UShortSubscriptionState> {
val ATTRIBUTE_ID: UInt = 10u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UShortSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Threadversion attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort? =
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUShort(AnonymousTag)
} else {
null
}
decodedValue?.let { emit(UShortSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(UShortSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readGeneratedCommandListAttribute(): GeneratedCommandListAttribute {
val ATTRIBUTE_ID: UInt = 65528u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Generatedcommandlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return GeneratedCommandListAttribute(decodedValue)
}
suspend fun subscribeGeneratedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<GeneratedCommandListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65528u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
GeneratedCommandListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Generatedcommandlist attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(GeneratedCommandListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(GeneratedCommandListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readAcceptedCommandListAttribute(): AcceptedCommandListAttribute {
val ATTRIBUTE_ID: UInt = 65529u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Acceptedcommandlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return AcceptedCommandListAttribute(decodedValue)
}
suspend fun subscribeAcceptedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<AcceptedCommandListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65529u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
AcceptedCommandListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Acceptedcommandlist attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(AcceptedCommandListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(AcceptedCommandListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readEventListAttribute(): EventListAttribute {
val ATTRIBUTE_ID: UInt = 65530u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Eventlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return EventListAttribute(decodedValue)
}
suspend fun subscribeEventListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<EventListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65530u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
EventListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Eventlist attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(EventListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(EventListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readAttributeListAttribute(): AttributeListAttribute {
val ATTRIBUTE_ID: UInt = 65531u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Attributelist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return AttributeListAttribute(decodedValue)
}
suspend fun subscribeAttributeListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<AttributeListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65531u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
AttributeListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Attributelist attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(AttributeListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(AttributeListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readFeatureMapAttribute(): UInt {
val ATTRIBUTE_ID: UInt = 65532u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Featuremap attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt = tlvReader.getUInt(AnonymousTag)
return decodedValue
}
suspend fun subscribeFeatureMapAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UIntSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65532u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UIntSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Featuremap attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt = tlvReader.getUInt(AnonymousTag)
emit(UIntSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UIntSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readClusterRevisionAttribute(): UShort {
val ATTRIBUTE_ID: UInt = 65533u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Clusterrevision attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort = tlvReader.getUShort(AnonymousTag)
return decodedValue
}
suspend fun subscribeClusterRevisionAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UShortSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65533u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UShortSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Clusterrevision attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort = tlvReader.getUShort(AnonymousTag)
emit(UShortSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UShortSubscriptionState.SubscriptionEstablished)
}
}
}
}
companion object {
private val logger = Logger.getLogger(NetworkCommissioningCluster::class.java.name)
const val CLUSTER_ID: UInt = 49u
}
}
| 1,443 | C++ | 1,769 | 6,671 | 420e6d424c00aed3ead4015eafd71a1632c5e540 | 84,606 | connectedhomeip | Apache License 2.0 |
sample/src/main/java/com/udfsoft/androidinfo/sample/ui/adapter/MapAdapter.kt | LiteSoftware | 550,715,360 | false | {"Kotlin": 127152} | /*
* Copyright 2022 Javavirys
*
* 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.udfsoft.androidinfo.sample.ui.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.udfsoft.androidinfo.sample.R
class MapAdapter : RecyclerView.Adapter<MapViewHolder>() {
private val items = mutableMapOf<String, Any?>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MapViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.layout_info_item, parent, false)
return MapViewHolder(view)
}
override fun onBindViewHolder(holder: MapViewHolder, position: Int) {
val name = items.keys.elementAt(position)
holder.onBind(name to items[name])
}
override fun getItemCount() = items.size
@SuppressLint("NotifyDataSetChanged")
fun setItems(map: Map<String, Any?>) {
items.clear()
items.putAll(map)
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 3 | 1c87c9c9f5e830a444ac6e6319f8eed50ddc5977 | 1,606 | AndroidInfoLib | Apache License 2.0 |
src/main/kotlin/id/walt/model/VerifiableCredentialModel.kt | walt-id | 392,607,264 | false | {"Kotlin": 1154151, "Java": 9175, "Open Policy Agent": 2974, "Shell": 2842, "Dockerfile": 1615, "JavaScript": 891, "Python": 351} | package id.walt.model
import id.walt.credentials.w3c.VerifiableCredential
import kotlinx.serialization.Serializable
@Serializable
data class VerifiableCredentialModel(
val type: List<String>,
val id: String,
val issuer: String,
val subject: String,
val issuedOn: String
) {
constructor(verifiableCredential: VerifiableCredential) : this(
verifiableCredential.type,
verifiableCredential.id.toString(),
verifiableCredential.issuerId.toString(),
verifiableCredential.subjectId.toString(),
verifiableCredential.issued.toString()
)
}
| 5 | Kotlin | 33 | 95 | a533315d1239271d53e7715bf10381cfd9259633 | 599 | waltid-ssikit | Apache License 2.0 |
app/src/main/java/org/simple/clinic/sync/indicator/SyncIndicatorConfig.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.sync.indicator
import java.time.Duration
import java.time.temporal.ChronoUnit
data class SyncIndicatorConfig(val syncFailureThreshold: Duration) {
companion object {
fun read() =
SyncIndicatorConfig(syncFailureThreshold = Duration.of(12, ChronoUnit.HOURS))
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 306 | simple-android | MIT License |
modules/library-network/src/main/kotlin/com/leinardi/forlago/library/network/interactor/StoreCertificatePinningEnabledInteractorImpl.kt | leinardi | 405,185,933 | false | {"Kotlin": 594315, "Shell": 3032} | /*
* Copyright 2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.leinardi.forlago.library.network.interactor
import com.leinardi.forlago.library.network.api.interactor.StoreCertificatePinningEnabledInteractor
import com.leinardi.forlago.library.preferences.api.di.App
import com.leinardi.forlago.library.preferences.api.repository.DataStoreRepository
import javax.inject.Inject
internal class StoreCertificatePinningEnabledInteractorImpl @Inject constructor(
@App private val appDataStoreRepository: DataStoreRepository,
) : StoreCertificatePinningEnabledInteractor {
override suspend operator fun invoke(isEnabled: Boolean) {
appDataStoreRepository.storeValue(ReadCertificatePinningEnabledInteractorImpl.CERTIFICATE_PINNING_ENABLED, isEnabled)
}
}
| 1 | Kotlin | 2 | 8 | 8098e124d1ae185d8777df3b5935db27bcc667f2 | 1,321 | Forlago | Apache License 2.0 |
android/wallet/history/WalletHistoryFragment.kt | Partner-Angola | 442,977,333 | false | {"Swift": 444824, "Kotlin": 314181} | package com.joeware.android.gpulumera.account.wallet.history
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.joeware.android.gpulumera.account.wallet.model.EthHistory
import com.joeware.android.gpulumera.account.wallet.model.EthTokenHistory
import com.joeware.android.gpulumera.account.wallet.model.SolHistory
import com.joeware.android.gpulumera.account.wallet.model.WalletHistoryType
import com.joeware.android.gpulumera.base.BaseFragment
import com.joeware.android.gpulumera.databinding.FragmentWalletHistoryBinding
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class WalletHistoryFragment : BaseFragment() {
private lateinit var binding: FragmentWalletHistoryBinding
private val viewModel: WalletHistoryViewModel by viewModel()
private var historyType: WalletHistoryType? = null
override fun setBinding(inflater: LayoutInflater, container: ViewGroup?): View {
binding = FragmentWalletHistoryBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.vm = viewModel
historyType = when(arguments?.getString("type")) {
WalletHistoryType.ETH_ANG.name -> {
binding.adapter = WalletHistoryAdapter<EthTokenHistory>().apply { setHistoryType(WalletHistoryType.ETH_ANG) }
WalletHistoryType.ETH_ANG
}
WalletHistoryType.ETH.name -> {
binding.adapter = WalletHistoryAdapter<EthHistory>().apply { setHistoryType(WalletHistoryType.ETH) }
WalletHistoryType.ETH
}
WalletHistoryType.SOL_ANG.name -> {
binding.adapter = WalletHistoryAdapter<SolHistory>().apply { setHistoryType(WalletHistoryType.SOL_ANG) }
WalletHistoryType.SOL_ANG
}
WalletHistoryType.SOL.name -> {
binding.adapter = WalletHistoryAdapter<SolHistory>().apply { setHistoryType(WalletHistoryType.SOL) }
WalletHistoryType.SOL
}
else -> null
}
return binding.root
}
override fun setObserveData() {
viewModel.ethItems.observe(this) { binding.adapter?.setItems(it) }
viewModel.ethTokenItems.observe(this) { binding.adapter?.setItems(it) }
viewModel.solItems.observe(this) { binding.adapter?.setItems(it) }
}
override fun init() {
viewModel.getWalletHistory(historyType)
}
} | 0 | Swift | 1 | 3 | e3c826b32475038db3b3e9b5a542adcbe2cd44ae | 2,527 | wallet | Apache License 2.0 |
compiler/test/data/typescript/node_modules/overloads/overloadAmbiguities.d.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | // [test] overloadAmbiguities.module_resolved_name.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
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.*
external interface A
external interface B
external interface C
external interface StaticApi {
@nativeInvoke
operator fun invoke(selector: String, context: A = definedExternally): A
@nativeInvoke
operator fun invoke(selector: String): A
@nativeInvoke
operator fun invoke(selector: String, context: B = definedExternally): A
@nativeInvoke
operator fun invoke(element: B): A
@nativeInvoke
operator fun invoke(): A
@nativeInvoke
operator fun invoke(html: String, ownerDocument: C = definedExternally): A
@nativeInvoke
operator fun invoke(html: String, attributes: Any): A
}
external fun ping(a: Number, b: Number, c: Number, d: Number = definedExternally, e: Number = definedExternally, f: Number = definedExternally)
external fun ping(a: Number, b: Number, c: Number)
external fun ping(a: Number, b: Number, c: Number, d: Number = definedExternally)
external fun ping(a: Number, b: Number, c: Number, d: Number = definedExternally, e: Number = definedExternally)
external fun ping(id: String)
external interface Extreme {
fun pong(o: A = definedExternally)
fun pong()
fun pong(o: B = definedExternally)
fun ping(a: String, b: A = definedExternally)
fun ping(a: String)
fun ping(a: String, b: B = definedExternally)
fun foo(a: Number, b: Number, c: Number, d: Number = definedExternally, e: Number = definedExternally, f: Number = definedExternally)
fun foo(a: Number, b: Number, c: Number)
fun foo(a: Number, b: Number, c: Number, d: Number = definedExternally)
fun foo(a: Number, b: Number, c: Number, d: Number = definedExternally, e: Number = definedExternally)
fun foo(a: String)
}
external interface Simple {
fun ping(a: String, b: A = definedExternally)
fun foo(a: Number, b: Number, c: Number, d: Number = definedExternally, e: Number = definedExternally, f: Number = definedExternally)
}
external open class BaseApi {
open fun register(preference: String /* "A" | "B" | "C" */ = definedExternally)
open fun completelyOptional(a: Number = definedExternally, b: Number = definedExternally, c: Number = definedExternally)
open fun completelyOptional()
open fun completelyOptional(a: Number = definedExternally)
open fun completelyOptional(a: Number = definedExternally, b: Number = definedExternally)
open fun completelyOptional(a: Number = definedExternally, b: Number = definedExternally, c: String = definedExternally)
open fun completelyOptional(a: Number = definedExternally, b: Number = definedExternally, c: Boolean = definedExternally)
}
external open class SimpleApi(a: String = definedExternally) : BaseApi | 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 3,180 | dukat | Apache License 2.0 |
sentry-samples/sentry-samples-spring-boot/src/test/kotlin/io/sentry/systemtest/GraphqlGreetingSystemTest.kt | getsentry | 3,368,190 | false | {"Kotlin": 2735935, "Java": 2328800, "C": 18038, "Python": 3773, "Shell": 3032, "Makefile": 1930, "CMake": 985, "C++": 703} | package io.sentry.systemtest
import io.sentry.systemtest.util.TestHelper
import org.junit.Before
import kotlin.test.Test
class GraphqlGreetingSystemTest {
lateinit var testHelper: TestHelper
@Before
fun setup() {
testHelper = TestHelper("http://localhost:8080")
}
@Test
fun `greeting works`() {
testHelper.snapshotEnvelopeCount()
val response = testHelper.graphqlClient.greet("world")
testHelper.ensureNoErrors(response)
testHelper.ensureEnvelopeCountIncreased()
}
@Test
fun `greeting error`() {
testHelper.snapshotEnvelopeCount()
val response = testHelper.graphqlClient.greet("crash")
testHelper.ensureErrorCount(response, 1)
testHelper.ensureEnvelopeCountIncreased()
}
}
| 205 | Kotlin | 472 | 1,067 | 5e04ee8e63c5617dbc4c2b9706b866e8823cec20 | 795 | sentry-java | MIT License |
src/test/kotlin/unit/WhoIsThereTest.kt | http4k | 91,459,926 | false | {"Kotlin": 43878, "HTML": 4048, "Handlebars": 1903, "CSS": 169, "Shell": 168} | package unit
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.testing.Approver
import org.http4k.testing.JsonApprovalTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import verysecuresystems.EmailAddress
import verysecuresystems.Id
import verysecuresystems.User
import verysecuresystems.Username
import verysecuresystems.api.WhoIsThere
@ExtendWith(JsonApprovalTest::class)
class WhoIsThereTest {
private val user = User(Id(1), Username("bob"), EmailAddress("a@b"))
@Test
fun `no users`(approver: Approver) {
val app = WhoIsThere(emptyList()) { user }
approver.assertApproved(app(Request(GET, "/whoIsThere")))
}
@Test
fun `there are users`(approver: Approver) {
val app = WhoIsThere(listOf(user.name)) { user }
approver.assertApproved(app(Request(GET, "/whoIsThere")))
}
} | 2 | Kotlin | 8 | 54 | 4dc46bb9c9075b92aa43e0982f0fbc92a20ae1f0 | 910 | http4k-by-example | Apache License 2.0 |
compiler/testData/diagnostics/tests/typealias/localTypeAliasRecursive.fir.kt | android | 263,405,600 | true | null | // !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_PARAMETER -TOPLEVEL_TYPEALIASES_ONLY
fun outer() {
typealias Test1 = Test1
typealias Test2 = List<Test2>
typealias Test3<T> = List<Test3<T>>
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 197 | kotlin | Apache License 2.0 |
app/src/test/java/com/radixdlt/android/apps/wallet/extension/ImmediateSchedulersExtension.kt | radixdlt | 158,528,536 | false | null | package com.radixdlt.android.apps.wallet.extension
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.ExtensionContext
class ImmediateSchedulersExtension : BeforeAllCallback, AfterAllCallback {
override fun beforeAll(context: ExtensionContext?) {
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() }
}
override fun afterAll(context: ExtensionContext?) {
RxJavaPlugins.reset()
}
}
| 1 | Kotlin | 4 | 16 | 2fa15c9b2d65040072cbb413a3549f8f489ed6ca | 771 | radixdlt-wallet-android | MIT License |
src/test/kotlin/TransformIfTests.kt | fada21 | 603,530,493 | false | null | import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class TransformIfTests {
@Test
fun `should transform if condition met`() {
0.transformIf(isEven) { plus(1) } shouldBe 1
}
@Test
fun `should not transform if condition not met`() {
1.transformIf(isEven) { plus(1) } shouldBe 1
}
@Test
fun `should transform nullable`() {
val address: String? = null
address.transformIf({ !isNullOrEmpty() }) { (this as String).trim() } shouldBe null
}
@Test
fun `should transform not null nullable`() {
val address: String? = " some address "
address.transformIf({ !isNullOrEmpty() }) { (this as String).trim() } shouldBe "some address"
}
}
private val isEven: (Int) -> Boolean = { it.mod(2) == 0 }
private val isOdd: (Int) -> Boolean = { it.mod(2) == 1 } | 0 | Kotlin | 0 | 0 | b23b16823ad8fbeeb0786053daec188b80afc385 | 943 | funs | MIT License |
app/src/main/java/com/lighttigerxiv/simple/mp/compose/frontend/screens/setup/welcome/WelcomeScreen.kt | jpbandroid | 733,977,750 | false | {"Kotlin": 458602} | package com.jpb.music.compose.frontend.screens.setup.welcome
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.jpb.music.compose.R
import com.jpb.music.compose.frontend.composables.PrimaryButton
import com.jpb.music.compose.frontend.navigation.goToPermissions
import com.jpb.music.compose.frontend.utils.Sizes
@Composable
fun WelcomeScreen(
navController: NavHostController
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(Sizes.LARGE)
) {
Column(
modifier = Modifier
.fillMaxSize()
.weight(1f, fill = true),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
modifier = Modifier.size(100.dp),
painter = painterResource(id = R.drawable.play_empty),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Text(
text = stringResource(id = R.string.title_welcome),
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
color = MaterialTheme.colorScheme.primary
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
PrimaryButton(text = stringResource(id = R.string.next)) {
navController.goToPermissions()
}
}
}
} | 0 | Kotlin | 0 | 0 | e53569c3ebe0cba05a70519805ffb6c97137fe1e | 2,383 | jpbMusic-Compose | MIT License |
app/src/main/java/com/zerowater/environment/ui/Binding.kt | byzerowater | 264,695,996 | false | null | package com.zerowater.environment.ui
import android.os.Build
import android.text.Html
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.NestedScrollView
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingMethod
import androidx.databinding.InverseBindingMethods
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.SimpleItemAnimator
import timber.log.Timber
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Environment
* Class: Binding
* Created by ZERO on 2020-05-19.
* zero company Ltd
* <EMAIL>
* Description:
*/
/**
* 뷰 가시성 상태 설정
*
* @param view View
* @param gone true 미노출, false 노출
*/
@BindingAdapter("visibleGone")
fun setVisibleGone(view: View, gone: Boolean) {
view.visibility = if (gone) View.GONE else View.VISIBLE
}
/**
* RecyclerViewBindingAdapters
*/
@InverseBindingMethods(
InverseBindingMethod(type = RecyclerView::class, attribute = "android:recyclerViewAdapter"),
InverseBindingMethod(type = RecyclerView::class, attribute = "android:supportsChangeAnimations"),
InverseBindingMethod(type = RecyclerView::class, attribute = "android:itemAnimator"),
InverseBindingMethod(type = RecyclerView::class, attribute = "android:itemDecoration"),
InverseBindingMethod(type = RecyclerView::class, attribute = "android:items"))
class RecyclerViewBindingAdapters {
companion object {
/**
* 어답터 설정
*
* @param recyclerView RecyclerView
* @param adapter 설정할 어답터
*/
@JvmStatic
@BindingAdapter("android:recyclerViewAdapter")
fun setRecyclerViewAdapter(recyclerView: RecyclerView, adapter: RecyclerView.Adapter<*>?) {
adapter?.let {
recyclerView.adapter = it
}
}
/**
* 아이템 데코레이션 설정
*
* @param recyclerView RecyclerView
* @param itemDecoration 설정할 데코레이션
*/
@JvmStatic
@BindingAdapter("android:itemDecoration")
fun addItemDecoration(recyclerView: RecyclerView, itemDecoration: ItemDecoration?) {
itemDecoration?.let {
recyclerView.addItemDecoration(itemDecoration)
}
}
/**
* 애니메이션 지원 여부 설정
*
* @param recyclerView RecyclerView
* @param supportsChangeAnimations true 애니메이션 지원, false 애니메이션 미지원.
*/
@JvmStatic
@BindingAdapter("android:supportsChangeAnimations")
fun setSupportsChangeAnimations(recyclerView: RecyclerView, supportsChangeAnimations: Boolean) {
Timber.i("supportsChangeAnimations %s", supportsChangeAnimations)
val animator = recyclerView.itemAnimator
if (animator is SimpleItemAnimator) {
Timber.i("SimpleItemAnimator %s", supportsChangeAnimations)
animator.supportsChangeAnimations = supportsChangeAnimations
}
}
/**
* 애니메이션 설정
*
* @param recyclerView RecyclerView
* @param useItemAnimator true DefaultItemAnimator 설정, false 미설정
*/
@JvmStatic
@BindingAdapter("android:itemAnimator")
fun setItemAnimator(recyclerView: RecyclerView, useItemAnimator: Boolean) {
Timber.i("useItemAnimator %s", useItemAnimator)
recyclerView.itemAnimator = if (useItemAnimator) DefaultItemAnimator() else null
}
/**
* 아이템 설정
*
* @param recyclerView RecyclerView
* @param adapter RecyclerView.Adapter
* @param dataList 설정할 아이템
*/
@JvmStatic
@BindingAdapter("android:recyclerViewAdapter", "android:items")
fun bindItem(recyclerView: RecyclerView, adapter: ListAdapter<Nothing, Nothing>?, dataList: List<Nothing>?) {
var varAdapter = adapter
val oldAapater = recyclerView.adapter
if (oldAapater != null) {
varAdapter = oldAapater as ListAdapter<Nothing, Nothing>
} else {
recyclerView.adapter = varAdapter
}
dataList?.let {
varAdapter?.submitList(dataList as List<Nothing>?)
}
}
}
}
/**
* NestedScrollViewViewBindingAdapters
*/
@InverseBindingMethods(
InverseBindingMethod(type = NestedScrollView::class, attribute = "android:openKeyboard"))
class NestedScrollViewViewBindingAdapters {
companion object {
/**
* 키보드 상태에 따라 스크롤 설정
*
* @param nestedScrollView NestedScrollView
* @param isOpen 키보드 열린 상태
*/
@JvmStatic
@BindingAdapter("android:openKeyboard")
fun setOpenKeyboard(nestedScrollView: NestedScrollView, isOpen: Boolean) {
if (isOpen)
nestedScrollView.post(Runnable {
nestedScrollView.scrollTo(0, nestedScrollView.bottom)
})
}
}
}
/**
* TextViewBindingAdapters
*/
@InverseBindingMethods(
InverseBindingMethod(type = TextView::class, attribute = "android:htmlText"),
InverseBindingMethod(type = TextView::class, attribute = "android:htmlTextHint"),
InverseBindingMethod(type = TextView::class, attribute = "android:currentFormat"),
InverseBindingMethod(type = TextView::class, attribute = "android:parseFormat"),
InverseBindingMethod(type = TextView::class, attribute = "android:date"))
class TextViewBindingAdapters {
companion object {
/**
* HTML형식 텍스트 변환
*
* @param view TextView
* @param text html 텍스트
*/
@JvmStatic
@BindingAdapter("android:htmlText")
fun setHtmlText(view: TextView, text: String?) {
text?.let {
val htmlText = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) Html.fromHtml(text) else Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)
view.text = htmlText
}
}
/**
* HTML형식 텍스트 변환
*
* @param view TextView
* @param text html 텍스트
*/
@JvmStatic
@BindingAdapter("android:htmlTextHint")
fun setHtmlTextHint(view: TextView, text: String?) {
text?.let {
val htmlText = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) Html.fromHtml(text) else Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)
view.hint = htmlText
}
}
/**
* HTML형식 텍스트 변환
*
* @param view TextView
* @param text html 텍스트
*/
@JvmStatic
@BindingAdapter("android:date", "android:currentFormat", "android:parseFormat")
fun convertDateFormat(view: TextView, date: String?, currentFormat: String?, parseFormat: String?) {
var parseDate: String? = date
if (!date.isNullOrBlank()) {
try {
val curSdf = SimpleDateFormat(currentFormat, Locale.getDefault())
val parSdf = SimpleDateFormat(parseFormat, Locale.getDefault())
parseDate = parSdf.format(curSdf.parse(date))
} catch (e: ParseException) {
Timber.e(e)
}
}
view.text = parseDate
}
}
}
/**
* ImageViewBindingAdapters
*/
@InverseBindingMethods(
InverseBindingMethod(type = ImageView::class, attribute = "android:iconImage"))
class ImageViewBindingAdapters {
companion object {
/**
* 벡터 이미지 로드
*
* @param imageView ImageView
* @param resource Int 이미지 이름
*/
@JvmStatic
@BindingAdapter("android:iconImage")
fun setIconImage(imageView: ImageView, resource: Int) {
imageView.setImageResource(resource)
}
}
}
| 0 | Kotlin | 0 | 0 | 3139da828c309cee13c0eaf3b8ce9a24ce151c5c | 8,553 | Environment3 | Apache License 2.0 |
src/commonMain/kotlin/io/grule/parser/ParserMatcherString.kt | 7hens | 376,845,987 | false | null | package io.grule.parser
import io.grule.node.KeyOwner
internal class ParserMatcherString(val text: String) : ParserMatcher {
override fun match(status: ParserStatus): ParserStatus {
val token = status.peek()
if (token.text == text) {
return status.next(KeyOwner(text).newNode(token))
}
status.panic(text)
}
override fun toString(): String {
return text
}
} | 0 | Kotlin | 0 | 1 | 3c00cfd151e78515a93f20a90369e43dd3b75f73 | 428 | grule | Apache License 2.0 |
core/src/main/kotlin/net/dontdrinkandroot/wicket/behavior/TitleModifier.kt | dontdrinkandroot | 7,002,436 | false | null | package net.dontdrinkandroot.wicket.behavior
import org.apache.wicket.AttributeModifier
import org.apache.wicket.model.IModel
import org.apache.wicket.model.Model
/**
* Sets the <tt>title</tt> attribute of an element.
*/
class TitleModifier : AttributeModifier {
constructor(title: IModel<*>?) : super("title", title)
constructor(title: String) : super("title", Model<String>(title))
}
fun title(title: String) = TitleModifier(title)
fun title(title: IModel<String>) = TitleModifier(title) | 35 | Kotlin | 0 | 3 | eaf007cfe70a136a334bd9cb22b5cc0e2fa50ff3 | 504 | wicket.java | Apache License 2.0 |
features/library/src/main/java/taiwan/no/one/feat/library/presentation/recyclerviews/viewholders/TrackViewHolder.kt | pokk | 263,073,196 | false | null | /*
* MIT License
*
* Copyright (c) 2021 Jieyi
*
* 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 taiwan.no.one.feat.library.presentation.recyclerviews.viewholders
import androidx.core.content.ContextCompat
import coil.load
import taiwan.no.one.dropbeat.AppResDrawable
import taiwan.no.one.dropbeat.databinding.ItemTypeOfMusicBinding
import taiwan.no.one.entity.SimpleTrackEntity
import taiwan.no.one.feat.library.presentation.recyclerviews.adapters.TrackAdapter
import taiwan.no.one.widget.recyclerviews.ViewHolderBinding
internal class TrackViewHolder(
private val binding: ItemTypeOfMusicBinding,
) : ViewHolderBinding<SimpleTrackEntity, TrackAdapter>(binding.root) {
companion object Constant {
private const val EMPTY_THUMB_URI =
"https://lastfm.freetls.fastly.net/i/u/34s/2a96cbd8b46e442fc41c2b86b821562f.png"
}
override fun initView(entity: SimpleTrackEntity, adapter: TrackAdapter) {
binding.apply {
mtvNumber.text = "#${absoluteAdapterPosition + 1}"
sivAlbumThumb.load(entity.thumbUri)
mtvAlbumName.text = entity.name
mtvArtistName.text = entity.artist
setFavoriteIcon(entity.isFavorite)
// Request the track thumb.
if (entity.thumbUri == EMPTY_THUMB_URI) {
adapter.requestPictureCallback?.invoke(entity)
}
btnOption.setOnClickListener { adapter.optionListener?.invoke(it, entity) }
btnFavorite.setOnClickListener {
entity.isFavorite = !entity.isFavorite
setFavoriteIcon(entity.isFavorite)
adapter.favoriteListener?.invoke(entity)
}
root.setOnClickListener { adapter.clickListener?.invoke(entity) }
}
}
private fun setFavoriteIcon(isFavorite: Boolean) {
binding.btnFavorite.icon = ContextCompat.getDrawable(
context,
if (isFavorite) AppResDrawable.ic_heart_solid else AppResDrawable.ic_heart
)
}
}
| 2 | Kotlin | 3 | 16 | 6d173194dcd3c44db46dfe6b0ef691b9322da975 | 3,062 | DropBeat | MIT License |
app/src/androidTest/java/com/jpp/mp/extras/test_extensions.kt | perettijuan | 156,444,935 | false | null | package com.jpp.mp.extras
import android.app.Activity
import androidx.test.rule.ActivityTestRule
import com.jpp.mpdomain.Movie
import com.jpp.mpdomain.MoviePage
/**
* Extension function to launch the Activity under test.
*/
fun <T : Activity> ActivityTestRule<T>.launch() {
launchActivity(android.content.Intent())
}
fun moviesPages(totalPages: Int): List<MoviePage> {
return mutableListOf<MoviePage>().apply {
for (i in 1..totalPages) {
add(createMoviesPage(i, 10))
}
}
}
fun createMoviesPage(page: Int, totalResults: Int) = MoviePage(
page = page,
results = createMoviesForPage(page, totalResults),
total_pages = 10,
total_results = 1000
)
private fun createMoviesForPage(page: Int, totalResults: Int = 10): List<Movie> {
return mutableListOf<Movie>().apply {
for (i in 1..totalResults) {
add(Movie(
id = (page + i).toDouble(),
poster_path = "/m110vLaDDOCca4hfOcS5mK5cDke.jpg",
backdrop_path = "/m110vLaDDOCca4hfOcS5mK5cDke.jpg",
title = "Movie $i",
original_title = "Movie Title $i",
original_language = "US",
overview = "Overview for $i",
release_date = "aReleaseDate for $i",
vote_count = i.toDouble(),
vote_average = i.toFloat(),
popularity = i.toFloat()
))
}
}
}
| 9 | Kotlin | 7 | 46 | 7921806027d5a9b805782ed8c1cad447444f476b | 1,517 | moviespreview | Apache License 2.0 |
src/main/kotlin/com/github/fantom/codeowners/lang/kind/bitbucket/psi/CodeownersRuleBase.kt | fan-tom | 325,829,611 | false | {"Kotlin": 257763, "Lex": 5866, "HTML": 966} | package com.github.fantom.codeowners.lang.kind.bitbucket.psi
import com.github.fantom.codeowners.lang.CodeownersRuleBase as CommonCodeownersRuleBase
interface CodeownersRuleBase : CommonCodeownersRuleBase<CodeownersPattern, CodeownersOwner>
| 22 | Kotlin | 4 | 15 | f898c1113f2f81b25aaeb6ba87f8e570da0ba08e | 243 | intellij-codeowners | MIT License |
app/src/main/java/com/example/wordconnector/MainActivity.kt | rahulsrma26 | 234,875,903 | false | null | package com.example.wordconnector
import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
private var buttonStateNext = false
object PermissionConstants {
const val READ_REQUEST_CODE = 101
const val WRITE_REQUEST_CODE = 102
}
private val tag = "MainActivity"
private fun fetchQuestionAnswer() {
var questionTxt = findViewById<TextView>(R.id.txtQuestion)
var answerTxt = findViewById<TextView>(R.id.txtAnswer)
val (k, v) = Logic.getRandomQA()
questionTxt.text = k
answerTxt.text = v
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
setupPermissions()
var buttonChange = findViewById<Button>(R.id.btnNext)
var answerTxt = findViewById<TextView>(R.id.txtAnswer)
Logic.loadData(applicationContext)
fetchQuestionAnswer()
buttonChange.setOnClickListener {
buttonStateNext = !buttonStateNext
if (buttonStateNext) {
answerTxt.visibility = View.VISIBLE
buttonChange.setText(R.string.next)
} else {
answerTxt.visibility = View.INVISIBLE
fetchQuestionAnswer()
buttonChange.setText(R.string.show)
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> {
return true
}
R.id.action_add -> {
var intent = Intent(this@MainActivity, AddWordActivity::class.java)
startActivity(intent)
return true
}
R.id.action_export -> {
Logic.exportData()
Toast.makeText(applicationContext, "Exported", Toast.LENGTH_LONG).show()
return true
}
R.id.action_import -> {
Logic.importData()
Logic.saveData(applicationContext)
Toast.makeText(applicationContext, "Imported", Toast.LENGTH_LONG).show()
return true
}
else -> super.onOptionsItemSelected(item)
}
}
// override fun onRequestPermissionsResult(
// requestCode: Int,
// permissions: Array<String>,
// grantResults: IntArray
// ) {
// when (requestCode) {
// READ_REQUEST_CODE -> {
// if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
// Log.i(TAG, READ_REQUEST_CODE.toString() + " Permission has been denied by user")
// } else {
// Log.i(
// TAG,
// READ_REQUEST_CODE.toString() + " Permission has been granted by user"
// )
// }
// }
// WRITE_REQUEST_CODE -> {
// if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
// Log.i(
// TAG,
// WRITE_REQUEST_CODE.toString() + " Permission has been denied by user"
// )
// } else {
// Log.i(
// TAG,
// WRITE_REQUEST_CODE.toString() + " Permission has been granted by user"
// )
// }
// }
// }
// }
private fun setupPermissions() {
val readPermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
)
if (readPermission != PackageManager.PERMISSION_GRANTED) {
Log.i(tag, "Permission to READ_EXTERNAL_STORAGE denied")
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
)
) {
val builder = AlertDialog.Builder(this)
builder.setMessage("Permission to read the storage is required for this app to import.")
.setTitle("Permission required")
builder.setPositiveButton(
"OK"
) { _, _ ->
Log.i(tag, "Clicked")
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PermissionConstants.READ_REQUEST_CODE
)
}
val dialog = builder.create()
dialog.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PermissionConstants.READ_REQUEST_CODE
)
}
}
val writePermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
if (writePermission != PackageManager.PERMISSION_GRANTED) {
Log.i(tag, "Permission to WRITE_EXTERNAL_STORAGE denied")
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
val builder = AlertDialog.Builder(this)
builder.setMessage("Permission to write the storage is required for this app to export.")
.setTitle("Permission required")
builder.setPositiveButton(
"OK"
) { _, _ ->
Log.i(tag, "Clicked")
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PermissionConstants.WRITE_REQUEST_CODE
)
}
val dialog = builder.create()
dialog.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PermissionConstants.WRITE_REQUEST_CODE
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6217824ae1858e1f0f7f8257b5bf25fd936278ea | 7,449 | WordConnector | MIT License |
compiler/testData/diagnostics/tests/dataFlow/WhenSubject.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | interface Expr
class BinOp(val operator : String) : Expr
fun test(e : Expr) {
if (e is BinOp) {
when (<!DEBUG_INFO_SMARTCAST!>e<!>.operator) {
else -> 0
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 196 | kotlin | Apache License 2.0 |
app/src/main/java/com/worldofplay/app/WorldOfPlayApp.kt | anil-gudigar | 254,635,237 | false | null | package com.worldofplay.app
import com.facebook.stetho.Stetho
import com.worldofplay.app.di.AppInjector
import com.worldofplay.core.BaseApp
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import javax.inject.Inject
class WorldOfPlayApp : BaseApp(), HasAndroidInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
override fun onCreate() {
super.onCreate()
AppInjector.init(this)
initializeStetho()
}
override fun androidInjector(): AndroidInjector<Any> = dispatchingAndroidInjector
private fun initializeStetho() {
//Stetho helps debug network calls and database / preference values
if (BuildConfig.DEBUG) Stetho.initializeWithDefaults(this)
}
} | 0 | Kotlin | 1 | 0 | fcab97b8d15bf538594f4f581e68bd5bb7a00fb2 | 840 | worldofplay | Apache License 2.0 |
library/src/main/java/com/xiangning/sectionadapter/SimpleItemBinder.kt | xiangning17 | 228,197,397 | false | null | package com.xiangning.sectionadapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.xiangning.sectionadapter.core.ItemBinder
/**
* @author xiangning
* @Date 2019-11-22
* @description 方便创建ItemBinder的工具类
*/
open class SimpleItemBinder<T : Any>() : ItemBinder<T, GeneralViewHolder>() {
private var layout: Int = 0
private var viewProvider: ((inflater: LayoutInflater, parent: ViewGroup) -> View)? = null
private var bindHolder: ((holder: GeneralViewHolder, item: T) -> Unit)? = null
@JvmOverloads
constructor(
@LayoutRes layout: Int,
bindHolder: ((holder: GeneralViewHolder, item: T) -> Unit)? = null
) : this(layout, null, bindHolder)
@JvmOverloads
constructor(
viewProvider: ((inflater: LayoutInflater, parent: ViewGroup) -> View),
bindHolder: ((holder: GeneralViewHolder, item: T) -> Unit)? = null
) : this(0, viewProvider, bindHolder)
private constructor(
@LayoutRes layout: Int = 0,
viewProvider: ((inflater: LayoutInflater, parent: ViewGroup) -> View)? = null,
bindHolder: ((holder: GeneralViewHolder, item: T) -> Unit)? = null
) : this() {
check(layout != 0 || viewProvider != null)
this.layout = layout
this.viewProvider = viewProvider
this.bindHolder = bindHolder
}
override fun onCreateViewHolder(
inflater: LayoutInflater,
parent: ViewGroup
): GeneralViewHolder {
return GeneralViewHolder(
viewProvider?.invoke(inflater, parent) ?: inflater.inflate(
layout,
parent,
false
)
)
}
override fun onBindViewHolder(holder: GeneralViewHolder, item: T) {
bindHolder?.invoke(holder, item)
}
} | 0 | Kotlin | 0 | 3 | e64449200b618b270f4bb33b71bbb30681d2f598 | 1,880 | sectionadapter | Apache License 2.0 |
app/src/main/java/xyz/khodok/khoblog/di/GlideAppModule.kt | Khoding | 374,429,520 | false | null | package xyz.khodok.khoblog.di
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
@GlideModule
class GlideAppModule : AppGlideModule() | 0 | Kotlin | 0 | 1 | d8dff19d64bcde15c87ea2bda54e8291c4c882df | 181 | khoBlogAndroid | Apache License 2.0 |
tinderswipe/src/main/java/com/kidach1/tinderswipe/model/CardModel.kt | kidach1 | 55,330,387 | false | null | package com.kidach1.tinderswipe.model
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import com.kidach1.tinderswipe.view.CardContainer
class CardModel(var name: String, var description: String, var cardImageUrl: String) {
var onCardDismissedListener: OnCardDismissedListener? = null
var onClickListener: OnClickListener? = null
interface OnCardDismissedListener {
fun onLike(callback: CardContainer.OnLikeListener)
fun onDislike()
}
interface OnClickListener {
fun OnClickListener()
}
}
| 0 | Kotlin | 3 | 37 | b5b9960f92f5a12f4b60d1ef6e38cf1066752dbb | 637 | AndroidTinderSwipe | Apache License 2.0 |
app/src/main/kotlin/me/xizzhu/android/joshua/settings/widgets/SettingSectionHeader.kt | xizzhu | 173,533,770 | false | null | /*
* Copyright (C) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.xizzhu.android.joshua.settings.widgets
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.annotation.Px
import androidx.annotation.RequiresApi
import me.xizzhu.android.joshua.R
import me.xizzhu.android.joshua.databinding.InnerSettingSectionHeaderBinding
import me.xizzhu.android.joshua.ui.setText
class SettingSectionHeader : FrameLayout {
private val viewBinding: InnerSettingSectionHeaderBinding = InnerSettingSectionHeaderBinding.inflate(LayoutInflater.from(context), this)
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
attrs?.let { context.obtainStyledAttributes(it, R.styleable.SettingSectionHeader) }
?.run {
viewBinding.title.setText(this, R.styleable.SettingSectionHeader_settingSectionHeaderTitle)
recycle()
}
}
fun setTextSize(@Px textSize: Int) {
viewBinding.title.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toFloat())
}
}
| 24 | Kotlin | 7 | 26 | db43163619c37fd7febd208eb7bde2ffefc4fa99 | 2,295 | Joshua | Apache License 2.0 |
app/src/main/java/com/brins/nba/api/result/LiveResultData.kt | BrinsLee | 278,326,885 | false | null | package com.brins.nba.api.result
import com.google.gson.annotations.SerializedName
/**
* @author lipeilin
* @date 2020/7/10
*/
class LiveResultData {
var data: LiveInfo? = null
class LiveInfo {
@SerializedName("cur_date")
var currentDate: String = ""
@SerializedName("pre_date")
var preDate: String = ""
@SerializedName("next_date")
var nextDate: String = ""
}
var msg = ""
var code = 0
} | 0 | Kotlin | 0 | 0 | 33f09a1ec45da1a2996bf24b30a84589330c85c4 | 467 | nba | Apache License 2.0 |
data/mongo/src/main/java/com/imnidasoftware/mongo/database/ImagesDatabase.kt | Lastlilith | 625,898,917 | false | null | package com.imnidasoftware.mongo.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.imnidasoftware.mongo.database.entity.ImageToDelete
import com.imnidasoftware.mongo.database.entity.ImageToUpload
@Database(
entities = [ImageToUpload::class, ImageToDelete::class],
version = 2,
exportSchema = false
)
abstract class ImagesDatabase: RoomDatabase() {
abstract fun imageToUploadDao(): ImageToUploadDao
abstract fun imageToDeleteDao(): ImageToDeleteDao
} | 0 | Kotlin | 0 | 0 | f15d21637a94e66b49d5952b2b8afcf1ac692ab1 | 505 | DayDiary | MIT License |
app/src/main/java/com/rewardtodo/presentation/todolist/TodolistViewModelFactory.kt | mattrob33 | 241,623,871 | false | null | package com.rewardtodo.presentation.todolist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.rewardtodo.cache.PreferencesHelper
import com.rewardtodo.data.repo.TodoRepository
import com.rewardtodo.data.repo.UserRepository
import com.rewardtodo.global.UserManager
import javax.inject.Inject
class TodolistViewModelFactory @Inject constructor (
private val userManager: UserManager,
private val userRepo: UserRepository,
private val todoRepo: TodoRepository,
private val prefs: PreferencesHelper
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return TodolistViewModel(userManager, userRepo, todoRepo, prefs) as T
}
} | 0 | Kotlin | 0 | 0 | eefb7aade1c43be3e32dedc83bffb6145fcc37e1 | 741 | reward | Apache License 2.0 |
app/src/main/java/io/lerk/lrkFM/activities/file/ContextMenuUtil.kt | lfuelling | 122,087,128 | false | {"Kotlin": 184967, "Java": 2298} | package io.lerk.lrkFM.activities.file
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.ContextMenu
import android.view.MenuItem
import android.widget.EditText
import android.widget.Toast
import io.lerk.lrkFM.Pref
import io.lerk.lrkFM.R
import io.lerk.lrkFM.adapter.ArchiveArrayAdapter
import io.lerk.lrkFM.adapter.BaseArrayAdapter
import io.lerk.lrkFM.consts.Operation
import io.lerk.lrkFM.consts.PreferenceEntity
import io.lerk.lrkFM.entities.FMFile
import io.lerk.lrkFM.tasks.archive.ArchiveCreationTask
import io.lerk.lrkFM.tasks.archive.ArchiveParentFinderTask
import io.lerk.lrkFM.tasks.operation.FileDeleteTask
import io.lerk.lrkFM.tasks.operation.FileMoveTask
import io.lerk.lrkFM.tasks.operation.FileOperationTask
import java.io.File
import java.util.Objects
/**
* @author <NAME> (<EMAIL>)
*/
class ContextMenuUtil(
private val activity: FileActivity,
private val arrayAdapter: BaseArrayAdapter
) {
/**
* Adds menu buttons to context menu.
*
* @param f the file
* @param fileName the file name for the title
* @param menu the context menu to fill
*/
fun initializeContextMenu(f: FMFile, fileName: String?, menu: ContextMenu) {
menu.setHeaderTitle(fileName)
addCopyPathToMenu(f, menu)
if (arrayAdapter !is ArchiveArrayAdapter) { // those actions are not available while inside archives
addExtractToMenu(f, menu)
addDeleteToMenu(f, menu)
addShareToMenu(f, menu)
addCreateZipToMenu(f, menu)
addExploreToMenu(f, menu)
addOpenWithToMenu(f, menu)
addCopyToMenu(f, menu)
addMoveToMenu(f, menu)
addRenameToMenu(f, menu)
}
}
/**
* Adds delete button to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addDeleteToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_DELETE, 0, activity.getString(R.string.delete))
.setOnMenuItemClickListener { _: MenuItem? ->
AlertDialog.Builder(activity)
.setTitle(R.string.delete)
.setMessage(activity.getString(R.string.warn_delete_msg) + FileActivity.Companion.WHITESPACE + f.name + "?")
.setNegativeButton(R.string.cancel) { dialogInterface: DialogInterface, i: Int -> dialogInterface.cancel() }
.setPositiveButton(R.string.yes) { dialogInterface: DialogInterface, _: Int ->
FileDeleteTask(activity, { b: Boolean? ->
if (!b!!) {
Toast.makeText(
activity,
R.string.err_deleting_element,
Toast.LENGTH_SHORT
).show()
}
}, f).execute()
activity.reloadCurrentDirectory()
dialogInterface.dismiss()
}
.show()
true
}
}
/**
* Adds extract to menu.
*
* @param file file file
* @param menu menu
*/
private fun addExtractToMenu(file: FMFile, menu: ContextMenu) {
ArchiveParentFinderTask(
file
) { parentFinder: ArchiveParentFinder ->
menu.add(0, ID_EXTRACT, 0, activity.getString(R.string.extract))
.setOnMenuItemClickListener { _: MenuItem? ->
var archiveToExtract: FMFile? = file
if (!file.isArchive && parentFinder.isArchive) {
archiveToExtract = parentFinder.archiveFile
}
activity.addFileToOpContext(Operation.EXTRACT, archiveToExtract)
if (Pref<Boolean>(PreferenceEntity.USE_CONTEXT_FOR_OPS_TOAST).value == true) {
Toast.makeText(
activity,
activity.getString(R.string.file_added_to_context) + (archiveToExtract?.name
?: "<ERROR>"),
Toast.LENGTH_SHORT
).show()
}
if (Pref<Boolean>(PreferenceEntity.ALWAYS_EXTRACT_IN_CURRENT_DIR).value == true) {
activity.finishFileOperation()
} else {
AlertDialog.Builder(activity)
.setView(R.layout.layout_extract_now_prompt)
.setPositiveButton(R.string.yes) { _: DialogInterface?, _: Int -> activity.finishFileOperation() }
.setNeutralButton(R.string.yes_and_remember) { _: DialogInterface?, _: Int ->
Pref<Boolean>(PreferenceEntity.ALWAYS_EXTRACT_IN_CURRENT_DIR).value = true
activity.finishFileOperation()
}
.setNegativeButton(R.string.no) { _: DialogInterface?, _: Int ->
Log.d(
TAG,
"noop"
)
}
.create().show()
}
activity.reloadCurrentDirectory()
true
}
.setVisible(file.isArchive || parentFinder.isArchive)
}.execute()
}
/**
* Adds share to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addShareToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_SHARE, 0, activity.getString(R.string.share))
.setOnMenuItemClickListener { _: MenuItem? ->
val intent = Intent(Intent.ACTION_SEND)
intent.setType(FMFile.Companion.getMimeTypeFromFile(f))
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f.file))
activity.startActivity(
Intent.createChooser(
intent,
activity.getString(R.string.share_file)
)
)
true
}
}
/**
* Adds rename to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addRenameToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_RENAME, 0, activity.getString(R.string.rename))
.setOnMenuItemClickListener { _: MenuItem? ->
val alertDialog = arrayAdapter.getGenericFileOpDialog(
R.string.rename,
R.string.rename,
R.drawable.ic_mode_edit_black_24dp,
R.layout.layout_name_prompt,
{ d: AlertDialog? ->
FileMoveTask(
activity, { b: Boolean? -> }, f, d
)
}
) { _: AlertDialog? -> Log.i(TAG, "Cancelled.") }
alertDialog.setOnShowListener { d: DialogInterface? ->
arrayAdapter.presetNameForDialog(
alertDialog,
R.id.destinationName,
f.name
)
}
alertDialog.show()
activity.reloadCurrentDirectory()
true
}
}
/**
* Adds move to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addMoveToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_MOVE, 0, activity.getString(R.string.move))
.setOnMenuItemClickListener { _: MenuItem? ->
activity.addFileToOpContext(Operation.MOVE, f)
if (Pref<Boolean>(PreferenceEntity.USE_CONTEXT_FOR_OPS_TOAST).value == true) {
Toast.makeText(
activity,
activity.getString(R.string.file_added_to_context) + f.name,
Toast.LENGTH_SHORT
).show()
}
activity.reloadCurrentDirectory()
true
}
}
/**
* Adds copy to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addCopyToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_COPY, 0, activity.getString(R.string.copy))
.setOnMenuItemClickListener { _: MenuItem? ->
activity.addFileToOpContext(Operation.COPY, f)
if (Pref<Boolean>(PreferenceEntity.USE_CONTEXT_FOR_OPS_TOAST).value == true) {
Toast.makeText(
activity,
activity.getString(R.string.file_added_to_context) + f.name,
Toast.LENGTH_SHORT
).show()
}
activity.reloadCurrentDirectory()
true
}
}
/**
* Adds "copy path" to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addCopyPathToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_COPY_PATH, 0, R.string.copy_path)
.setOnMenuItemClickListener { _: MenuItem? ->
(Objects.requireNonNull(activity.getSystemService(Context.CLIPBOARD_SERVICE)) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText(
activity.getString(R.string.file_location), f.file.absolutePath
)
)
true
}
}
/**
* Adds "Create zip" and "add to zip" to menu.
*
* @param f the file
* @param menu the menu
*/
private fun addCreateZipToMenu(f: FMFile, menu: ContextMenu) {
val fileOpContext = activity.fileOpContext
val zipFileReady =
fileOpContext.first == Operation.CREATE_ZIP && fileOpContext.second.size >= 1
menu.add(
0,
ID_ADD_TO_ZIP,
0,
if (zipFileReady) activity.getString(R.string.add_to_zip) else activity.getString(R.string.new_zip_file)
).setOnMenuItemClickListener { _: MenuItem? ->
activity.addFileToOpContext(Operation.CREATE_ZIP, f)
if (Pref<Boolean>(PreferenceEntity.USE_CONTEXT_FOR_OPS_TOAST).value == true) {
Toast.makeText(
activity,
activity.getString(R.string.file_added_to_context) + f.name,
Toast.LENGTH_SHORT
).show()
}
activity.reloadCurrentDirectory()
true
}
if (zipFileReady) {
menu.add(0, ID_CREATE_ZIP, 0, activity.getString(R.string.create_zip_file))
.setOnMenuItemClickListener { _: MenuItem? ->
if (fileOpContext.first == Operation.CREATE_ZIP) {
val alertDialog = arrayAdapter.getGenericFileOpDialog(
R.string.create_zip_file,
R.string.op_destination,
R.drawable.ic_archive_black_24dp,
R.layout.layout_name_prompt,
{ d: AlertDialog? ->
var tmpName: String?
val editText = d?.findViewById<EditText>(R.id.destinationName)
tmpName = editText?.text.toString()
if (tmpName.isEmpty() || tmpName.startsWith("/")) {
Toast.makeText(
activity,
R.string.err_invalid_input_zip,
Toast.LENGTH_SHORT
).show()
tmpName = null
} else if (!tmpName.endsWith(".zip")) {
tmpName = "$tmpName.zip"
}
val destination = File(activity.currentDirectory + "/" + tmpName)
if (destination.exists()) {
val builder: AlertDialog.Builder =
FileOperationTask.Companion.getFileExistsDialogBuilder(
activity
)
builder.setOnDismissListener { _: DialogInterface? ->
ArchiveCreationTask(
activity, fileOpContext.second, destination
) { success: Boolean? ->
activity.clearFileOpCache()
activity.reloadCurrentDirectory()
if (!success!!) {
Toast.makeText(
activity,
R.string.unable_to_create_zip_file,
Toast.LENGTH_LONG
).show()
}
}.execute()
}.show()
} else {
ArchiveCreationTask(
activity,
fileOpContext.second,
destination
) { success: Boolean? ->
activity.clearFileOpCache()
activity.reloadCurrentDirectory()
if (!success!!) {
Toast.makeText(
activity,
R.string.unable_to_create_zip_file,
Toast.LENGTH_LONG
).show()
}
}.execute()
}
}
) { _: AlertDialog? -> Log.i(TAG, "Cancelled.") }
alertDialog.show()
activity.reloadCurrentDirectory()
return@setOnMenuItemClickListener true
} else {
Log.e(
TAG,
"Illegal operation mode. Expected " + Operation.CREATE_ZIP + " but was: " + fileOpContext.first
)
}
false
}.setVisible(fileOpContext.first == Operation.CREATE_ZIP)
}
}
private fun addExploreToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_EXPLORE, 0, activity.getString(R.string.explore))
.setOnMenuItemClickListener { _: MenuItem? ->
activity.loadPath(f.absolutePath)
true
}.setVisible(f.isArchive)
}
@SuppressLint("QueryPermissionsNeeded") // apparently my code should work regardless
private fun addOpenWithToMenu(f: FMFile, menu: ContextMenu) {
menu.add(0, ID_OPEN_WITH, 0, activity.getString(R.string.open_with))
.setOnMenuItemClickListener { _: MenuItem? ->
val i = Intent(Intent.ACTION_VIEW)
val mimeType: String = FMFile.Companion.getMimeTypeFromFile(f) ?: "application/octet-stream"
i.setDataAndType(Uri.fromFile(f.file), mimeType)
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val chooser =
Intent.createChooser(i, activity.getString(R.string.choose_application))
if (i.resolveActivity(activity.packageManager) != null) {
if (activity.packageManager.queryIntentActivities(i, 0).size == 1) {
Toast.makeText(
activity,
R.string.only_one_app_to_handle_file,
Toast.LENGTH_SHORT
).show()
}
activity.startActivity(chooser)
} else {
Toast.makeText(activity, R.string.no_app_to_handle_file, Toast.LENGTH_SHORT)
.show()
}
true
}.setVisible(!f.isDirectory)
}
companion object {
private const val ID_COPY = 0
private const val ID_MOVE = 1
private const val ID_RENAME = 2
private const val ID_DELETE = 3
private const val ID_EXTRACT = 4
private const val ID_SHARE = 5
private const val ID_COPY_PATH = 6
private const val ID_ADD_TO_ZIP = 7
private const val ID_CREATE_ZIP = 8
private const val ID_EXPLORE = 9
private const val ID_OPEN_WITH = 10
private val TAG = ContextMenuUtil::class.java.canonicalName
}
}
| 9 | Kotlin | 10 | 55 | 60fe91fd75d7c369637e41f2d9ec2ff4189641b6 | 17,768 | lrkFM | MIT License |
compiler/testData/codegen/box/ranges/contains/inOptimizableIntRange.kt | android | 263,405,600 | true | null | // IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JS_IR_ES6
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// WITH_RUNTIME
fun check(x: Int, left: Int, right: Int): Boolean {
val result = x in left..right
val manual = x >= left && x <= right
val range = left..right
assert(result == manual) { "Failed: optimized === manual for $range" }
assert(result == checkUnoptimized(x, range)) { "Failed: optimized === unoptimized for $range" }
return result
}
fun checkUnoptimized(x: Int, range: ClosedRange<Int>): Boolean {
return x in range
}
fun box(): String {
assert(check(1, 0, 2))
assert(!check(1, -1, 0))
assert(!check(239, 239, 238))
assert(check(239, 238, 239))
assert(check(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE))
assert(check(Int.MAX_VALUE, Int.MIN_VALUE, Int.MAX_VALUE))
var value = 0
assert(++value in 1..1)
assert(++value !in 1..1)
return "OK"
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 972 | kotlin | Apache License 2.0 |
app/src/main/java/com/edotassi/amazmod/adapters/ApplicationAdapter.kt | yael-lorenzo | 446,505,597 | true | {"Java": 1451658, "Kotlin": 69745, "Shell": 3734, "Ruby": 1467} | package com.edotassi.amazmod.adapters
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.edotassi.amazmod.R
import com.edotassi.amazmod.support.AppInfo
import com.edotassi.amazmod.ui.ApplicationSelectActivity
import com.edotassi.amazmod.ui.NotificationPackageOptionsActivity
class ApplicationAdapter(private val mActivity: ApplicationSelectActivity, private val appList: List<AppInfo>) : RecyclerView.Adapter<ApplicationAdapter.AppViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppViewHolder {
val view = LayoutInflater.from(mActivity).inflate(R.layout.row_appinfo, parent, false)
return AppViewHolder(view)
}
override fun onBindViewHolder(holder: AppViewHolder, position: Int) {
val app = appList[position]
holder.setApp(app)
}
override fun getItemCount(): Int {
return appList.size
}
inner class AppViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private lateinit var app : AppInfo
var appInfoButton: ImageView = view.findViewById(R.id.row_appinfo_button)
var appInfoIcon: ImageView = view.findViewById(R.id.row_appinfo_icon)
var appInfoAppName: TextView = view.findViewById(R.id.row_app_info_appname)
var appInfoPackageName: TextView = view.findViewById(R.id.row_app_info_package_name)
var appInfoVersionName: TextView = view.findViewById(R.id.row_appinfo_version)
var appInfoSwitch: Switch = view.findViewById(R.id.row_appinfo_switch)
init {
appInfoButton.setOnClickListener {
if (app.isEnabled) {
val intent = Intent(mActivity, NotificationPackageOptionsActivity::class.java)
intent.putExtra("app", app.packageName)
mActivity.startActivity(intent)
}
}
appInfoSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked != app.isEnabled) {
app.isEnabled = isChecked
appInfoButton.isEnabled = isChecked
mActivity.sortRecyclerView()
}
}
}
fun setApp(app:AppInfo) {
this.app = app
appInfoAppName.text = app.appName;
appInfoIcon.setImageDrawable(app.icon)
appInfoVersionName.text = app.versionName
appInfoPackageName.text = app.packageName
appInfoSwitch.isChecked = app.isEnabled
appInfoButton.isEnabled = app.isEnabled
}
}
} | 0 | Java | 0 | 0 | 9526f7cfa52cac01a3de65914460c17b57490e7c | 2,798 | AmazMod | Creative Commons Attribution 4.0 International |
src/test/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/integration/pages/UpdatePricePage.kt | ministryofjustice | 292,861,912 | false | {"Kotlin": 874836, "HTML": 131707, "Shell": 20530, "CSS": 19037, "Mustache": 4593, "Dockerfile": 1110} | package uk.gov.justice.digital.hmpps.pecs.jpc.integration.pages
import org.assertj.core.api.Assertions.assertThat
import org.fluentlenium.core.annotation.PageUrl
import org.fluentlenium.core.domain.FluentWebElement
import org.openqa.selenium.By
import org.openqa.selenium.support.FindBy
import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Money
import java.time.Month
@PageUrl("http://localhost:8080/update-price/{fromAgencyId-toAgencyId}")
class UpdatePricePage : ApplicationPage() {
@FindBy(id = "price")
private lateinit var price: FluentWebElement
@FindBy(id = "confirm-save-price")
private lateinit var submit: FluentWebElement
@FindBy(id = "tab_price-exceptions")
private lateinit var priceExceptionsTab: FluentWebElement
@FindBy(id = "exception-month")
private lateinit var exceptionMonth: FluentWebElement
@FindBy(id = "exception-price")
private lateinit var exceptionPrice: FluentWebElement
@FindBy(id = "confirm-save-exception")
private lateinit var submitException: FluentWebElement
fun isAtPricePageForJourney(fromAgencyId: String, toAgencyId: String): UpdatePricePage {
this.isAt("$fromAgencyId-$toAgencyId")
return this
}
fun updatePriceForJourney(fromAgencyId: String, toAgencyId: String, amount: Money) {
this.isAtPricePageForJourney(fromAgencyId, toAgencyId)
price.fill().withText(amount.toString())
submit.click()
}
fun assertTextIsPresent(text: String): UpdatePricePage {
assertThat(super.pageSource()).containsIgnoringCase(text)
return this
}
fun showPriceExceptionsTab(): UpdatePricePage {
priceExceptionsTab.click()
return this
}
fun addPriceException(month: Month, amount: Money) {
exceptionMonth.fillSelect().withValue(month.name)
exceptionPrice.fill().withText(amount.toString())
submitException.click()
}
fun removePriceException(month: Month): UpdatePricePage {
val element = super.find(By.id("remove-exception-${month.name}")).firstOrNull()
assertThat(element).isNotNull
element!!.click()
return this
}
}
| 1 | Kotlin | 2 | 2 | 409dde1a40a58974f3540edf49afa18cbeb5f51d | 2,072 | calculate-journey-variable-payments | MIT License |
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/RenderIrElement.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 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.ir.util
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.impl.ReturnTypeIsNotInitializedException
import org.jetbrains.kotlin.ir.types.impl.originalKotlinType
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.ifTrue
fun IrElement.render(options: DumpIrTreeOptions = DumpIrTreeOptions()) =
accept(RenderIrElementVisitor(options), null)
open class RenderIrElementVisitor(private val options: DumpIrTreeOptions = DumpIrTreeOptions()) :
IrElementVisitor<String, Nothing?> {
private val variableNameData = VariableNameData(options.normalizeNames)
fun renderType(type: IrType) = type.renderTypeWithRenderer(this@RenderIrElementVisitor, options)
fun renderSymbolReference(symbol: IrSymbol) = symbol.renderReference()
fun renderAsAnnotation(irAnnotation: IrConstructorCall): String =
StringBuilder().also { it.renderAsAnnotation(irAnnotation, this, options) }.toString()
private fun IrType.render(): String =
this.renderTypeWithRenderer(this@RenderIrElementVisitor, options)
private fun IrSymbol.renderReference() =
if (isBound)
owner.accept(BoundSymbolReferenceRenderer(variableNameData, options), null)
else
"UNBOUND ${javaClass.simpleName}"
private class BoundSymbolReferenceRenderer(
private val variableNameData: VariableNameData,
private val options: DumpIrTreeOptions,
) : IrElementVisitor<String, Nothing?> {
override fun visitElement(element: IrElement, data: Nothing?) = buildTrimEnd {
append('{')
append(element.javaClass.simpleName)
append('}')
if (element is IrDeclaration) {
if (element is IrDeclarationWithName) {
append(element.name)
append(' ')
}
renderDeclaredIn(element)
}
}
override fun visitTypeParameter(declaration: IrTypeParameter, data: Nothing?): String =
renderTypeParameter(declaration, null, options)
override fun visitClass(declaration: IrClass, data: Nothing?) =
renderClassWithRenderer(declaration, null, options)
override fun visitEnumEntry(declaration: IrEnumEntry, data: Nothing?) =
renderEnumEntry(declaration, options)
override fun visitField(declaration: IrField, data: Nothing?) =
renderField(declaration, null, options)
override fun visitVariable(declaration: IrVariable, data: Nothing?) =
buildTrimEnd {
if (declaration.isVar) append("var ") else append("val ")
append(declaration.normalizedName(variableNameData))
append(": ")
append(declaration.type.renderTypeWithRenderer(null, options))
append(' ')
if (options.printFlagsInDeclarationReferences) {
append(declaration.renderVariableFlags())
}
renderDeclaredIn(declaration)
}
override fun visitValueParameter(declaration: IrValueParameter, data: Nothing?) =
buildTrimEnd {
append(declaration.name.asString())
append(": ")
append(declaration.type.renderTypeWithRenderer(null, options))
append(' ')
if (options.printFlagsInDeclarationReferences) {
append(declaration.renderValueParameterFlags())
}
renderDeclaredIn(declaration)
}
override fun visitFunction(declaration: IrFunction, data: Nothing?) =
buildTrimEnd {
append(declaration.visibility)
append(' ')
if (declaration is IrSimpleFunction) {
append(declaration.modality.toString().toLowerCaseAsciiOnly())
append(' ')
}
when (declaration) {
is IrSimpleFunction -> append("fun ")
is IrConstructor -> append("constructor ")
else -> append("{${declaration.javaClass.simpleName}}")
}
append(declaration.name.asString())
append(' ')
renderTypeParameters(declaration)
appendIterableWith(declaration.valueParameters, "(", ")", ", ") { valueParameter ->
val varargElementType = valueParameter.varargElementType
if (varargElementType != null) {
append("vararg ")
append(valueParameter.name.asString())
append(": ")
append(varargElementType.renderTypeWithRenderer(null, options))
} else {
append(valueParameter.name.asString())
append(": ")
append(valueParameter.type.renderTypeWithRenderer(null, options))
}
}
if (declaration is IrSimpleFunction) {
append(": ")
append(declaration.renderReturnType(null, options))
}
append(' ')
if (options.printFlagsInDeclarationReferences) {
when (declaration) {
is IrSimpleFunction -> append(declaration.renderSimpleFunctionFlags())
is IrConstructor -> append(declaration.renderConstructorFlags())
}
}
renderDeclaredIn(declaration)
}
private fun StringBuilder.renderTypeParameters(declaration: IrTypeParametersContainer) {
if (declaration.typeParameters.isNotEmpty()) {
appendIterableWith(declaration.typeParameters, "<", ">", ", ") { typeParameter ->
append(typeParameter.name.asString())
}
append(' ')
}
}
override fun visitProperty(declaration: IrProperty, data: Nothing?) =
buildTrimEnd {
append(declaration.visibility)
append(' ')
append(declaration.modality.toString().toLowerCaseAsciiOnly())
append(' ')
append(declaration.name.asString())
val getter = declaration.getter
if (getter != null) {
append(": ")
append(getter.renderReturnType(null, options))
} else declaration.backingField?.type?.let { type ->
append(": ")
append(type.renderTypeWithRenderer(null, options))
}
if (options.printFlagsInDeclarationReferences) {
append(' ')
append(declaration.renderPropertyFlags())
}
}
override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty, data: Nothing?): String =
buildTrimEnd {
if (declaration.isVar) append("var ") else append("val ")
append(declaration.name.asString())
append(": ")
append(declaration.type.renderTypeWithRenderer(null, options))
append(" by (...)")
}
private fun StringBuilder.renderDeclaredIn(irDeclaration: IrDeclaration) {
append("declared in ")
renderParentOfReferencedDeclaration(irDeclaration)
}
private fun StringBuilder.renderParentOfReferencedDeclaration(declaration: IrDeclaration) {
val parent = try {
declaration.parent
} catch (e: Exception) {
append("<no parent>")
return
}
when (parent) {
is IrPackageFragment -> {
val fqn = parent.packageFqName.asString()
append(fqn.ifEmpty { "<root>" })
}
is IrDeclaration -> {
renderParentOfReferencedDeclaration(parent)
appendDeclarationNameToFqName(parent, options) {
renderElementNameFallback(parent)
}
}
else ->
renderElementNameFallback(parent)
}
}
private fun StringBuilder.renderElementNameFallback(element: Any) {
append('{')
append(element.javaClass.simpleName)
append('}')
}
}
override fun visitElement(element: IrElement, data: Nothing?): String =
"?ELEMENT? ${element::class.java.simpleName} $element"
override fun visitDeclaration(declaration: IrDeclarationBase, data: Nothing?): String =
"?DECLARATION? ${declaration::class.java.simpleName} $declaration"
override fun visitModuleFragment(declaration: IrModuleFragment, data: Nothing?): String {
return buildString {
append("MODULE_FRAGMENT")
if (options.printModuleName) {
append(" name:").append(declaration.name)
}
}
}
override fun visitExternalPackageFragment(declaration: IrExternalPackageFragment, data: Nothing?): String =
"EXTERNAL_PACKAGE_FRAGMENT fqName:${declaration.packageFqName}"
override fun visitFile(declaration: IrFile, data: Nothing?): String {
val fileName = if (options.printFilePath) declaration.path else declaration.name
return "FILE fqName:${declaration.packageFqName} fileName:$fileName"
}
override fun visitFunction(declaration: IrFunction, data: Nothing?): String =
declaration.runTrimEnd {
"FUN ${renderOriginIfNonTrivial()}"
}
override fun visitScript(declaration: IrScript, data: Nothing?) = "SCRIPT"
override fun visitSimpleFunction(declaration: IrSimpleFunction, data: Nothing?): String =
declaration.runTrimEnd {
"FUN ${renderOriginIfNonTrivial()}" +
"name:$name " +
renderSignatureIfEnabled(options.printSignatures) +
"visibility:$visibility modality:$modality " +
renderTypeParameters() + " " +
renderValueParameterTypes() + " " +
"returnType:${renderReturnType(this@RenderIrElementVisitor, options)} " +
renderSimpleFunctionFlags()
}
private fun IrFunction.renderValueParameterTypes(): String =
ArrayList<String>().apply {
addIfNotNull(dispatchReceiverParameter?.run { "\$this:${type.render()}" })
addIfNotNull(extensionReceiverParameter?.run { "\$receiver:${type.render()}" })
valueParameters.mapTo(this) { "${it.name}:${it.type.render()}" }
}.joinToString(separator = ", ", prefix = "(", postfix = ")")
override fun visitConstructor(declaration: IrConstructor, data: Nothing?): String =
declaration.runTrimEnd {
"CONSTRUCTOR ${renderOriginIfNonTrivial()}" +
renderSignatureIfEnabled(options.printSignatures) +
"visibility:$visibility " +
renderTypeParameters() + " " +
renderValueParameterTypes() + " " +
"returnType:${renderReturnType(this@RenderIrElementVisitor, options)} " +
renderConstructorFlags()
}
override fun visitProperty(declaration: IrProperty, data: Nothing?): String =
declaration.runTrimEnd {
"PROPERTY ${renderOriginIfNonTrivial()}" +
"name:$name " +
renderSignatureIfEnabled(options.printSignatures) +
"visibility:$visibility modality:$modality " +
renderPropertyFlags()
}
override fun visitField(declaration: IrField, data: Nothing?): String =
renderField(declaration, this, options)
override fun visitClass(declaration: IrClass, data: Nothing?): String =
renderClassWithRenderer(declaration, this, options)
override fun visitVariable(declaration: IrVariable, data: Nothing?): String =
declaration.runTrimEnd {
"VAR ${renderOriginIfNonTrivial()}name:${normalizedName(variableNameData)} type:${type.render()} ${renderVariableFlags()}"
}
override fun visitEnumEntry(declaration: IrEnumEntry, data: Nothing?): String =
renderEnumEntry(declaration, options)
override fun visitAnonymousInitializer(declaration: IrAnonymousInitializer, data: Nothing?): String =
"ANONYMOUS_INITIALIZER isStatic=${declaration.isStatic}"
override fun visitTypeParameter(declaration: IrTypeParameter, data: Nothing?): String =
renderTypeParameter(declaration, this, options)
override fun visitValueParameter(declaration: IrValueParameter, data: Nothing?): String =
declaration.runTrimEnd {
"VALUE_PARAMETER ${renderOriginIfNonTrivial()}" +
"name:$name " +
(if (index >= 0) "index:$index " else "") +
"type:${type.render()} " +
(varargElementType?.let { "varargElementType:${it.render()} " } ?: "") +
renderValueParameterFlags()
}
override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty, data: Nothing?): String =
declaration.runTrimEnd {
"LOCAL_DELEGATED_PROPERTY ${declaration.renderOriginIfNonTrivial()}" +
"name:$name type:${type.render()} flags:${renderLocalDelegatedPropertyFlags()}"
}
override fun visitTypeAlias(declaration: IrTypeAlias, data: Nothing?): String =
declaration.run {
"TYPEALIAS ${declaration.renderOriginIfNonTrivial()}" +
"name:$name " +
renderSignatureIfEnabled(options.printSignatures) +
"visibility:$visibility expandedType:${expandedType.render()}" +
renderTypeAliasFlags()
}
override fun visitExpressionBody(body: IrExpressionBody, data: Nothing?): String =
"EXPRESSION_BODY"
override fun visitBlockBody(body: IrBlockBody, data: Nothing?): String =
"BLOCK_BODY"
override fun visitSyntheticBody(body: IrSyntheticBody, data: Nothing?): String =
"SYNTHETIC_BODY kind=${body.kind}"
override fun visitExpression(expression: IrExpression, data: Nothing?): String =
"? ${expression::class.java.simpleName} type=${expression.type.render()}"
override fun visitConst(expression: IrConst<*>, data: Nothing?): String =
"CONST ${expression.kind} type=${expression.type.render()} value=${expression.value?.escapeIfRequired()}"
private fun Any.escapeIfRequired() =
when (this) {
is String -> "\"${StringUtil.escapeStringCharacters(this)}\""
is Char -> "'${StringUtil.escapeStringCharacters(this.toString())}'"
else -> this
}
override fun visitVararg(expression: IrVararg, data: Nothing?): String =
"VARARG type=${expression.type.render()} varargElementType=${expression.varargElementType.render()}"
override fun visitSpreadElement(spread: IrSpreadElement, data: Nothing?): String =
"SPREAD_ELEMENT"
override fun visitBlock(expression: IrBlock, data: Nothing?): String {
val prefix = when (expression) {
is IrReturnableBlock -> "RETURNABLE_"
is IrInlinedFunctionBlock -> "INLINED_"
else -> ""
}
return "${prefix}BLOCK type=${expression.type.render()} origin=${expression.origin}"
}
override fun visitComposite(expression: IrComposite, data: Nothing?): String =
"COMPOSITE type=${expression.type.render()} origin=${expression.origin}"
override fun visitReturn(expression: IrReturn, data: Nothing?): String =
"RETURN type=${expression.type.render()} from='${expression.returnTargetSymbol.renderReference()}'"
override fun visitCall(expression: IrCall, data: Nothing?): String =
"CALL '${expression.symbol.renderReference()}' ${expression.renderSuperQualifier()}" +
"type=${expression.type.render()} origin=${expression.origin}"
private fun IrCall.renderSuperQualifier(): String =
superQualifierSymbol?.let { "superQualifier='${it.renderReference()}' " } ?: ""
override fun visitConstructorCall(expression: IrConstructorCall, data: Nothing?): String =
"CONSTRUCTOR_CALL '${expression.symbol.renderReference()}' type=${expression.type.render()} origin=${expression.origin}"
override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall, data: Nothing?): String =
"DELEGATING_CONSTRUCTOR_CALL '${expression.symbol.renderReference()}'"
override fun visitEnumConstructorCall(expression: IrEnumConstructorCall, data: Nothing?): String =
"ENUM_CONSTRUCTOR_CALL '${expression.symbol.renderReference()}'"
override fun visitInstanceInitializerCall(expression: IrInstanceInitializerCall, data: Nothing?): String =
"INSTANCE_INITIALIZER_CALL classDescriptor='${expression.classSymbol.renderReference()}'"
override fun visitGetValue(expression: IrGetValue, data: Nothing?): String =
"GET_VAR '${expression.symbol.renderReference()}' type=${expression.type.render()} origin=${expression.origin}"
override fun visitSetValue(expression: IrSetValue, data: Nothing?): String =
"SET_VAR '${expression.symbol.renderReference()}' type=${expression.type.render()} origin=${expression.origin}"
override fun visitGetField(expression: IrGetField, data: Nothing?): String =
"GET_FIELD '${expression.symbol.renderReference()}' type=${expression.type.render()} origin=${expression.origin}"
override fun visitSetField(expression: IrSetField, data: Nothing?): String =
"SET_FIELD '${expression.symbol.renderReference()}' type=${expression.type.render()} origin=${expression.origin}"
override fun visitGetObjectValue(expression: IrGetObjectValue, data: Nothing?): String =
"GET_OBJECT '${expression.symbol.renderReference()}' type=${expression.type.render()}"
override fun visitGetEnumValue(expression: IrGetEnumValue, data: Nothing?): String =
"GET_ENUM '${expression.symbol.renderReference()}' type=${expression.type.render()}"
override fun visitStringConcatenation(expression: IrStringConcatenation, data: Nothing?): String =
"STRING_CONCATENATION type=${expression.type.render()}"
override fun visitTypeOperator(expression: IrTypeOperatorCall, data: Nothing?): String =
"TYPE_OP type=${expression.type.render()} origin=${expression.operator} typeOperand=${expression.typeOperand.render()}"
override fun visitWhen(expression: IrWhen, data: Nothing?): String =
"WHEN type=${expression.type.render()} origin=${expression.origin}"
override fun visitBranch(branch: IrBranch, data: Nothing?): String =
"BRANCH"
override fun visitWhileLoop(loop: IrWhileLoop, data: Nothing?): String =
"WHILE label=${loop.label} origin=${loop.origin}"
override fun visitDoWhileLoop(loop: IrDoWhileLoop, data: Nothing?): String =
"DO_WHILE label=${loop.label} origin=${loop.origin}"
override fun visitBreak(jump: IrBreak, data: Nothing?): String =
"BREAK label=${jump.label} loop.label=${jump.loop.label}"
override fun visitContinue(jump: IrContinue, data: Nothing?): String =
"CONTINUE label=${jump.label} loop.label=${jump.loop.label}"
override fun visitThrow(expression: IrThrow, data: Nothing?): String =
"THROW type=${expression.type.render()}"
override fun visitFunctionReference(expression: IrFunctionReference, data: Nothing?): String =
"FUNCTION_REFERENCE '${expression.symbol.renderReference()}' " +
"type=${expression.type.render()} origin=${expression.origin} " +
"reflectionTarget=${renderReflectionTarget(expression)}"
override fun visitRawFunctionReference(expression: IrRawFunctionReference, data: Nothing?): String =
"RAW_FUNCTION_REFERENCE '${expression.symbol.renderReference()}' type=${expression.type.render()}"
private fun renderReflectionTarget(expression: IrFunctionReference) =
if (expression.symbol == expression.reflectionTarget)
"<same>"
else
expression.reflectionTarget?.renderReference()
override fun visitPropertyReference(expression: IrPropertyReference, data: Nothing?): String =
buildTrimEnd {
append("PROPERTY_REFERENCE ")
append("'${expression.symbol.renderReference()}' ")
appendNullableAttribute("field=", expression.field) { "'${it.renderReference()}'" }
appendNullableAttribute("getter=", expression.getter) { "'${it.renderReference()}'" }
appendNullableAttribute("setter=", expression.setter) { "'${it.renderReference()}'" }
append("type=${expression.type.render()} ")
append("origin=${expression.origin}")
}
private inline fun <T : Any> StringBuilder.appendNullableAttribute(prefix: String, value: T?, toString: (T) -> String) {
append(prefix)
if (value != null) {
append(toString(value))
} else {
append("null")
}
append(" ")
}
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference, data: Nothing?): String =
buildTrimEnd {
append("LOCAL_DELEGATED_PROPERTY_REFERENCE ")
append("'${expression.symbol.renderReference()}' ")
append("delegate='${expression.delegate.renderReference()}' ")
append("getter='${expression.getter.renderReference()}' ")
appendNullableAttribute("setter=", expression.setter) { "'${it.renderReference()}'" }
append("type=${expression.type.render()} ")
append("origin=${expression.origin}")
}
override fun visitFunctionExpression(expression: IrFunctionExpression, data: Nothing?): String =
buildTrimEnd {
append("FUN_EXPR type=${expression.type.render()} origin=${expression.origin}")
}
override fun visitClassReference(expression: IrClassReference, data: Nothing?): String =
"CLASS_REFERENCE '${expression.symbol.renderReference()}' type=${expression.type.render()}"
override fun visitGetClass(expression: IrGetClass, data: Nothing?): String =
"GET_CLASS type=${expression.type.render()}"
override fun visitTry(aTry: IrTry, data: Nothing?): String =
"TRY type=${aTry.type.render()}"
override fun visitCatch(aCatch: IrCatch, data: Nothing?): String =
"CATCH parameter=${aCatch.catchParameter.symbol.renderReference()}"
override fun visitDynamicOperatorExpression(expression: IrDynamicOperatorExpression, data: Nothing?): String =
"DYN_OP operator=${expression.operator} type=${expression.type.render()}"
override fun visitDynamicMemberExpression(expression: IrDynamicMemberExpression, data: Nothing?): String =
"DYN_MEMBER memberName='${expression.memberName}' type=${expression.type.render()}"
@OptIn(ObsoleteDescriptorBasedAPI::class)
override fun visitErrorDeclaration(declaration: IrErrorDeclaration, data: Nothing?): String =
"ERROR_DECL ${declaration.descriptor::class.java.simpleName} " +
descriptorRendererForErrorDeclarations.renderDescriptor(declaration.descriptor.original)
override fun visitErrorExpression(expression: IrErrorExpression, data: Nothing?): String =
"ERROR_EXPR '${expression.description}' type=${expression.type.render()}"
override fun visitErrorCallExpression(expression: IrErrorCallExpression, data: Nothing?): String =
"ERROR_CALL '${expression.description}' type=${expression.type.render()}"
override fun visitConstantArray(expression: IrConstantArray, data: Nothing?): String =
"CONSTANT_ARRAY type=${expression.type.render()}"
override fun visitConstantObject(expression: IrConstantObject, data: Nothing?): String =
"CONSTANT_OBJECT type=${expression.type.render()} constructor=${expression.constructor.renderReference()}"
override fun visitConstantPrimitive(expression: IrConstantPrimitive, data: Nothing?): String =
"CONSTANT_PRIMITIVE type=${expression.type.render()}"
private val descriptorRendererForErrorDeclarations = DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES
}
internal fun DescriptorRenderer.renderDescriptor(descriptor: DeclarationDescriptor): String =
if (descriptor is ReceiverParameterDescriptor)
"this@${descriptor.containingDeclaration.name}: ${descriptor.type}"
else
render(descriptor)
private fun IrDeclarationWithName.renderSignatureIfEnabled(printSignatures: Boolean): String =
if (printSignatures) symbol.signature?.let { "signature:${it.render()} " }.orEmpty() else ""
internal fun IrDeclaration.renderOriginIfNonTrivial(): String =
if (origin != IrDeclarationOrigin.DEFINED) "$origin " else ""
internal fun IrClassifierSymbol.renderClassifierFqn(options: DumpIrTreeOptions): String =
if (isBound)
when (val owner = owner) {
is IrClass -> owner.renderClassFqn(options)
is IrScript -> owner.renderScriptFqn(options)
is IrTypeParameter -> owner.renderTypeParameterFqn(options)
else -> "`unexpected classifier: ${owner.render(options)}`"
}
else
"<unbound ${this.javaClass.simpleName}>"
internal fun IrTypeAliasSymbol.renderTypeAliasFqn(options: DumpIrTreeOptions): String =
if (isBound)
StringBuilder().also { owner.renderDeclarationFqn(it, options) }.toString()
else
"<unbound $this>"
internal fun IrClass.renderClassFqn(options: DumpIrTreeOptions): String =
StringBuilder().also { renderDeclarationFqn(it, options) }.toString()
internal fun IrScript.renderScriptFqn(options: DumpIrTreeOptions): String =
StringBuilder().also { renderDeclarationFqn(it, options) }.toString()
internal fun IrTypeParameter.renderTypeParameterFqn(options: DumpIrTreeOptions): String =
StringBuilder().also { sb ->
sb.append(name.asString())
sb.append(" of ")
renderDeclarationParentFqn(sb, options)
}.toString()
private inline fun StringBuilder.appendDeclarationNameToFqName(
declaration: IrDeclaration,
options: DumpIrTreeOptions,
fallback: () -> Unit
) {
if (!declaration.isFileClass || options.printFacadeClassInFqNames) {
append('.')
if (declaration is IrDeclarationWithName) {
append(declaration.name)
} else {
fallback()
}
}
}
private fun IrDeclaration.renderDeclarationFqn(sb: StringBuilder, options: DumpIrTreeOptions) {
renderDeclarationParentFqn(sb, options)
sb.appendDeclarationNameToFqName(this, options) {
sb.append(this)
}
}
private fun IrDeclaration.renderDeclarationParentFqn(sb: StringBuilder, options: DumpIrTreeOptions) {
try {
val parent = this.parent
if (parent is IrDeclaration) {
parent.renderDeclarationFqn(sb, options)
} else if (parent is IrPackageFragment) {
sb.append(parent.packageFqName.toString())
}
} catch (e: UninitializedPropertyAccessException) {
sb.append("<uninitialized parent>")
}
}
fun IrType.render(options: DumpIrTreeOptions = DumpIrTreeOptions()) =
renderTypeWithRenderer(RenderIrElementVisitor(options), options)
fun IrSimpleType.render(options: DumpIrTreeOptions = DumpIrTreeOptions()) = (this as IrType).render(options)
fun IrTypeArgument.render(options: DumpIrTreeOptions = DumpIrTreeOptions()) =
when (this) {
is IrStarProjection -> "*"
is IrTypeProjection -> "$variance ${type.render(options)}"
}
internal inline fun <T, Buffer : Appendable> Buffer.appendIterableWith(
iterable: Iterable<T>,
prefix: String,
postfix: String,
separator: String,
renderItem: Buffer.(T) -> Unit
) {
append(prefix)
var isFirst = true
for (item in iterable) {
if (!isFirst) append(separator)
renderItem(item)
isFirst = false
}
append(postfix)
}
private inline fun buildTrimEnd(fn: StringBuilder.() -> Unit): String =
buildString(fn).trimEnd()
private inline fun <T> T.runTrimEnd(fn: T.() -> String): String =
run(fn).trimEnd()
private fun renderFlagsList(vararg flags: String?) =
flags.filterNotNull().run {
if (isNotEmpty())
joinToString(prefix = "[", postfix = "] ", separator = ",")
else
""
}
private fun IrClass.renderClassFlags() =
renderFlagsList(
"companion".takeIf { isCompanion },
"inner".takeIf { isInner },
"data".takeIf { isData },
"external".takeIf { isExternal },
"value".takeIf { isValue },
"expect".takeIf { isExpect },
"fun".takeIf { isFun }
)
private fun IrField.renderFieldFlags() =
renderFlagsList(
"final".takeIf { isFinal },
"external".takeIf { isExternal },
"static".takeIf { isStatic },
)
private fun IrSimpleFunction.renderSimpleFunctionFlags(): String =
renderFlagsList(
"tailrec".takeIf { isTailrec },
"inline".takeIf { isInline },
"external".takeIf { isExternal },
"suspend".takeIf { isSuspend },
"expect".takeIf { isExpect },
"fake_override".takeIf { isFakeOverride },
"operator".takeIf { isOperator },
"infix".takeIf { isInfix }
)
private fun IrConstructor.renderConstructorFlags() =
renderFlagsList(
"inline".takeIf { isInline },
"external".takeIf { isExternal },
"primary".takeIf { isPrimary },
"expect".takeIf { isExpect }
)
private fun IrProperty.renderPropertyFlags() =
renderFlagsList(
"external".takeIf { isExternal },
"const".takeIf { isConst },
"lateinit".takeIf { isLateinit },
"delegated".takeIf { isDelegated },
"expect".takeIf { isExpect },
"fake_override".takeIf { isFakeOverride },
if (isVar) "var" else "val"
)
private fun IrVariable.renderVariableFlags(): String =
renderFlagsList(
"const".takeIf { isConst },
"lateinit".takeIf { isLateinit },
if (isVar) "var" else "val"
)
private fun IrValueParameter.renderValueParameterFlags(): String =
renderFlagsList(
"vararg".takeIf { varargElementType != null },
"crossinline".takeIf { isCrossinline },
"noinline".takeIf { isNoinline },
"assignable".takeIf { isAssignable }
)
private fun IrTypeAlias.renderTypeAliasFlags(): String =
renderFlagsList(
"actual".takeIf { isActual }
)
private fun IrFunction.renderTypeParameters(): String =
typeParameters.joinToString(separator = ", ", prefix = "<", postfix = ">") { it.name.toString() }
private val IrFunction.safeReturnType: IrType?
get() = try {
returnType
} catch (e: ReturnTypeIsNotInitializedException) {
null
}
private fun IrLocalDelegatedProperty.renderLocalDelegatedPropertyFlags() =
if (isVar) "var" else "val"
internal class VariableNameData(val normalizeNames: Boolean) {
val nameMap: MutableMap<IrVariableSymbol, String> = mutableMapOf()
var temporaryIndex: Int = 0
}
internal fun IrVariable.normalizedName(data: VariableNameData): String {
if (data.normalizeNames && (origin == IrDeclarationOrigin.IR_TEMPORARY_VARIABLE || origin == IrDeclarationOrigin.FOR_LOOP_ITERATOR)) {
return data.nameMap.getOrPut(symbol) { "tmp_${data.temporaryIndex++}" }
}
return name.asString()
}
private fun IrFunction.renderReturnType(renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions): String =
safeReturnType?.renderTypeWithRenderer(renderer, options) ?: "<Uninitialized>"
private fun IrType.renderTypeWithRenderer(renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions): String =
"${renderTypeAnnotations(annotations, renderer, options)}${renderTypeInner(renderer, options)}"
private fun IrType.renderTypeInner(renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) =
when (this) {
is IrDynamicType -> "dynamic"
is IrErrorType -> "IrErrorType(${options.verboseErrorTypes.ifTrue { originalKotlinType }})"
is IrSimpleType -> buildTrimEnd {
val isDefinitelyNotNullType =
classifier is IrTypeParameterSymbol && nullability == SimpleTypeNullability.DEFINITELY_NOT_NULL
if (isDefinitelyNotNullType) append("{")
append(classifier.renderClassifierFqn(options))
if (arguments.isNotEmpty()) {
append(
arguments.joinToString(prefix = "<", postfix = ">", separator = ", ") {
it.renderTypeArgument(renderer, options)
}
)
}
if (isDefinitelyNotNullType) {
append(" & Any}")
} else if (isMarkedNullable()) {
append('?')
}
if (options.printTypeAbbreviations)
abbreviation?.let {
append(it.renderTypeAbbreviation(renderer, options))
}
}
else -> "{${javaClass.simpleName} $this}"
}
private fun IrTypeAbbreviation.renderTypeAbbreviation(renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions): String =
buildString {
append("{ ")
append(renderTypeAnnotations(annotations, renderer, options))
append(typeAlias.renderTypeAliasFqn(options))
if (arguments.isNotEmpty()) {
append(
arguments.joinToString(prefix = "<", postfix = ">", separator = ", ") {
it.renderTypeArgument(renderer, options)
}
)
}
if (hasQuestionMark) {
append('?')
}
append(" }")
}
private fun IrTypeArgument.renderTypeArgument(renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions): String =
when (this) {
is IrStarProjection -> "*"
is IrTypeProjection -> buildTrimEnd {
append(variance.label)
if (variance != Variance.INVARIANT) append(' ')
append(type.renderTypeWithRenderer(renderer, options))
}
}
private fun renderTypeAnnotations(annotations: List<IrConstructorCall>, renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) =
if (annotations.isEmpty())
""
else
buildString {
appendIterableWith(annotations, prefix = "", postfix = " ", separator = " ") {
append("@[")
renderAsAnnotation(it, renderer, options)
append("]")
}
}
private fun StringBuilder.renderAsAnnotation(
irAnnotation: IrConstructorCall,
renderer: RenderIrElementVisitor?,
options: DumpIrTreeOptions,
) {
val annotationClassName = irAnnotation.symbol.takeIf { it.isBound }?.owner?.parentAsClass?.name?.asString() ?: "<unbound>"
append(annotationClassName)
if (irAnnotation.typeArgumentsCount != 0) {
(0 until irAnnotation.typeArgumentsCount).joinTo(this, ", ", "<", ">") { i ->
irAnnotation.getTypeArgument(i)?.renderTypeWithRenderer(renderer, options) ?: "null"
}
}
if (irAnnotation.valueArgumentsCount == 0) return
val valueParameterNames = irAnnotation.getValueParameterNamesForDebug()
appendIterableWith(0 until irAnnotation.valueArgumentsCount, separator = ", ", prefix = "(", postfix = ")") {
append(valueParameterNames[it])
append(" = ")
renderAsAnnotationArgument(irAnnotation.getValueArgument(it), renderer, options)
}
}
private fun StringBuilder.renderAsAnnotationArgument(irElement: IrElement?, renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) {
when (irElement) {
null -> append("<null>")
is IrConstructorCall -> renderAsAnnotation(irElement, renderer, options)
is IrConst<*> -> {
renderIrConstAsAnnotationArgument(irElement)
}
is IrVararg -> {
appendIterableWith(irElement.elements, prefix = "[", postfix = "]", separator = ", ") {
renderAsAnnotationArgument(it, renderer, options)
}
}
else -> if (renderer != null) {
append(irElement.accept(renderer, null))
} else {
append("...")
}
}
}
private fun StringBuilder.renderIrConstAsAnnotationArgument(const: IrConst<*>) {
val quotes = when (const.kind) {
IrConstKind.String -> "\""
IrConstKind.Char -> "'"
else -> ""
}
append(quotes)
append(const.value.toString())
append(quotes)
}
private fun renderClassWithRenderer(declaration: IrClass, renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) =
declaration.runTrimEnd {
"CLASS ${renderOriginIfNonTrivial()}" +
"$kind name:$name " +
renderSignatureIfEnabled(options.printSignatures) +
"modality:$modality visibility:$visibility " +
renderClassFlags() +
"superTypes:[${superTypes.joinToString(separator = "; ") { it.renderTypeWithRenderer(renderer, options) }}]"
}
private fun renderEnumEntry(declaration: IrEnumEntry, options: DumpIrTreeOptions) = declaration.runTrimEnd {
"ENUM_ENTRY " +
renderOriginIfNonTrivial() +
"name:$name " +
renderSignatureIfEnabled(options.printSignatures)
}
private fun renderField(declaration: IrField, renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) = declaration.runTrimEnd {
"FIELD ${renderOriginIfNonTrivial()}name:$name ${renderSignatureIfEnabled(options.printSignatures)}type:${
type.renderTypeWithRenderer(
renderer,
options
)
} visibility:$visibility ${renderFieldFlags()}"
}
private fun renderTypeParameter(declaration: IrTypeParameter, renderer: RenderIrElementVisitor?, options: DumpIrTreeOptions) =
declaration.runTrimEnd {
"TYPE_PARAMETER ${renderOriginIfNonTrivial()}" +
"name:$name index:$index variance:$variance " +
renderSignatureIfEnabled(options.printSignatures) +
"superTypes:[${
superTypes.joinToString(separator = "; ") {
it.renderTypeWithRenderer(
renderer, options
)
}
}] " +
"reified:$isReified"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 39,758 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/ExternalAccessors.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// See KT-13997
class Foo {
var bar: Int // Ok
external get
external set
}
class Bar {
val foo: Int // Ok
external get
<!MUST_BE_INITIALIZED_OR_BE_ABSTRACT!>var baz: Int<!>
external get
<!MUST_BE_INITIALIZED_OR_BE_ABSTRACT!>var gav: Int<!>
external set
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 333 | kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/common-klib-lib-and-app/build.gradle.kts | android | 263,405,600 | true | null | plugins {
kotlin("multiplatform").version("<pluginMarkerVersion>")
id("maven-publish")
}
group = "com.example"
version = "1.0"
repositories {
mavenLocal()
jcenter()
}
kotlin {
jvm()
js()
linuxX64()
linuxArm64()
// Linux-specific targets – embedded:
linuxMips32()
linuxMipsel32()
// macOS-specific targets - created by the ios() shortcut:
ios()
// Windows-specific targets:
mingwX64()
mingwX86()
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
}
}
val linuxMain by creating {
dependsOn(commonMain)
}
configure(listOf(linuxX64(), linuxArm64())) {
compilations["main"].defaultSourceSet.dependsOn(linuxMain)
}
val jvmAndJsMain by creating {
dependsOn(commonMain)
}
val jvmMain by getting {
dependsOn(jvmAndJsMain)
dependencies {
implementation(kotlin("stdlib-jdk8"))
}
}
val jsMain by getting {
dependsOn(jvmAndJsMain)
dependencies {
implementation(kotlin("stdlib-js"))
}
}
val embeddedMain by creating {
dependsOn(commonMain)
}
configure(listOf(linuxMips32(), linuxMipsel32())) {
compilations["main"].defaultSourceSet.dependsOn(embeddedMain)
}
val windowsMain by creating {
dependsOn(commonMain)
}
configure(listOf(mingwX64(), mingwX86())) {
compilations["main"].defaultSourceSet.dependsOn(windowsMain)
}
}
}
publishing {
repositories {
maven("$rootDir/repo")
}
}
tasks {
val skipCompilationOfTargets = kotlin.targets.matching { it.platformType.toString() == "native" }.names
all {
val target = name.removePrefix("compileKotlin").decapitalize()
if (target in skipCompilationOfTargets) {
actions.clear()
doLast {
val destinationFile = project.buildDir.resolve("classes/kotlin/$target/main/${project.name}.klib")
destinationFile.parentFile.mkdirs()
println("Writing a dummy klib to $destinationFile")
destinationFile.createNewFile()
}
}
}
} | 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 1,962 | kotlin | Apache License 2.0 |
app/src/main/java/com/googof/bitcointimechainwidgets/mempool/lightning/LightningNetworkWorker.kt | gooGofZ | 573,747,284 | false | {"Kotlin": 116937} | package com.googof.bitcointimechainwidgets.mempool
import android.content.Context
import androidx.glance.GlanceId
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.appwidget.updateAll
import androidx.work.*
import java.time.Duration
class MempoolWorker(
private val context: Context,
workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters) {
companion object {
private val uniqueWorkName = MempoolWorker::class.java.simpleName
fun enqueue(context: Context, force: Boolean = false) {
val manager = WorkManager.getInstance(context)
val requestBuilder = PeriodicWorkRequestBuilder<MempoolWorker>(
Duration.ofMinutes(15)
)
var workPolicy = ExistingPeriodicWorkPolicy.KEEP
// Replace any enqueued work and expedite the request
if (force) {
workPolicy = ExistingPeriodicWorkPolicy.REPLACE
}
manager.enqueueUniquePeriodicWork(
uniqueWorkName,
workPolicy,
requestBuilder.build()
)
}
/**
* Cancel any ongoing worker
*/
fun cancel(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(uniqueWorkName)
}
}
override suspend fun doWork(): Result {
val manager = GlanceAppWidgetManager(context)
val glanceIds = manager.getGlanceIds(MempoolGlanceWidget::class.java)
return try {
// Update state to indicate loading
setWidgetState(glanceIds, MempoolInfo.Loading)
// Update state with new data
setWidgetState(glanceIds, MempoolRepo.getMempoolInfo())
Result.success()
} catch (e: Exception) {
setWidgetState(glanceIds, MempoolInfo.Unavailable(e.message.orEmpty()))
if (runAttemptCount < 10) {
// Exponential backoff strategy will avoid the request to repeat
// too fast in case of failures.
Result.retry()
} else {
Result.failure()
}
}
}
/**
* Update the state of all widgets and then force update UI
*/
private suspend fun setWidgetState(glanceIds: List<GlanceId>, newState: MempoolInfo) {
glanceIds.forEach { glanceId ->
updateAppWidgetState(
context = context,
definition = MempoolInfoStateDefinition,
glanceId = glanceId,
updateState = { newState }
)
}
MempoolGlanceWidget().updateAll(context)
}
} | 1 | Kotlin | 2 | 12 | 1a4bbb6f1f69f21cc31ebca8beaeecdcf35e6bc9 | 2,761 | BitcoinTimechainWidgets | Apache License 2.0 |
app/src/main/java/com/dk/newssync/data/executor/BaseSchedulerProvider.kt | dimkonomis | 173,963,908 | false | null | package com.dk.newssync.data.executor
import io.reactivex.Scheduler
/**
* Created by <NAME> (<EMAIL>) on 13/11/2018.
**/
interface BaseSchedulerProvider {
fun computation(): Scheduler
fun multi(): Scheduler
fun io(): Scheduler
fun ui(): Scheduler
} | 2 | Kotlin | 8 | 48 | b299ca3b040c93cfa79d47fd7b7e3335c9ccc5a4 | 302 | NewsSync | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/integer-literals/hexadecimal-integer-literals/p-1/neg/2.1.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* KOTLIN DIAGNOSTICS SPEC TEST (NEGATIVE)
*
* SPEC VERSION: 0.1-100
* MAIN LINK: expressions, constant-literals, integer-literals, hexadecimal-integer-literals -> paragraph 1 -> sentence 2
* NUMBER: 1
* DESCRIPTION: Hexadecimal integer literals with an underscore after the prefix.
*/
// TESTCASE NUMBER: 1
val value_1 = <!ILLEGAL_UNDERSCORE!>0x_1234567890<!>
// TESTCASE NUMBER: 2
val value_2 = <!ILLEGAL_UNDERSCORE!>0X_______23456789<!>
// TESTCASE NUMBER: 3
val value_3 = <!ILLEGAL_UNDERSCORE!>0X_2_3_4_5_6_7_8_9<!>
// TESTCASE NUMBER: 4
val value_4 = <!ILLEGAL_UNDERSCORE, INT_LITERAL_OUT_OF_RANGE!>0x_<!>
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 624 | kotlin | Apache License 2.0 |
plugins/atomicfu/atomicfu-compiler/testData/nativeBox/atomics_basic/ScopeTest.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | import kotlinx.atomicfu.*
import kotlin.test.*
class AA(val value: Int) {
val b = B(value + 1)
val c = C(D(E(value + 1)))
fun updateToB(affected: Any): Boolean {
(affected as AtomicState).state.compareAndSet(this, b)
return (affected.state.value is B && (affected.state.value as B).value == value + 1)
}
fun manyProperties(affected: Any): Boolean {
(affected as AtomicState).state.compareAndSet(this, c.d.e)
return (affected.state.value is E && (affected.state.value as E).x == value + 1)
}
}
class B (val value: Int)
class C (val d: D)
class D (val e: E)
class E (val x: Int)
private class AtomicState(value: Any) {
val state = atomic<Any?>(value)
}
class ScopeTest {
fun scopeTest() {
val a = AA(0)
val affected: Any = AtomicState(a)
check(a.updateToB(affected))
val a1 = AA(0)
val affected1: Any = AtomicState(a1)
check(a1.manyProperties(affected1))
}
}
@Test
fun box() {
val testClass = ScopeTest()
testClass.scopeTest()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,060 | kotlin | Apache License 2.0 |