path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/ColorFill.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.ColorFill: ImageVector get() { if (_colorFill != null) { return _colorFill!! } _colorFill = fluentIcon(name = "Regular.ColorFill") { fluentPath { moveTo(9.0f, 1.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, 0.0f) verticalLineToRelative(1.27f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 1.24f, 0.57f) lineToRelative(3.53f, 3.54f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 0.0f, 2.83f) lineToRelative(-4.24f, 4.24f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.83f, 0.0f) lineToRelative(-3.54f, -3.54f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 0.0f, -2.82f) lineToRelative(4.25f, -4.25f) lineToRelative(0.09f, -0.08f) lineTo(9.0f, 1.75f) close() moveTo(9.0f, 6.25f) verticalLineToRelative(-0.63f) lineToRelative(-2.89f, 2.9f) horizontalLineToRelative(8.25f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.15f, -0.33f) lineToRelative(-3.54f, -3.54f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.17f, -0.11f) verticalLineToRelative(1.71f) arcToRelative(0.75f, 0.75f, 0.0f, true, true, -1.5f, 0.0f) close() moveTo(6.13f, 10.01f) lineToRelative(3.13f, 3.13f) curveToRelative(0.2f, 0.2f, 0.51f, 0.2f, 0.7f, 0.0f) lineTo(13.1f, 10.0f) lineTo(6.13f, 10.0f) close() moveTo(6.6f, 14.0f) lineTo(4.5f, 14.0f) arcTo(2.5f, 2.5f, 0.0f, false, false, 2.0f, 16.5f) verticalLineToRelative(3.0f) arcTo(2.5f, 2.5f, 0.0f, false, false, 4.5f, 22.0f) horizontalLineToRelative(15.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, 2.5f, -2.5f) verticalLineToRelative(-3.0f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, -2.02f, -2.45f) arcToRelative(3.5f, 3.5f, 0.0f, false, true, -0.17f, 1.5f) curveToRelative(0.4f, 0.13f, 0.69f, 0.5f, 0.69f, 0.95f) verticalLineToRelative(3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f) horizontalLineToRelative(-15.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineToRelative(-3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(3.83f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -0.84f, -0.6f) lineToRelative(-0.9f, -0.9f) close() moveTo(14.01f, 14.38f) curveToRelative(0.0f, -0.5f, 0.15f, -0.98f, 0.34f, -1.39f) curveToRelative(0.2f, -0.41f, 0.44f, -0.8f, 0.68f, -1.13f) curveToRelative(0.23f, -0.33f, 0.47f, -0.61f, 0.64f, -0.81f) lineToRelative(0.3f, -0.32f) lineToRelative(0.01f, -0.01f) curveToRelative(0.3f, -0.3f, 0.77f, -0.3f, 1.06f, 0.0f) lineToRelative(0.3f, 0.33f) arcTo(6.98f, 6.98f, 0.0f, false, true, 18.66f, 13.0f) curveToRelative(0.2f, 0.4f, 0.35f, 0.88f, 0.35f, 1.38f) curveToRelative(0.0f, 1.39f, -1.03f, 2.62f, -2.5f, 2.62f) reflectiveCurveTo(14.0f, 15.77f, 14.0f, 14.37f) close() moveTo(16.78f, 12.73f) arcToRelative(8.42f, 8.42f, 0.0f, false, false, -0.27f, -0.35f) arcToRelative(8.42f, 8.42f, 0.0f, false, false, -0.8f, 1.24f) curveToRelative(-0.14f, 0.3f, -0.2f, 0.56f, -0.2f, 0.76f) curveToRelative(0.0f, 0.69f, 0.48f, 1.12f, 1.0f, 1.12f) reflectiveCurveToRelative(1.0f, -0.43f, 1.0f, -1.13f) curveToRelative(0.0f, -0.19f, -0.06f, -0.44f, -0.2f, -0.75f) arcToRelative(5.5f, 5.5f, 0.0f, false, false, -0.53f, -0.89f) close() } } return _colorFill!! } private var _colorFill: ImageVector? = null
1
null
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
4,640
compose-fluent-ui
Apache License 2.0
src/test/java/it/smartphonecombo/uecapabilityparser/importer/ImportCapabilityInformationTest.kt
HandyMenny
539,436,833
false
null
package it.smartphonecombo.uecapabilityparser.importer import it.smartphonecombo.uecapabilityparser.UtilityForTests.getResourceAsStream import it.smartphonecombo.uecapabilityparser.UtilityForTests.toPowerClass import it.smartphonecombo.uecapabilityparser.model.PowerClass import it.smartphonecombo.uecapabilityparser.model.band.BandLteDetails import it.smartphonecombo.uecapabilityparser.model.band.BandNrDetails import it.smartphonecombo.uecapabilityparser.model.bandwidth.BwsNr import it.smartphonecombo.uecapabilityparser.model.modulation.ModulationOrder import it.smartphonecombo.uecapabilityparser.model.modulation.toModulation import it.smartphonecombo.uecapabilityparser.model.toMimo import it.smartphonecombo.uecapabilityparser.util.Output import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertLinesMatch import org.junit.jupiter.api.Test internal class ImportCapabilityInformationTest { @Test fun ueCapEutraCombinationAdd() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream("/newEngine/input/json/ueCapEutraCombinationAdd.json")!! .readBytes() ) // LTE Category assertEquals(18, capabilities.lteCategoryDL) assertEquals(13, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutraCombinationAdd.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 2, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 4, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 12, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 13, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 17, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 66, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(20), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(66), BandNrDetails(77), BandNrDetails(78), ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutraCombinationReduced() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream("/newEngine/input/json/ueCapEutraCombinationReduced.json")!! .readBytes() ) // LTE Category assertEquals(20, capabilities.lteCategoryDL) assertEquals(13, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutraCombinationReduced.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 2, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 4, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 12, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 13, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 26, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 46, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 48, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 66, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf(BandNrDetails(260), BandNrDetails(261)) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutra1024qam() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream("/newEngine/input/json/ueCapEutra1024qam.json")!!.readBytes() ) // LTE Category assertEquals(20, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutra1024qam.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 2.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(7), BandNrDetails(28), BandNrDetails(78) ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutraCombinationReduced1024qam() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapEutraCombinationReduced1024qam.json", )!! .readBytes() ) // LTE Category assertEquals(22, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutraCombinationReduced1024qam.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 2, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 4, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 12, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 13, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 14, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 17, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 18, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 19, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 25, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 26, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 29, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 30, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 34, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 39, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 42, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 46, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 48, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 66, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 71, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM1024.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(2), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(12), BandNrDetails(20), BandNrDetails(25), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(66), BandNrDetails(71), BandNrDetails(77), BandNrDetails(78), BandNrDetails(79), ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutra64qamDLMimoUL() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapEutra64qamDLMimoUL.json", )!! .readBytes() ) // LTE Category assertEquals(7, capabilities.lteCategoryDL) assertEquals(7, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutra64qamDLMimoUL.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM64.toModulation(), modUL = ModulationOrder.QAM16.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands assertArrayEquals(emptyArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutra256qamDLMimoUL() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapEutra256qamDLMimoUL.json", )!! .readBytes() ) // LTE Category assertEquals(12, capabilities.lteCategoryDL) assertEquals(13, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutra256qamDLMimoUL.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 38, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bans in eutra capability val actualNrNsaBands = capabilities.nrNSAbands assertArrayEquals(emptyArray(), actualNrNsaBands.toTypedArray()) // NR SA bans in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapEutraCombinationReducedMimoPerCC() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapEutraCombinationReducedMimoPerCC.json", )!! .readBytes() ) // LTE Category assertEquals(19, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // LTE Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapEutraCombinationReducedMimoPerCC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) // LTE bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 4.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 2.toPowerClass() ), BandLteDetails( 42, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(7), BandNrDetails(8), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(78) ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands val expectedNrSaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(20), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(78) ) assertArrayEquals(expectedNrSaBands.toTypedArray(), actualNrSaBands.toTypedArray()) } @Test fun ueCapNrOneCC() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapNrOneCC.json", )!! .readBytes() ) // NR bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(2).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(12).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(25).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(20))) powerClass = 3.toPowerClass() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(80, 40))) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 40, 20))) powerClass = 3.toPowerClass() }, BandNrDetails(48).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 40, 20))) powerClass = 3.toPowerClass() }, BandNrDetails(66).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(71).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100))) powerClass = 3.toPowerClass() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(79).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(258).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100))) powerClass = 3.toPowerClass() }, BandNrDetails(260).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() }, BandNrDetails(261).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapNrOneCC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) } @Test fun ueCapNrThreeCC() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapNrThreeCC.json", )!! .readBytes() ) // NR bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(40, 30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(2).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(12).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(25).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(30, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(30).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10))) powerClass = 3.toPowerClass() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(40, 30, 20))) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(48).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf( BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20), intArrayOf(100, 40, 20)) ) powerClass = 3.toPowerClass() }, BandNrDetails(66).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(30, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(71).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 40, 30, 20))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20))) powerClass = 3.toPowerClass() }, BandNrDetails(257).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100))) powerClass = 3.toPowerClass() }, BandNrDetails(258).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100))) powerClass = 3.toPowerClass() }, BandNrDetails(260).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() }, BandNrDetails(261).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedCsv = getResourceAsStream("/newEngine/oracle/ueCapNrThreeCC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualCsv = Output.toCsv(capabilities).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedCsv, actualCsv) } @Test fun ueCapMrdcDefaultBws() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapMrdcDefaultBws.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcDefaultBws-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) // EUTRA // Category assertEquals(19, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // Combos val expectedLteCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcDefaultBws-LTE.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualLteCsv = Output.toCsv(capabilities.lteCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedLteCsv, actualLteCsv) // Bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 4.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 2.toPowerClass() ), BandLteDetails( 42, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 43, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(20), BandNrDetails(28), BandNrDetails(38), BandNrDetails(41), BandNrDetails(77), BandNrDetails(78), ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) // NR // bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(50, 40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(50, 40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(30, 20, 15, 10, 5)), BwsNr(30, intArrayOf(30, 20, 15, 10)) ) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(80, 60, 50, 40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 20, 15, 10)), BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10)) ) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 20, 15, 10)), BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 20, 15, 10)), BwsNr(30, intArrayOf(100, 90, 80, 70, 60, 50, 40, 30, 20, 15, 10)) ) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = emptyList<String>() val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } @Test fun ueCapMrdcFR2() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapMrdcFR2.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcFR2-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) // EUTRA // Category assertEquals(19, capabilities.lteCategoryDL) assertEquals(13, capabilities.lteCategoryUL) // Combos val expectedLteCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcFR2-LTE.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualLteCsv = Output.toCsv(capabilities.lteCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedLteCsv, actualLteCsv) // Bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 18, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 19, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 21, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 26, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 42, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(77), BandNrDetails(78), BandNrDetails(79), BandNrDetails(257), ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) // NR // bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(79).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = false bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(257).apply { modDL = ModulationOrder.QAM64.toModulation() modUL = ModulationOrder.QAM64.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(60, intArrayOf(200, 100, 50)), BwsNr(120, intArrayOf(200, 100, 50)) ) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 2.toMimo() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = emptyList<String>() val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } @Test fun ueCapMrdcExynos() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapMrdcExynos.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcExynos-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) // EUTRA // Category assertEquals(20, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // Combos val expectedLteCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcExynos-LTE.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualLteCsv = Output.toCsv(capabilities.lteCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedLteCsv, actualLteCsv) // Bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(20), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(75), BandNrDetails(77), BandNrDetails(78), ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) // NR // bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)), BwsNr(60, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(30, 25, 20, 15, 10)), BwsNr(60, intArrayOf(30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)), BwsNr(60, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5)), BwsNr(30, intArrayOf(20, 15, 10)), BwsNr(60, intArrayOf(20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5)), BwsNr(30, intArrayOf(80, 60, 50, 40, 30, 25, 20, 15, 10)), BwsNr(60, intArrayOf(80, 60, 50, 40, 30, 25, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 20, 15, 10)), BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20, 15, 10)), BwsNr(60, intArrayOf(100, 80, 60, 50, 40, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(75).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(20, 15, 10, 5), intArrayOf()), BwsNr(30, intArrayOf(20, 15, 10), intArrayOf()), BwsNr(60, intArrayOf(20, 15, 10), intArrayOf()) ) powerClass = PowerClass.NONE }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(50, 40, 20, 15, 10)), BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20, 15, 10)), BwsNr(60, intArrayOf(100, 80, 60, 50, 40, 20, 15, 10)) ) powerClass = 3.toPowerClass() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(30, intArrayOf(100, 90, 80, 70, 60, 50, 40, 30, 25, 20, 15, 10)) ) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = emptyList<String>() val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } @Test fun ueCapMrdcIntraEnDc() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapMrdcIntraEnDc.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcIntraEnDc-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) // EUTRA // Category assertEquals(19, capabilities.lteCategoryDL) assertEquals(13, capabilities.lteCategoryUL) // Combos val expectedLteCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcIntraEnDc-LTE.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualLteCsv = Output.toCsv(capabilities.lteCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedLteCsv, actualLteCsv) // Bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 5, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 8, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 34, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 39, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 40, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 41, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 42, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 43, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM64.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(77), BandNrDetails(78), BandNrDetails(79), BandNrDetails(80), BandNrDetails(84) ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) // NR // bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf(BwsNr(30, intArrayOf(20, 15, 10))) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(90, 80, 60, 50, 40, 20))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf( BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20)), ) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf( BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20)), ) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf( BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20)), ) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(79).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf( BwsNr(30, intArrayOf(100, 80, 60, 50, 40)), ) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(80).apply { modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(), intArrayOf(20, 15, 10, 5)), ) powerClass = 3.toPowerClass() }, BandNrDetails(84).apply { modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf( BwsNr(15, intArrayOf(), intArrayOf(20, 15, 10, 5)), ) powerClass = 3.toPowerClass() } ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = emptyList<String>() val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } @Test fun ueCapMrdcIntraEnDcV1590() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapMrdcIntraEnDcV1590.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcIntraEnDcV1590-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) // EUTRA // Category assertEquals(19, capabilities.lteCategoryDL) assertEquals(18, capabilities.lteCategoryUL) // Combos val expectedLteCsv = getResourceAsStream("/newEngine/oracle/ueCapMrdcIntraEnDcV1590-LTE.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualLteCsv = Output.toCsv(capabilities.lteCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedLteCsv, actualLteCsv) // Bands val expectedLteBands = listOf( BandLteDetails( 1, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 3, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 7, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 20, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 28, mimoDL = 2.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ), BandLteDetails( 32, mimoDL = 2.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), powerClass = PowerClass.NONE ), BandLteDetails( 38, mimoDL = 4.toMimo(), mimoUL = 1.toMimo(), modDL = ModulationOrder.QAM256.toModulation(), modUL = ModulationOrder.QAM256.toModulation(), powerClass = 3.toPowerClass() ) ) val actualLteBands = capabilities.lteBands assertArrayEquals(expectedLteBands.toTypedArray(), actualLteBands.toTypedArray()) // NR NSA bands in eutra capability val actualNrNsaBands = capabilities.nrNSAbands val expectedNrNsaBands = listOf( BandNrDetails(1), BandNrDetails(2), BandNrDetails(3), BandNrDetails(5), BandNrDetails(7), BandNrDetails(8), BandNrDetails(12), BandNrDetails(20), BandNrDetails(25), BandNrDetails(28), BandNrDetails(38), BandNrDetails(40), BandNrDetails(41), BandNrDetails(66), BandNrDetails(75), BandNrDetails(77), BandNrDetails(78) ) assertArrayEquals(expectedNrNsaBands.toTypedArray(), actualNrNsaBands.toTypedArray()) // NR SA bands in eutra capability val actualNrSaBands = capabilities.nrSAbands assertArrayEquals(emptyArray(), actualNrSaBands.toTypedArray()) // NR // bands in nr capability val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(2).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(12).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(25).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(40, 30, 20, 15, 10))) powerClass = 3.toPowerClass() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(80, 60, 50, 40, 30, 20, 15, 10))) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf( BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10)), ) powerClass = 3.toPowerClass() }, BandNrDetails(66).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(75).apply { modDL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5), intArrayOf())) powerClass = PowerClass.NONE }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf( BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10)), ) powerClass = 3.toPowerClass() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 bandwidths = listOf( BwsNr(30, intArrayOf(100, 90, 80, 70, 60, 50, 40, 30, 20, 15, 10)), ) mimoDL = 4.toMimo() mimoUL = 1.toMimo() } ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = emptyList<String>() val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } @Test fun ueCapEutraNrOnlyIntraBcsAll() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapEutraNrOnlyIntraBcsAll.json", )!! .readBytes() ) // MRDC // ENDC combos val expectedEndcCsv = getResourceAsStream("/newEngine/oracle/ueCapEutraNrOnlyIntraBcsAll-EN-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualEndcCsv = Output.toCsv(capabilities.enDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedEndcCsv, actualEndcCsv) } @Test fun ueCapNrDc() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapNrdc.json", )!! .readBytes() ) // NR val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(2).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(5).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(7).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(8).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(12).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(13).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(14).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(18).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(20).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(25).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(40, 30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(26).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(30, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(29).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(10, 5), intArrayOf())) powerClass = PowerClass.NONE }, BandNrDetails(30).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(40, 30, 20, 15, 10))) powerClass = 3.toPowerClass() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(80, 60, 50, 40, 30, 20, 15, 10))) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(48).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf( BwsNr( 30, intArrayOf(100, 80, 60, 50, 40, 30, 20, 10), intArrayOf(100, 40, 30, 20, 10) ) ) powerClass = 3.toPowerClass() }, BandNrDetails(53).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(10))) powerClass = 3.toPowerClass() }, BandNrDetails(66).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(40, 30, 20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(70).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(25, 20, 15, 10, 5), intArrayOf(15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(71).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(75).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(50, 40, 30, 25, 20, 15, 10, 5), intArrayOf())) powerClass = PowerClass.NONE }, BandNrDetails(76).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(5), intArrayOf())) powerClass = PowerClass.NONE }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 70, 60, 50, 40, 30, 20, 15, 10))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(79).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40))) powerClass = 2.toPowerClass() maxUplinkDutyCycle = 50 }, BandNrDetails(91).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(92).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(93).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(94).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() rateMatchingLteCrs = true bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(257).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM64.toModulation() bandwidths = listOf(BwsNr(120, intArrayOf(200, 100, 50))) powerClass = 3.toPowerClass() }, BandNrDetails(258).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM64.toModulation() bandwidths = listOf(BwsNr(120, intArrayOf(200, 100, 50))) powerClass = 3.toPowerClass() }, BandNrDetails(260).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM64.toModulation() bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() }, BandNrDetails(261).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM64.toModulation() bandwidths = listOf(BwsNr(120, intArrayOf(100, 50))) powerClass = 3.toPowerClass() mimoDL = 2.toMimo() mimoUL = 2.toMimo() }, ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = getResourceAsStream("/newEngine/oracle/ueCapNrdc-NR.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) // NR-DC Combos val expectedNrDcCsv = getResourceAsStream("/newEngine/oracle/ueCapNrdc-NR-DC.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualNrDcCsv = Output.toCsv(capabilities.nrDcCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrDcCsv, actualNrDcCsv) } @Test fun ueCapNrSUL() { val capabilities = ImportCapabilityInformation.parse( getResourceAsStream( "/newEngine/input/json/ueCapNrSUL.json", )!! .readBytes() ) // NR val actualNrBands = capabilities.nrBands val expectedNrBands = listOf( BandNrDetails(1).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(3).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(28).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(30, 20, 15, 10, 5))) powerClass = 3.toPowerClass() }, BandNrDetails(38).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(20))) powerClass = 3.toPowerClass() }, BandNrDetails(40).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(30, intArrayOf(80, 60, 50, 40, 30, 20))) powerClass = 3.toPowerClass() }, BandNrDetails(41).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40, 20, 15, 10))) }, BandNrDetails(77).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf(BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20))) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(78).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf(BwsNr(30, intArrayOf(100, 90, 80, 60, 50, 40, 20, 10))) mimoDL = 4.toMimo() mimoUL = 1.toMimo() }, BandNrDetails(79).apply { modDL = ModulationOrder.QAM256.toModulation() modUL = ModulationOrder.QAM256.toModulation() powerClass = 2.toPowerClass() maxUplinkDutyCycle = 100 bandwidths = listOf(BwsNr(30, intArrayOf(100, 80, 60, 50, 40))) }, BandNrDetails(80).apply { modDL = ModulationOrder.NONE.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(), intArrayOf(30, 25, 20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoUL = 1.toMimo() }, BandNrDetails(84).apply { modDL = ModulationOrder.NONE.toModulation() modUL = ModulationOrder.QAM256.toModulation() bandwidths = listOf(BwsNr(15, intArrayOf(), intArrayOf(20, 15, 10, 5))) powerClass = 3.toPowerClass() mimoUL = 1.toMimo() } ) assertArrayEquals(expectedNrBands.toTypedArray(), actualNrBands.toTypedArray()) // NR Combos val expectedNrCsv = getResourceAsStream("/newEngine/oracle/ueCapNrSUL-NR.csv")!! .bufferedReader() .readLines() .dropLastWhile { it.isBlank() } val actualNrCsv = Output.toCsv(capabilities.nrCombos).lines().dropLastWhile { it.isBlank() } assertLinesMatch(expectedNrCsv, actualNrCsv) } }
2
Kotlin
7
9
b5b94a2d0f0e31fcdc9dfacc507e920838d308d4
145,013
uecapabilityparser
MIT License
app/src/test/java/com/elifox/legocatalog/api/LegoServiceTest.kt
Eli-Fox
198,384,890
false
null
package com.example.kotlinwithjetpack.api import androidx.arch.core.executor.testing.InstantTaskExecutorRule import kotlinx.coroutines.runBlocking import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okio.Okio import org.hamcrest.CoreMatchers.`is` import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @RunWith(JUnit4::class) class LegoServiceTest { @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() private lateinit var service: LegoService private lateinit var mockWebServer: MockWebServer @Before fun createService() { mockWebServer = MockWebServer() service = Retrofit.Builder() .baseUrl(mockWebServer.url("")) .addConverterFactory(GsonConverterFactory.create()) .build() .create(LegoService::class.java) } @After fun stopService() { mockWebServer.shutdown() } @Test fun requestLegoSets() { runBlocking { enqueueResponse("legosets.json") val resultResponse = service.getSets().body() val request = mockWebServer.takeRequest() assertNotNull(resultResponse) assertThat(request.path, `is`("/lego/sets/")) } } @Test fun getLegoSetsResponse() { runBlocking { enqueueResponse("legosets.json") val resultResponse = service.getSets().body() val legoSets = resultResponse!!.results assertThat(resultResponse.count, `is`(9)) assertThat(legoSets.size, `is`(9)) } } @Test fun getLegoSetsPagination() { runBlocking { enqueueResponse("legosets.json") val resultResponse = service.getSets().body() assertNull(resultResponse!!.next) assertNull(resultResponse.previous) } } @Test fun getLegoSetItem() { runBlocking { enqueueResponse("legosets.json") val resultResponse = service.getSets().body() val legoSets = resultResponse!!.results val legoSet = legoSets[0] assertThat(legoSet.id, `is`("30212-1")) assertThat(legoSet.name, `is`("Mirkwood Elf Guard")) assertThat(legoSet.year, `is`(2012)) assertThat(legoSet.themeId, `is`(563)) assertThat(legoSet.numParts, `is`(27)) assertThat(legoSet.imageUrl, `is`("https://cdn.rebrickable.com/media/sets/30212-1.jpg")) assertThat(legoSet.url, `is`("https://rebrickable.com/sets/30212-1/mirkwood-elf-guard/")) assertThat(legoSet.lastModifiedDate, `is`("2016-04-23T12:25:04.325081Z")) } } private fun enqueueResponse(fileName: String, headers: Map<String, String> = emptyMap()) { val inputStream = javaClass.classLoader .getResourceAsStream("api-response/$fileName") val source = Okio.buffer(Okio.source(inputStream)) val mockResponse = MockResponse() for ((key, value) in headers) { mockResponse.addHeader(key, value) } mockWebServer.enqueue(mockResponse.setBody( source.readString(Charsets.UTF_8)) ) } }
8
null
191
770
65bb14ed9972cc21604b13b06209e3c22c1adc3a
3,474
LEGO-Catalog
Apache License 2.0
buildSrc/src/main/kotlin/Versions.kt
Dormitory-Management
365,696,122
false
null
object Versions { object Apps { const val compileSdk = 30 const val minSdk = 21 const val targetSdk = 30 const val buildToolVersion = "30.0.2" const val versionCode = 1 const val versionName = "1.0.0" const val commonVersionCode = 1 const val commonVersionName = "1.0.0" const val networkVersionCode = 1 const val networkVersionName = "1.0.0" } object Plugins { const val gradle = "4.2.1" const val kotlin = "1.5.0" const val appcompat = "1.2.0" const val junit = "4.13.2" const val junitExt = "1.1.2" const val espressoCore = "3.3.0" const val coreKtx = "1.3.2" const val lifecycleVersion = "2.2.0" const val viewModelVersion = "2.2.0" const val fragmentVersion = "1.2.5" const val navigationVersion = "2.3.2" const val constraintLayout = "2.0.4" const val swipeVersion = "1.1.0" const val materialVersion = "1.3.0" const val jsoupVersion = "1.12.1" const val glideVersion = "4.9.0" const val okhttpVersion = "3.14.9" const val okhttpLoggingVersion = "3.12.0" const val retrofitVersion = "2.9.0" const val converterGsonVersion = "2.9.0" const val adapterRxjavaVersion = "2.9.0" const val tikxmlVersion = "0.8.13" const val threetenbpVersion = "1.2.4" const val rxjavaVersion = "3.0.9" const val rxAndroidVersion = "3.0.0" const val rxkotlinVersion = "3.0.1" const val rxBindingVersion = "4.0.0" const val easyPermissionVersion = "3.0.0" const val gson = "2.8.6" } }
0
Kotlin
0
0
aab7530e8f57545bfabc918067c8eb446d5082a2
1,695
Dormitory-Management-AOS
MIT License
Code/app/src/main/java/com/istudio/solid_principles/utils/usecase_user_functions/UserAuthenticator.kt
devrath
737,474,684
false
{"Kotlin": 27173}
package com.istudio.solid_principles.utils.usecase_user_functions class UserAuthenticator { fun login(user: User) { // Logic for user log-in // ... } fun logOut(user: User) { // Logic for user log-out // ... } }
0
Kotlin
0
1
113eb902edc14210ad22fd0520903eb287368858
263
SOLID-Principles
Apache License 2.0
sdk/src/main/java/com/exponea/sdk/manager/AppInboxManagerImpl.kt
exponea
134,699,893
false
{"Kotlin": 1773395, "Java": 206}
package com.exponea.sdk.manager import com.exponea.sdk.models.AppInboxMessateType.UNKNOWN import com.exponea.sdk.models.CustomerIds import com.exponea.sdk.models.Event import com.exponea.sdk.models.EventType import com.exponea.sdk.models.ExponeaProject import com.exponea.sdk.models.MessageItem import com.exponea.sdk.models.Result import com.exponea.sdk.repository.AppInboxCache import com.exponea.sdk.repository.CustomerIdsRepository import com.exponea.sdk.repository.DrawableCache import com.exponea.sdk.services.ExponeaProjectFactory import com.exponea.sdk.util.Logger import com.exponea.sdk.util.runOnBackgroundThread import com.exponea.sdk.util.runOnMainThread import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.atomic.AtomicBoolean internal class AppInboxManagerImpl( private val fetchManager: FetchManager, private val drawableCache: DrawableCache, private val customerIdsRepository: CustomerIdsRepository, private val appInboxCache: AppInboxCache, private val projectFactory: ExponeaProjectFactory ) : AppInboxManager { internal var lastCustomerIdsForFetch: CustomerIds? = null internal val isFetching = AtomicBoolean(false) internal val onFetchDoneCallbacks = LinkedBlockingQueue<(List<MessageItem>?) -> Unit>() public override fun markMessageAsRead(message: MessageItem, callback: ((Boolean) -> Unit)?) { if (message.syncToken == null || message.customerIds.isEmpty()) { Logger.e(this, "Unable to mark message ${message.id} as read, try to fetch AppInbox") runOnMainThread { callback?.invoke(false) } return } message.read = true // ensure to message change is stored markCachedMessageAsRead(message.id) requireMutualExponeaProject { expoProject -> if (expoProject.authorization == null) { Logger.e(this, "AppInbox loading failed. Authorization token is missing") runOnMainThread { callback?.invoke(false) } } val customerIds = CustomerIds(HashMap(message.customerIds)).apply { message.customerIds.get(CustomerIds.COOKIE)?.let { cookie = it } } fetchManager.markAppInboxAsRead( exponeaProject = expoProject, customerIds = customerIds, syncToken = message.syncToken!!, messageIds = listOf(message.id), onSuccess = { Logger.i(this, "AppInbox marked as read") runOnMainThread { callback?.invoke(true) } }, onFailure = { Logger.e(this, "AppInbox marking as read failed. ${it.results.message}") runOnMainThread { callback?.invoke(false) } } ) } } private fun markCachedMessageAsRead(messageId: String) { val messages = appInboxCache.getMessages() messages.forEach { cachedMessage -> if (cachedMessage.id == messageId) { cachedMessage.read = true } } appInboxCache.setMessages(messages) } public override fun fetchAppInbox(callback: ((List<MessageItem>?) -> Unit)) { val customerIds = customerIdsRepository.get() onFetchDoneCallbacks.add(callback) if (!isFetching.compareAndSet(false, true)) { Logger.d(this, "AppInbox fetch already in progress, waiting for response") lastCustomerIdsForFetch = customerIds return } invokeFetchAppInbox(customerIds) } private fun invokeFetchAppInbox(customerIds: CustomerIds) { requireMutualExponeaProject { expoProject -> if (expoProject.authorization == null) { Logger.e(this, "AppInbox loading failed. Authorization token is missing") notifyFetchCallbacks(null) isFetching.set(false) return@requireMutualExponeaProject } fetchManager.fetchAppInbox( exponeaProject = expoProject, customerIds = customerIds, syncToken = appInboxCache.getSyncToken(), onSuccess = { result -> Logger.d(this, "AppInbox fetch is done for customerIds ${customerIds.toHashMap()}") handleDataFetchResult(result, customerIds) }, onFailure = { Logger.e(this, "AppInbox loading failed. ${it.results.message}") handleDataFetchResult(null, customerIds) } ) } } private fun handleDataFetchResult( result: Result<ArrayList<MessageItem>?>?, processCustomerIds: CustomerIds ) { val fetchProcessIsValid: Boolean val lastCustomerIdsForFetchLocal = lastCustomerIdsForFetch if (lastCustomerIdsForFetchLocal == null) { fetchProcessIsValid = true } else if (lastCustomerIdsForFetchLocal.toHashMap() == processCustomerIds.toHashMap()) { fetchProcessIsValid = true lastCustomerIdsForFetch = null } else { fetchProcessIsValid = false Logger.w( this, "AppInbox fetch is outdated for last customer IDs ${lastCustomerIdsForFetchLocal.toHashMap()}" ) } if (fetchProcessIsValid) { onAppInboxDataLoaded(result, processCustomerIds) } else { appInboxCache.clear() val customerIdsToRepeat = lastCustomerIdsForFetchLocal ?: customerIdsRepository.get() lastCustomerIdsForFetch = null Logger.i(this, "AppInbox fetch is going to repeat for ${customerIdsToRepeat.toHashMap()}") invokeFetchAppInbox(customerIdsToRepeat) } } private fun notifyFetchCallbacks(data: List<MessageItem>?) { val activeCallbacks = mutableListOf<(List<MessageItem>?) -> Unit>() onFetchDoneCallbacks.drainTo(activeCallbacks) activeCallbacks.forEach { activeCallback -> runOnMainThread { activeCallback.invoke(data) } } } private fun requireMutualExponeaProject(onTokenCallback: (ExponeaProject) -> Unit) { runOnBackgroundThread { onTokenCallback.invoke(projectFactory.mutualExponeaProject) } } /** * Adds customerIds and syncToken into every MessageItem in list. * These values will be used for tracking and markAsRead future calls */ private fun enhanceMessages(messages: List<MessageItem>?, customerIds: CustomerIds, syncToken: String?) { messages?.forEach { messageItem -> messageItem.customerIds = customerIds.toHashMap() messageItem.syncToken = syncToken } } private fun onAppInboxDataLoaded( result: Result<ArrayList<MessageItem>?>?, customerIds: CustomerIds ) { if (customerIds.toHashMap() != customerIdsRepository.get().toHashMap()) { Logger.i(this, "AppInbox data for ${customerIds.toHashMap()} will replace old data") appInboxCache.clear() } val dataFetchFinalization = { appInboxData: List<MessageItem>? -> isFetching.set(false) notifyFetchCallbacks(appInboxData) } if (result == null) { // failure => no data Logger.e(this, "AppInbox loading failed") dataFetchFinalization(null) } else { // we have data => success Logger.i(this, "AppInbox loaded successfully") enhanceMessages(result.results, customerIds, result.syncToken) result.syncToken?.let { appInboxCache.setSyncToken(it) } val loadedMessages = result.results ?: arrayListOf() val supportedMessages = loadedMessages.filter { it.type != UNKNOWN } appInboxCache.addMessages(supportedMessages) val allMessages = appInboxCache.getMessages() val imageUrls = supportedMessages .mapNotNull { messageItem -> messageItem.content?.imageUrl } .filter { imageUrl -> imageUrl.isNotBlank() } drawableCache.preload(imageUrls) { dataFetchFinalization(allMessages) } } } override fun fetchAppInboxItem(messageId: String, callback: (MessageItem?) -> Unit) { fetchAppInbox { messages -> val foundMessage = messages?.find { messageItem -> messageItem.id == messageId } callback.invoke(foundMessage) } } override fun reload() { appInboxCache.clear() fetchAppInbox { Logger.d(this, "AppInbox loaded") } } override fun onEventCreated(event: Event, type: EventType) { if (EventType.TRACK_CUSTOMER == type) { Logger.i(this, "CustomerIDs are updated, clearing AppInbox messages") fetchAppInbox { Logger.d(this, "AppInbox loaded") } } } }
0
Kotlin
16
17
150999cffec54fa2266e0d9db07c16143dc17a26
9,273
exponea-android-sdk
MIT License
app/src/main/java/soko/ekibun/bangumi/model/history/HistoryDatabase.kt
ekibun
136,573,582
false
null
package soko.ekibun.bangumi.model.history import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [History::class], version = 1) abstract class HistoryDatabase : RoomDatabase() { abstract fun historyDao(): HistoryDao }
9
null
13
408
81099b44d5f351868f8ff2beb0cc19704d44e030
253
Bangumi
Apache License 2.0
app/src/main/java/com/gatheringhallstudios/mhworlddatabase/data/entities/locations.kt
gatheringhallstudios
109,581,966
false
{"Kotlin": 840815, "Java": 83759, "Ruby": 1279}
package com.gatheringhallstudios.mhworlddatabase.data.entities import androidx.room.Entity import androidx.room.PrimaryKey import com.gatheringhallstudios.mhworlddatabase.data.types.Rank @Entity(tableName = "location_text", primaryKeys = ["id", "lang_id"]) data class LocationText( val id: Int, val order_id: Int, val lang_id: String, val name: String? ) @Entity(tableName = "location_item") data class LocationItemEntity( @PrimaryKey val id: Int, val location_id: Int, val rank: Rank?, val area: Int, val item_id: Int, val stack: Int, val percentage: Int, val nodes: Int ) @Entity(tableName = "location_camp_text") data class LocationCampText( @PrimaryKey val id: Int, val location_id: Int, val lang_id: String, val name: String?, val area: Int )
5
Kotlin
22
54
7a81b4ccd9e5f898bf9373d7c60f85c6c8f85781
888
MHWorldDatabase
MIT License
library/src/main/java/com/aaron/rollpicker/RollPicker.kt
aaronzzx
655,271,516
false
null
package com.aaron.rollpicker import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.AnimationState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDecay import androidx.compose.animation.core.snap import androidx.compose.animation.core.spring import androidx.compose.animation.rememberSplineBasedDecay import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.CacheDrawScope import androidx.compose.ui.draw.DrawResult import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.util.fastFirstOrNull import androidx.compose.ui.util.packInts import androidx.compose.ui.util.unpackInt1 import androidx.compose.ui.util.unpackInt2 import com.aaron.rollpicker.RollPickerDefaults.LineSpacingMultiplier import com.aaron.rollpicker.RollPickerDefaults.Loop import com.aaron.rollpicker.RollPickerDefaults.MaxFlingVelocity import com.aaron.rollpicker.RollPickerDefaults.Style import com.aaron.rollpicker.RollPickerDefaults.VisibleCount import com.aaron.rollpicker.RollPickerDefaults.getDefaultSize import com.aaron.rollpicker.RollPickerDefaults.paintOnPick import com.aaron.rollpicker.RollPickerStyle.Flat import com.aaron.rollpicker.RollPickerStyle.Wheel import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.math.sin /** * 垂直滚动的选择器 * * @param count 个数 * @param onPick 选中回调 * @param state 选择器状态 * @param style 选择器风格 * @param visibleCount 可见数量 * @param lineSpacingMultiplier 行间距 * @param absMaxVelocity 最大加速度 * @param loop 循环滚动 * @param onItemClick 点击 item 回调 * @param onDrawWithCache Modifier.drawWithCache 回调,提供 [RollPickerDrawScope] * @param onFling 惯性滑动回调 * @param itemContent item 内容回调 */ @Composable fun VerticalRollPicker( count: Int, onPick: (index: RollPickerIndex) -> Unit, modifier: Modifier = Modifier, state: RollPickerState = rememberRollPickerState(), style: RollPickerStyle = Style, visibleCount: Int = VisibleCount, lineSpacingMultiplier: Float = LineSpacingMultiplier, absMaxVelocity: Float = MaxFlingVelocity, loop: Boolean = Loop, onItemClick: ((index: RollPickerIndex) -> Unit)? = null, onDrawWithCache: (RollPickerDrawScope.() -> DrawResult)? = paintOnPick(), onFling: (suspend RollPickerScope.(available: Velocity) -> Velocity)? = null, itemContent: @Composable RollPickerScope.(index: RollPickerIndex) -> Unit ) { BoxWithConstraints(modifier = modifier.size(getDefaultSize(style, visibleCount))) { if (maxWidth <= 0.dp || maxHeight <= 0.dp) return@BoxWithConstraints RollPicker( count = count, onPick = onPick, orientation = Orientation.Vertical, diameter = maxHeight, state = state, style = style, visibleCount = visibleCount, lineSpacingMultiplier = lineSpacingMultiplier, absMaxVelocity = absMaxVelocity, loop = loop, onItemClick = onItemClick, onDrawWithCache = onDrawWithCache, onFling = onFling, itemContent = itemContent ) } } /** * 水平滚动的选择器 * * @param count 个数 * @param onPick 选中回调 * @param state 选择器状态 * @param style 选择器风格 * @param visibleCount 可见数量 * @param lineSpacingMultiplier 行间距 * @param absMaxVelocity 最大加速度 * @param loop 循环滚动 * @param onItemClick 点击 item 回调 * @param onDrawWithCache Modifier.drawWithCache 回调,提供 [RollPickerDrawScope] * @param onFling 惯性滑动回调 * @param itemContent item 内容回调 */ @Composable fun HorizontalRollPicker( count: Int, onPick: (index: RollPickerIndex) -> Unit, modifier: Modifier = Modifier, state: RollPickerState = rememberRollPickerState(), style: RollPickerStyle = Style, visibleCount: Int = VisibleCount, lineSpacingMultiplier: Float = LineSpacingMultiplier, absMaxVelocity: Float = MaxFlingVelocity, loop: Boolean = Loop, onItemClick: ((index: RollPickerIndex) -> Unit)? = null, onDrawWithCache: (RollPickerDrawScope.() -> DrawResult)? = paintOnPick(), onFling: (suspend RollPickerScope.(available: Velocity) -> Velocity)? = null, itemContent: @Composable RollPickerScope.(index: RollPickerIndex) -> Unit ) { BoxWithConstraints(modifier = modifier.size(getDefaultSize(style, visibleCount))) { if (maxWidth <= 0.dp || maxHeight <= 0.dp) return@BoxWithConstraints RollPicker( count = count, onPick = onPick, orientation = Orientation.Horizontal, diameter = maxWidth, state = state, style = style, visibleCount = visibleCount, lineSpacingMultiplier = lineSpacingMultiplier, absMaxVelocity = absMaxVelocity, loop = loop, onItemClick = onItemClick, onDrawWithCache = onDrawWithCache, onFling = onFling, itemContent = itemContent ) } } @Composable private fun RollPicker( count: Int, onPick: (index: RollPickerIndex) -> Unit, orientation: Orientation, diameter: Dp, state: RollPickerState, style: RollPickerStyle, visibleCount: Int, lineSpacingMultiplier: Float, absMaxVelocity: Float, loop: Boolean, onItemClick: ((index: RollPickerIndex) -> Unit)?, onDrawWithCache: (RollPickerDrawScope.() -> DrawResult)?, onFling: (suspend RollPickerScope.(available: Velocity) -> Velocity)?, itemContent: @Composable RollPickerScope.(index: RollPickerIndex) -> Unit ) { if (count <= 0) return check(visibleCount > 0 && visibleCount and 1 != 0) { "visibleCount must be greater than 0 and must be odd number" } val actualVisibleCount = when (style) { is Wheel -> visibleCount + 2 is Flat -> if (style.halfExposed) visibleCount + 1 else visibleCount } val itemSizeAnchor = when (style) { is Wheel -> diameter / (actualVisibleCount - 1) is Flat -> diameter / actualVisibleCount } val itemSize = when (style) { is Wheel -> itemSizeAnchor * 1.5f / lineSpacingMultiplier is Flat -> itemSizeAnchor / lineSpacingMultiplier } val padding = (diameter - itemSizeAnchor) / 2 val density = LocalDensity.current val rollPickerScope = rememberUpdatedRollPickerScope( state = state, orientation = orientation, count = count, visibleCount = visibleCount, diameter = diameter, itemSizeAnchor = itemSizeAnchor, itemSize = itemSize, itemFontSize = density.run { itemSize.toSp() * 0.73f } ) val virtualCount = if (loop) Int.MAX_VALUE else count val startIndexOffset = if (loop) virtualCount / 2 else 0 val listState = rememberLazyListState( initialFirstVisibleItemIndex = startIndexOffset + state.initialIndex ) state.also { it.listState = listState it.loop = loop it.startIndexOffset = startIndexOffset it.actualCount = count } val curOnPick by rememberUpdatedState(newValue = onPick) LaunchedEffect(key1 = state) { snapshotFlow { state.isScrollInProgress } .drop(1) .filter { !it && state.currentIndexOffsetFraction == 0f } .map { state.currentIndex } .distinctUntilChanged() .collect { index -> curOnPick(index) } } val coroutineScope = rememberCoroutineScope() val internalOnItemClick: (Int) -> Unit = { index -> val rollPickerIndex = RollPickerIndex(state.mapIndex(index), index) onItemClick?.invoke(rollPickerIndex) ?: coroutineScope.launch { state.animateScrollToIndex(rollPickerIndex) } } val curOnFling by rememberUpdatedState(newValue = onFling) val curOrientation by rememberUpdatedState(newValue = orientation) val decayAnimationSpec = rememberSplineBasedDecay<Float>() val nestedScrollConnection = remember(rollPickerScope, state, coroutineScope) { val velocityRange = -absMaxVelocity..absMaxVelocity object : NestedScrollConnection { override suspend fun onPreFling(available: Velocity): Velocity { val internalOnFling = curOnFling if (internalOnFling != null) { return rollPickerScope.internalOnFling(available) } var lastValue = 0f AnimationState( initialValue = 0f, initialVelocity = when (curOrientation) { Orientation.Vertical -> available.y.coerceIn(velocityRange) else -> available.x.coerceIn(velocityRange) } ).animateDecay(animationSpec = decayAnimationSpec) { coroutineScope.launch { val delta = value - lastValue state.scrollBy(-delta) lastValue = value } } // snap state.animateScrollToIndex(index = state.currentIndex) return available } } } val pickerBox: @Composable (index: Int) -> Unit = { index -> val rollPickerIndex = RollPickerIndex(state.mapIndex(index), index) // 第一个 Box 固定位置,确保 snap 正常 Box( modifier = Modifier .run { if (orientation == Orientation.Vertical) { this .fillMaxWidth() .height(itemSizeAnchor) } else { this .fillMaxHeight() .width(itemSizeAnchor) } } .run { if (style !is Wheel) this else { wheelTransformation( state = state, index = rollPickerIndex, orientation = orientation, diameter = diameter, visibleCount = visibleCount, itemSizeAnchor = itemSizeAnchor ) } } .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { internalOnItemClick(index) }, contentAlignment = Alignment.Center ) { // 第二个 Box 实现 lineSpacingMultiplier 效果 Box( modifier = Modifier .run { if (orientation == Orientation.Vertical) { this .fillMaxWidth() .requiredHeight(itemSize) } else { this .fillMaxHeight() .requiredWidth(itemSize) } }, contentAlignment = Alignment.Center ) { rollPickerScope.itemContent(rollPickerIndex) } } } val rollPickerDrawScope = rollPickerScope.rememberRollPickerDrawScope() val drawWithCacheModifier = if (onDrawWithCache == null) Modifier else { Modifier .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen) .drawWithCache { rollPickerDrawScope.cacheDrawScope = this rollPickerDrawScope.onDrawWithCache() } } if (orientation == Orientation.Vertical) { LazyColumn( modifier = Modifier .then(drawWithCacheModifier) .fillMaxSize() .nestedScroll(nestedScrollConnection), state = listState, contentPadding = PaddingValues(vertical = padding) ) { items(virtualCount) { index -> pickerBox(index) } } } else { LazyRow( modifier = Modifier .then(drawWithCacheModifier) .fillMaxSize() .nestedScroll(nestedScrollConnection), state = listState, contentPadding = PaddingValues(horizontal = padding) ) { items(virtualCount) { index -> pickerBox(index) } } } } private fun Modifier.wheelTransformation( state: RollPickerState, index: RollPickerIndex, orientation: Orientation, diameter: Dp, visibleCount: Int, itemSizeAnchor: Dp ) = graphicsLayer { val offsetFraction = state.calculateOffsetFraction(index) val actualVisibleCount = visibleCount + 2 val actualSideVisibleCount = (actualVisibleCount - 1) / 2 val degree = offsetFraction * 90f / actualSideVisibleCount val safeDegree = degree.coerceIn(-90f, 90f) val scaleFactor = 1f - (safeDegree.absoluteValue / 90f) val radius = diameter.toPx() / 2f val radian = Math .toRadians(degree.toDouble()) .toFloat() val arcLength = sin(radian) * radius // 所有子项偏移到原点(选中区域) val initialTrans = itemSizeAnchor.toPx() * offsetFraction val transOffset = initialTrans - arcLength if (orientation == Orientation.Vertical) { scaleY = scaleFactor translationY = transOffset } else { scaleX = scaleFactor translationX = transOffset } } /** * 自适应子项空间,自动缩放字体大小 * * @param fontSizeRange 字体大小范围 * @param fitCenter 是否忽略基线位置偏移到中间 */ @Composable fun RollPickerScope.RollPickerText( text: String, modifier: Modifier = Modifier, fontSizeRange: FontSizeRange = FontSizeRange( min = 8.sp, max = run { val itemFontSize = itemFontSize if (itemFontSize < 8.sp) 8.sp else itemFontSize } ), maxLines: Int = 1, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, fitCenter: Boolean = true, style: TextStyle = LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace) ) { AutoResizeText( text = text, modifier = modifier .fillMaxSize() .wrapContentSize(), fontSizeRange = fontSizeRange, maxLines = maxLines, overflow = overflow, softWrap = softWrap, fitCenter = fitCenter, style = style ) } /** * 选择器作用域,提供参数 */ @Stable interface RollPickerScope { /** * 滚轮方向 */ val orientation: Orientation /** * 数据容量 */ val count: Int /** * 当前真实索引 */ val currentIndex: RollPickerIndex /** * 当前索引偏移值 */ val currentIndexOffsetFraction: Float /** * 可见子项数量 */ val visibleCount: Int /** * 直径,[VerticalRollPicker] 为高度,[HorizontalRollPicker] 为宽度 */ val diameter: Dp /** * 锚点子项大小,用来固定子项位置,例如滚轮的形变基于这个大小 */ val itemSizeAnchor: Dp /** * 子项大小 */ val itemSize: Dp /** * 子项字体大小 */ val itemFontSize: TextUnit /** * 计算给定索引偏移值 */ fun calculateOffsetFraction(index: RollPickerIndex): Float } private class RollPickerScopeImpl( state: RollPickerState ) : RollPickerScope { var state: RollPickerState by mutableStateOf(state) override var orientation: Orientation by mutableStateOf(Orientation.Vertical) override var count: Int by mutableStateOf(0) override val currentIndex: RollPickerIndex get() = state.currentIndex override val currentIndexOffsetFraction: Float get() = state.currentIndexOffsetFraction override var visibleCount: Int by mutableStateOf(0) override var diameter: Dp by mutableStateOf(0.dp) override var itemSizeAnchor: Dp by mutableStateOf(0.dp) override var itemSize: Dp by mutableStateOf(0.dp) override var itemFontSize: TextUnit by mutableStateOf(0.sp) override fun calculateOffsetFraction(index: RollPickerIndex): Float { return state.calculateOffsetFraction(index) } } @Composable private fun rememberUpdatedRollPickerScope( state: RollPickerState, orientation: Orientation, count: Int, visibleCount: Int, diameter: Dp, itemSizeAnchor: Dp, itemSize: Dp, itemFontSize: TextUnit ): RollPickerScope = remember { RollPickerScopeImpl(state) }.also { it.state = state it.orientation = orientation it.count = count it.visibleCount = visibleCount it.diameter = diameter it.itemSizeAnchor = itemSizeAnchor it.itemSize = itemSize it.itemFontSize = itemFontSize } /** * 绘制作用域,提供参数 */ @Stable interface RollPickerDrawScope : RollPickerScope, Density { val size: Size val layoutDirection: LayoutDirection fun onDrawBehind(block: DrawScope.() -> Unit): DrawResult fun onDrawWithContent(block: ContentDrawScope.() -> Unit): DrawResult override val density: Float override val fontScale: Float } private class RollPickerDrawScopeImpl( rollPickerScope: RollPickerScope, density: Density ) : RollPickerDrawScope, RollPickerScope by rollPickerScope, Density by density { var cacheDrawScope: CacheDrawScope? by mutableStateOf(null) override val size: Size get() = safeCall { size } override val layoutDirection: LayoutDirection get() = safeCall { layoutDirection } override val density: Float get() = safeCall { density } override val fontScale: Float get() = safeCall { fontScale } override fun onDrawBehind(block: DrawScope.() -> Unit): DrawResult { return safeCall { onDrawBehind(block) } } override fun onDrawWithContent(block: ContentDrawScope.() -> Unit): DrawResult { return safeCall { onDrawWithContent(block) } } private inline fun <T> safeCall(block: CacheDrawScope.() -> T): T { val cacheDrawScope = cacheDrawScope ?: error("RollPickerDrawScope is missing CacheDrawScope") return cacheDrawScope.block() } } @Composable private fun RollPickerScope.rememberRollPickerDrawScope(): RollPickerDrawScopeImpl { val density = LocalDensity.current return remember(this, density) { RollPickerDrawScopeImpl(this, density) } } /** * 选择器状态容器 */ @Composable fun rememberRollPickerState(initialIndex: Int = 0): RollPickerState { return remember { RollPickerState(initialIndex) } } @Stable class RollPickerState(val initialIndex: Int = 0) { internal var listState: LazyListState? by mutableStateOf(null) internal var loop: Boolean by mutableStateOf(false) internal var actualCount: Int by mutableStateOf(0) internal var startIndexOffset: Int by mutableStateOf(0) /** * 当前索引 */ val currentIndex: RollPickerIndex by derivedStateOf { val foundIndex = listState ?.layoutInfo ?.visibleItemsInfo ?.fastFirstOrNull { it.offset.absoluteValue <= it.size / 2f } ?.index ?: -1 RollPickerIndex(mapIndex(foundIndex), foundIndex) } /** * 当前索引偏移值 */ val currentIndexOffsetFraction: Float by derivedStateOf { val curItem = listState ?.layoutInfo ?.visibleItemsInfo ?.fastFirstOrNull { it.index == currentIndex.actualValue } ?: return@derivedStateOf 0f -curItem.offset / curItem.size.toFloat() } /** * 是否在滚动中 */ val isScrollInProgress: Boolean by derivedStateOf { listState?.isScrollInProgress ?: false } /** * 能否向前滚动,结束方向 */ val canScrollForward: Boolean get() = listState?.canScrollForward ?: false /** * 能否向后滚动,开始方向 */ val canScrollBackward: Boolean get() = listState?.canScrollBackward ?: false /** * 计算给定索引偏移值 */ fun calculateOffsetFraction(index: RollPickerIndex): Float { return (currentIndex.actualValue - index.actualValue) + currentIndexOffsetFraction } /** * 按像素滚动 */ suspend fun scrollBy(value: Float) { listState?.scrollBy(value) } /** * 立即滚动到给定索引 */ suspend fun scrollToIndex(index: RollPickerIndex) { animateScrollToIndex( index = index, animationSpec = snap() ) } /** * 动画形式滚动到给定索引 */ suspend fun animateScrollToIndex( index: RollPickerIndex, animationSpec: AnimationSpec<Float> = spring( stiffness = Spring.StiffnessMediumLow ) ) { val listState = listState ?: return val size = listState.layoutInfo.visibleItemsInfo.firstOrNull()?.size ?: return val fraction = calculateOffsetFraction(index) val scrollOffset = size * fraction listState.animateScrollBy( value = -scrollOffset, animationSpec = animationSpec ) } /** * 转换索引,在开启循环时真实索引过大,需要进行转换才能对应数据 */ internal fun mapIndex(index: Int): Int { if (!loop) return index return floorMod(index - startIndexOffset, actualCount) } private fun floorMod(value: Int, other: Int): Int = when (other) { 0 -> value else -> value - value.floorDiv(other) * other } } /** * 选择器风格 */ @Stable sealed class RollPickerStyle { /** * 滚轮 */ class Wheel : RollPickerStyle() { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } } /** * 扁平 * * @param halfExposed 是否露出一半消失的 item */ data class Flat(val halfExposed: Boolean = false) : RollPickerStyle() } fun RollPickerIndex(value: Int) = RollPickerIndex(value, -1) private fun RollPickerIndex(index: Int, actualIndex: Int) = RollPickerIndex(packInts(index, actualIndex)) @JvmInline value class RollPickerIndex internal constructor(private val packedValue: Long) { val value: Int get() = unpackInt1(packedValue) /** * 如果有真实索引存在则用真实索引,否则用 [value] */ internal val actualValue: Int get() { val index = unpackInt2(packedValue) return if (index == -1) value else index } operator fun plus(other: RollPickerIndex): RollPickerIndex { val offset = abs(value - other.value) return this + offset } operator fun plus(offset: Int): RollPickerIndex { return RollPickerIndex( index = value + offset, actualIndex = actualValue + offset ) } operator fun minus(other: RollPickerIndex): RollPickerIndex { val offset = abs(value - other.value) return this - offset } operator fun minus(offset: Int): RollPickerIndex { return RollPickerIndex( index = value - offset, actualIndex = actualValue - offset ) } } object RollPickerDefaults { const val VisibleCount = 5 const val LineSpacingMultiplier = 1f const val Loop = false const val MaxFlingVelocity = 3000f val Style = Wheel() private val ItemSize = 25.dp /** * 选中区域着色、形变 */ @Composable fun paintOnPick( color: Color = MaterialTheme.colorScheme.primary, scaleX: Float = 1.0f, scaleY: Float = 1.0f ): RollPickerDrawScope.() -> DrawResult { val block: RollPickerDrawScope.() -> DrawResult = { paintOnPick(color, scaleX, scaleY) } return block } private fun RollPickerDrawScope.paintOnPick( color: Color, scaleX: Float, scaleY: Float ): DrawResult { val path = Path().apply { val itemSizePx = itemSize.toPx() if (orientation == Orientation.Vertical) { val top = (size.height - itemSizePx) / 2f addRect( Rect( left = 0f, top = top, right = size.width, bottom = top + itemSizePx ) ) } else { val left = (size.width - itemSizePx) / 2f addRect( Rect( left = left, top = 0f, right = left + itemSizePx, bottom = size.height ) ) } } return onDrawWithContent { clipPath(path, clipOp = ClipOp.Difference) { [email protected]() } clipPath(path) { scale(scaleX = scaleX, scaleY = scaleY) { [email protected]() if (color.isSpecified) { drawRect( color = color, blendMode = BlendMode.SrcIn ) } } } } } internal fun getDefaultSize(style: RollPickerStyle, visibleCount: Int): Dp { val defaultItemSize = ItemSize if (style is Wheel) { return defaultItemSize * (visibleCount + 1) } else if (style is Flat && style.halfExposed) { return defaultItemSize * (visibleCount + 1) } return defaultItemSize * visibleCount } }
0
Kotlin
0
0
ff6dbddf9e11d43c6354626df6938fa21267d258
28,947
RollPicker
Apache License 2.0
app/src/main/java/org/kl/smartbuy/ui/purchase/PurchaseListScreen.kt
klappdev
274,739,460
false
null
/* * Licensed under the MIT License <http://opensource.org/licenses/MIT>. * SPDX-License-Identifier: MIT * Copyright (c) 2020 - 2022 https://github.com/klappdev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.kl.smartbuy.ui.purchase import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.items import org.kl.smartbuy.R import org.kl.smartbuy.db.entity.Purchase import org.kl.smartbuy.ui.common.CenterScreenText import org.kl.smartbuy.viewmodel.PurchaseListViewModel @Composable fun PurchaseListScreen( navigationController: NavHostController, viewModel: PurchaseListViewModel, ) { val purchases: LazyPagingItems<Purchase> = viewModel.purchases.collectAsLazyPagingItems() if (purchases.itemCount != 0) { LazyColumn( verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(top = 4.dp) ) { items(purchases) { purchase -> if (purchase != null) { PurchaseItem(purchase) } else { PurchaseItemPlaceholder() } } } } else { CenterScreenText(stringResource(R.string.empty_purchases)) } } @Composable private fun PurchaseItem(purchase: Purchase) { Row( verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.Center, modifier = Modifier.background(Color.White) ) { ImagePurchaseView() Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { NamePurchaseView(purchase) DatePurchaseView(purchase) } } } @Composable private fun PurchaseItemPlaceholder() { PurchaseItem(Purchase(-1, "<no name>", "<no date>")) } @Composable private fun ImagePurchaseView() { Image( painter = painterResource(R.drawable.purchase_icon), contentDescription = stringResource(R.string.purchase_name), modifier = Modifier .width(64.dp) .height(64.dp) .padding(10.dp) ) } @Composable private fun NamePurchaseView(purchase: Purchase) { Text( text = purchase.name, textAlign = TextAlign.Center, fontFamily = FontFamily.Serif, fontSize = 16.sp, color = Color.Gray, modifier = Modifier .fillMaxWidth() .padding(start = 36.dp, top = 8.dp, end = 4.dp, bottom = 4.dp) .wrapContentWidth(Alignment.Start) ) } @Composable private fun DatePurchaseView(purchase: Purchase) { Text( text = purchase.date, textAlign = TextAlign.Center, fontFamily = FontFamily.Serif, fontSize = 14.sp, color = Color.Gray, modifier = Modifier .fillMaxWidth() .padding(start = 36.dp, top = 8.dp, end = 4.dp, bottom = 4.dp) .wrapContentWidth(Alignment.Start) ) }
0
Kotlin
0
0
e008c690bb0b8e07879945be0557f54950c1325c
4,797
smartbuy
MIT License
BineClient/Sdk/bine-sdk/src/main/java/com/msr/bine_sdk/eventbus/events/AnalyticsEvent.kt
microsoft
563,698,948
false
{"Kotlin": 1296950, "Java": 406327, "Gherkin": 3712, "Shell": 1179}
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. package com.msr.bine_sdk.eventbus.events data class AnalyticsEvent (var key: String, var params: HashMap<String, String>?)
0
Kotlin
3
1
eed3f78a61c110714227f4709873d0193d65ec50
199
digital-content-distribution-toolkit-client
MIT License
app/src/main/java/my/id/andraaa/dstory/stories/util/SignaturedData.kt
andraantariksa
592,246,390
false
null
package my.id.andraaa.dstory.stories.util import android.graphics.Bitmap import java.nio.ByteBuffer import java.security.MessageDigest class SignaturedData(private var _value: Bitmap) { private val md5MessageDigest = MessageDigest.getInstance("MD5") var value: Bitmap get() = _value set(newValue) { _value = newValue refreshSignature() } private lateinit var _signature: ByteArray val signature get() = _signature init { refreshSignature() } fun refreshSignature() { val buffer = ByteBuffer.allocate(value.allocationByteCount) value.copyPixelsToBuffer(buffer) _signature = md5MessageDigest.digest(buffer.array()) } override fun equals(other: Any?): Boolean { if (other is SignaturedData) { return _signature.contentEquals(other._signature) } return super.equals(other) } override fun hashCode(): Int { return _signature.hashCode() } }
0
Kotlin
0
0
bc9cc47f11556c9c429161bf2ea715b546afc216
1,023
dicoding-a352-dstory
MIT License
src/test/kotlin/com/github/oshai/StatementAwaitTest.kt
oshai
85,758,623
false
null
package com.github.oshai import kotlinx.coroutines.experimental.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class StatementAwaitTest { @Test fun sendPreparedStatement() = runBlocking { val queryStatement = QueryStatement(statement = "select 1") val mockConnection = MockConnection() val sendPreparedStatement = queryStatement.sendPreparedStatement(mockConnection) assertEquals(mockConnection.queryResult, sendPreparedStatement.awaitQuery()) } }
0
Kotlin
0
2
c768466610ff44d3622aab1a706dc074e26e0ebd
520
kotlin-coroutines-mysql
Apache License 2.0
app/src/main/java/io/fastkv/fastkvdemo/data/UserInfo.kt
BillyWei01
416,593,131
false
{"Java": 260679, "Kotlin": 72600}
package io.fastkv.fastkvdemo.data import android.util.ArrayMap import io.fastkv.fastkvdemo.account.AccountInfo import io.fastkv.fastkvdemo.account.Gender import io.fastkv.fastkvdemo.base.AppContext import io.fastkv.fastkvdemo.fastkv.LongListEncoder import io.fastkv.fastkvdemo.fastkv.kvbase.UserKV import io.fastkv.interfaces.FastEncoder /** * 用户信息 */ class UserInfo(uid: Long): UserKV("user_info", uid) { companion object { private val map = ArrayMap<Long, UserInfo>() @Synchronized fun get(): UserInfo { return get(AppContext.uid) } @Synchronized fun get(uid: Long): UserInfo { return map.getOrPut(uid) { UserInfo(uid) } } } override fun encoders(): Array<FastEncoder<*>> { return arrayOf(AccountInfo.ENCODER, LongListEncoder) } var userAccount by obj("user_account", AccountInfo.ENCODER) var gender by intEnum("gender", Gender.CONVERTER) var isVip by boolean("is_vip") var fansCount by int("fans_count") var score by float("score") var loginTime by long("login_time") var balance by double("balance") var sign by string("sing") var lock by array("lock") var tags by stringSet("tags") var friendIdList by obj("favorite_channels", LongListEncoder) val favorites by string2Set("favorites") val config by combineKey("config") }
0
Java
37
329
ec30b26e7d9b562be3e299ecbbe94de1ae34dc9a
1,420
FastKV
MIT License
src/Day03.kt
akijowski
574,262,746
false
null
private val priorityList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun main() { // TODO: This is better fun priority(groups: List<String>): Int { val chars = groups.flatMap { it.toSet() } val sharedItem = chars.groupingBy { it }.eachCount().maxBy { it.value }.key return if (sharedItem.isUpperCase()) (sharedItem - 'A') + 27 else (sharedItem - 'a') + 1 } fun part1Other(input: List<String>): Int { val leftSide = mutableSetOf<Char>() val rightSide = mutableSetOf<Char>() var sum = 0 for (ruck in input) { var left = 0 var right = ruck.length - 1 while (left < right) { leftSide.add(ruck[left]) rightSide.add(ruck[right]) left++ right-- } leftSide.retainAll(rightSide) val match = leftSide.first() val i = priorityList.indexOfFirst { it == match } + 1 sum += i leftSide.clear() rightSide.clear() } return sum } fun part1(input: List<String>): Int { return input.map {it.chunked(it.length / 2)}.sumOf { priority(it) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { priority(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1Other(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
1,618
advent-of-code-2022
Apache License 2.0
cpg-core/src/test/kotlin/de/fraunhofer/aisec/cpg/enhancements/DFGTest.kt
Fraunhofer-AISEC
225,386,107
false
null
/* * Copyright (c) 2021, Fraunhofer AISEC. All rights reserved. * * 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 de.fraunhofer.aisec.cpg.enhancements import de.fraunhofer.aisec.cpg.TestUtils.analyze import de.fraunhofer.aisec.cpg.TestUtils.findByUniqueName import de.fraunhofer.aisec.cpg.graph.* import de.fraunhofer.aisec.cpg.graph.statements.expressions.* import java.nio.file.Path import kotlin.test.* internal class DFGTest { // Test DFG // Test ControlFlowSensitiveDFGPass /** * To test assignments of different value in an expression that then has a joinPoint. a = a == b * ? b = 2: b = 3; * * @throws Exception */ @Test @Throws(Exception::class) fun testConditionalExpression() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("conditional_expression.cpp").toFile()), topLevel, true) val bJoin = result.refs[{ it.name.localName == "b" && it.location?.region?.startLine == 6 }] val a5 = result.refs[{ it.name.localName == "a" && it.location?.region?.startLine == 5 }] val a6 = result.refs[{ it.name.localName == "a" && it.location?.region?.startLine == 6 }] val bCond = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 16 }] val b2 = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 16 }] val b3 = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 23 }] assertNotNull(bJoin) assertNotNull(bCond) assertNotNull(b2) assertNotNull(b3) assertNotNull(a5) assertNotNull(a6) val val2 = result.literals[{ it.value == 2 }] assertNotNull(val2) val val3 = result.literals[{ it.value == 3 }] assertNotNull(val3) assertEquals(1, b2.prevDFG.size) assertTrue(b2.prevDFG.contains(val2)) assertEquals(1, b3.prevDFG.size) assertTrue(b3.prevDFG.contains(val3)) // We want the ConditionalExpression assertEquals(1, a5.prevDFG.size) assertTrue(a5.prevDFG.first() is ConditionalExpression) assertTrue(flattenDFGGraph(a5, false).contains(val2)) assertTrue(flattenDFGGraph(a5, false).contains(val3)) assertEquals(1, a6.prevDFG.size) assertTrue(a6.prevDFG.contains(bJoin)) assertEquals(2, bJoin.prevDFG.size) // The b which got assigned 2 flows to the b in line 6 assertTrue(bJoin.prevDFG.contains(b2)) // The b which got assigned 3 flows to the b in line 6 assertTrue(bJoin.prevDFG.contains(b3)) } // Test DFG when ReadWrite access occurs, such as compound operators or unary operators @Test @Throws(Exception::class) fun testCompoundOperatorDFG() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("compoundoperator.cpp").toFile()), topLevel, true) val rwCompoundOperator = findByUniqueName(result.allChildren(), "+=") assertNotNull(rwCompoundOperator) val expression = findByUniqueName(result.refs, "i") assertNotNull(expression) val prevDFGOperator = rwCompoundOperator.prevDFG assertNotNull(prevDFGOperator) assertTrue(prevDFGOperator.contains(expression)) val nextDFGOperator = rwCompoundOperator.nextDFG assertNotNull(nextDFGOperator) assertTrue(nextDFGOperator.contains(expression)) } @Test @Throws(Exception::class) fun testUnaryOperatorDFG() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("unaryoperator.cpp").toFile()), topLevel, true) val rwUnaryOperator = findByUniqueName(result.allChildren<UnaryOperator>(), "++") assertNotNull(rwUnaryOperator) val expression = findByUniqueName(result.refs, "i") assertNotNull(expression) val prevDFGOperator: Set<Node> = rwUnaryOperator.prevDFG val nextDFGOperator: Set<Node> = rwUnaryOperator.nextDFG assertTrue(prevDFGOperator.contains(expression)) assertTrue(nextDFGOperator.contains(expression)) } /** * Gets Integer Literal from the List of nodes to simplify the test syntax. The Literal is * expected to be contained in the list and the function will throw an * [IndexOutOfBoundsException] otherwise. * * @param nodes * - The list of nodes to filter for the Literal. * * @param v * - The integer value expected from the Literal. * * @return The Literal with the specified value. */ private fun getLiteral(nodes: List<Node>, v: Int): Literal<*> { return nodes.filter { n: Node? -> n is Literal<*> && n.value == Integer.valueOf(v) }[0] as Literal<*> } /** * Traverses the DFG Graph induced by the provided node in the specified direction and retrieves * all nodes that are passed by and are therefore part of the incoming or outgoing data-flow. * * @param node * - The node that induces the DFG-subgraph for which nodes are retrieved * * @param outgoing * - true if the Data-Flow from this node should be considered, false if the data-flow is to * this node. * * @return A set of nodes that are part of the data-flow */ private fun flattenDFGGraph(node: Node?, outgoing: Boolean): Set<Node?> { if (node == null) { return setOf() } val dfgNodes = mutableSetOf<Node>() dfgNodes.add(node) val worklist = LinkedHashSet<Node>() worklist.add(node) while (worklist.isNotEmpty()) { val toProcess = worklist.iterator().next() worklist.remove(toProcess) // DataFlow direction val nextDFGNodes = if (outgoing) { toProcess.nextDFG } else { toProcess.prevDFG } // Adding all NEWLY discovered df-nodes to the work-list. for (dfgNode in nextDFGNodes) { if (!dfgNodes.contains(dfgNode)) { worklist.add(dfgNode) dfgNodes.add(dfgNode) } } } return dfgNodes } }
81
Kotlin
48
146
85d81208315e3c93c6734f55a214dd1a983120c0
7,861
cpg
Apache License 2.0
cpg-core/src/test/kotlin/de/fraunhofer/aisec/cpg/enhancements/DFGTest.kt
Fraunhofer-AISEC
225,386,107
false
null
/* * Copyright (c) 2021, Fraunhofer AISEC. All rights reserved. * * 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 de.fraunhofer.aisec.cpg.enhancements import de.fraunhofer.aisec.cpg.TestUtils.analyze import de.fraunhofer.aisec.cpg.TestUtils.findByUniqueName import de.fraunhofer.aisec.cpg.graph.* import de.fraunhofer.aisec.cpg.graph.statements.expressions.* import java.nio.file.Path import kotlin.test.* internal class DFGTest { // Test DFG // Test ControlFlowSensitiveDFGPass /** * To test assignments of different value in an expression that then has a joinPoint. a = a == b * ? b = 2: b = 3; * * @throws Exception */ @Test @Throws(Exception::class) fun testConditionalExpression() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("conditional_expression.cpp").toFile()), topLevel, true) val bJoin = result.refs[{ it.name.localName == "b" && it.location?.region?.startLine == 6 }] val a5 = result.refs[{ it.name.localName == "a" && it.location?.region?.startLine == 5 }] val a6 = result.refs[{ it.name.localName == "a" && it.location?.region?.startLine == 6 }] val bCond = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 16 }] val b2 = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 16 }] val b3 = result.refs[ { it.name.localName == "b" && it.location?.region?.startLine == 5 && it.location?.region?.startColumn == 23 }] assertNotNull(bJoin) assertNotNull(bCond) assertNotNull(b2) assertNotNull(b3) assertNotNull(a5) assertNotNull(a6) val val2 = result.literals[{ it.value == 2 }] assertNotNull(val2) val val3 = result.literals[{ it.value == 3 }] assertNotNull(val3) assertEquals(1, b2.prevDFG.size) assertTrue(b2.prevDFG.contains(val2)) assertEquals(1, b3.prevDFG.size) assertTrue(b3.prevDFG.contains(val3)) // We want the ConditionalExpression assertEquals(1, a5.prevDFG.size) assertTrue(a5.prevDFG.first() is ConditionalExpression) assertTrue(flattenDFGGraph(a5, false).contains(val2)) assertTrue(flattenDFGGraph(a5, false).contains(val3)) assertEquals(1, a6.prevDFG.size) assertTrue(a6.prevDFG.contains(bJoin)) assertEquals(2, bJoin.prevDFG.size) // The b which got assigned 2 flows to the b in line 6 assertTrue(bJoin.prevDFG.contains(b2)) // The b which got assigned 3 flows to the b in line 6 assertTrue(bJoin.prevDFG.contains(b3)) } // Test DFG when ReadWrite access occurs, such as compound operators or unary operators @Test @Throws(Exception::class) fun testCompoundOperatorDFG() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("compoundoperator.cpp").toFile()), topLevel, true) val rwCompoundOperator = findByUniqueName(result.allChildren(), "+=") assertNotNull(rwCompoundOperator) val expression = findByUniqueName(result.refs, "i") assertNotNull(expression) val prevDFGOperator = rwCompoundOperator.prevDFG assertNotNull(prevDFGOperator) assertTrue(prevDFGOperator.contains(expression)) val nextDFGOperator = rwCompoundOperator.nextDFG assertNotNull(nextDFGOperator) assertTrue(nextDFGOperator.contains(expression)) } @Test @Throws(Exception::class) fun testUnaryOperatorDFG() { val topLevel = Path.of("src", "test", "resources", "dfg") val result = analyze(listOf(topLevel.resolve("unaryoperator.cpp").toFile()), topLevel, true) val rwUnaryOperator = findByUniqueName(result.allChildren<UnaryOperator>(), "++") assertNotNull(rwUnaryOperator) val expression = findByUniqueName(result.refs, "i") assertNotNull(expression) val prevDFGOperator: Set<Node> = rwUnaryOperator.prevDFG val nextDFGOperator: Set<Node> = rwUnaryOperator.nextDFG assertTrue(prevDFGOperator.contains(expression)) assertTrue(nextDFGOperator.contains(expression)) } /** * Gets Integer Literal from the List of nodes to simplify the test syntax. The Literal is * expected to be contained in the list and the function will throw an * [IndexOutOfBoundsException] otherwise. * * @param nodes * - The list of nodes to filter for the Literal. * * @param v * - The integer value expected from the Literal. * * @return The Literal with the specified value. */ private fun getLiteral(nodes: List<Node>, v: Int): Literal<*> { return nodes.filter { n: Node? -> n is Literal<*> && n.value == Integer.valueOf(v) }[0] as Literal<*> } /** * Traverses the DFG Graph induced by the provided node in the specified direction and retrieves * all nodes that are passed by and are therefore part of the incoming or outgoing data-flow. * * @param node * - The node that induces the DFG-subgraph for which nodes are retrieved * * @param outgoing * - true if the Data-Flow from this node should be considered, false if the data-flow is to * this node. * * @return A set of nodes that are part of the data-flow */ private fun flattenDFGGraph(node: Node?, outgoing: Boolean): Set<Node?> { if (node == null) { return setOf() } val dfgNodes = mutableSetOf<Node>() dfgNodes.add(node) val worklist = LinkedHashSet<Node>() worklist.add(node) while (worklist.isNotEmpty()) { val toProcess = worklist.iterator().next() worklist.remove(toProcess) // DataFlow direction val nextDFGNodes = if (outgoing) { toProcess.nextDFG } else { toProcess.prevDFG } // Adding all NEWLY discovered df-nodes to the work-list. for (dfgNode in nextDFGNodes) { if (!dfgNodes.contains(dfgNode)) { worklist.add(dfgNode) dfgNodes.add(dfgNode) } } } return dfgNodes } }
81
Kotlin
48
146
85d81208315e3c93c6734f55a214dd1a983120c0
7,861
cpg
Apache License 2.0
domain/src/main/java/kr/ohyung/domain/executor/ExecutorProvider.kt
androiddevnotesforks
310,938,493
false
{"Kotlin": 243295}
/* * Created by <NAME> on 2020/09/19. */ package kr.ohyung.domain.executor import io.reactivex.Scheduler interface ExecutorProvider { fun io(): Scheduler fun mainThread(): Scheduler fun computation(): Scheduler fun newThread(): Scheduler }
0
Kotlin
2
1
c1567d938af59c3ca09c8dc15675358ba1abc63a
260
android-mvi-redux
MIT License
src/main/kotlin/imgui/imgui/widgets/listBoxes.kt
lb1987
181,112,500
true
{"Kotlin": 1613500, "C++": 13198, "Java": 9222}
package imgui.imgui.widgets import glm_.glm import glm_.vec2.Vec2 import imgui.* import imgui.ImGui.beginChildFrame import imgui.ImGui.beginGroup import imgui.ImGui.calcItemSize import imgui.ImGui.calcItemWidth import imgui.ImGui.calcTextSize import imgui.ImGui.currentWindow import imgui.ImGui.endChildFrame import imgui.ImGui.endGroup import imgui.ImGui.getId import imgui.ImGui.isRectVisible import imgui.ImGui.itemAdd import imgui.ImGui.itemSize import imgui.ImGui.markItemEdited import imgui.ImGui.popId import imgui.ImGui.pushId import imgui.ImGui.renderText import imgui.ImGui.sameLine import imgui.ImGui.selectable import imgui.ImGui.setItemDefaultFocus import imgui.ImGui.style import imgui.ImGui.textLineHeightWithSpacing import imgui.internal.Rect import kotlin.reflect.KMutableProperty0 import imgui.SelectableFlag as Sf import imgui.WindowFlag as Wf import imgui.internal.ButtonFlag as Bf import imgui.internal.ItemFlag as If /** * Widgets: List Boxes * - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them. */ interface listBoxes { fun listBox(label: String, currentItemPtr: KMutableProperty0<Int>, items: Array<String>, heightInItems: Int = -1): Boolean { var currentItem by currentItemPtr val itemsCount = items.size if (!listBoxHeader(label, itemsCount, heightInItems)) return false // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. var valueChanged = false // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. val clipper = ListClipper(itemsCount, textLineHeightWithSpacing) while (clipper.step()) for (i in clipper.display.start until clipper.display.last) withBool { itemSelected -> itemSelected.set(i == currentItem) val itemText = items.getOrElse(i) { "*Unknown item*" } pushId(i) if (selectable(itemText, itemSelected)) { currentItem = i valueChanged = true } if (itemSelected()) setItemDefaultFocus() popId() } listBoxFooter() if (valueChanged) markItemEdited(g.currentWindow!!.dc.lastItemId) return valueChanged } /** FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we * want to keep the same signature. * Helper to calculate the size of a listbox and display a label on the right. * Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty" */ fun listBoxHeader(label: String, sizeArg: Vec2 = Vec2()): Boolean { val window = currentWindow if (window.skipItems) return false val id = getId(label) val labelSize = calcTextSize(label, true) // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. val size = calcItemSize(sizeArg, calcItemWidth(), textLineHeightWithSpacing * 7.4f + style.itemSpacing.y) val frameSize = Vec2(size.x, glm.max(size.y, labelSize.y)) val frameBb = Rect(window.dc.cursorPos, window.dc.cursorPos + frameSize) val bb = Rect(frameBb.min, frameBb.max + Vec2(if (labelSize.x > 0f) style.itemInnerSpacing.x + labelSize.x else 0f, 0f)) window.dc.lastItemRect put bb // Forward storage for ListBoxFooter.. dodgy. if (!isRectVisible(bb.min, bb.max)) { itemSize(bb.size, style.framePadding.y) itemAdd(bb, 0, frameBb) return false } beginGroup() if (labelSize.x > 0) renderText(Vec2(frameBb.max.x + style.itemInnerSpacing.x, frameBb.min.y + style.framePadding.y), label) beginChildFrame(id, frameBb.size) return true } /** FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. */ fun listBoxHeader(label: String, itemsCount: Int, heightInItems_: Int = -1): Boolean { /* Size default to hold ~7.25 items. We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar. We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. */ val heightInItems = if (heightInItems_ < 0) glm.min(itemsCount, 7) else heightInItems_ val heightInItemsF = heightInItems + if (heightInItems < itemsCount) 0.25f else 0f /* We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). */ val size = Vec2(0f, textLineHeightWithSpacing * heightInItemsF + style.itemSpacing.y * 2f) return listBoxHeader(label, size) } /** FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. * Terminate the scrolling region. Only call ListBoxFooter() if ListBoxHeader() returned true! */ fun listBoxFooter() { val parentWindow = currentWindow.parentWindow!! val bb = parentWindow.dc.lastItemRect // assign is safe, itemSize() won't modify bb endChildFrame() /* Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) We call SameLine() to restore DC.CurrentLine* data */ sameLine() parentWindow.dc.cursorPos put bb.min itemSize(bb, style.framePadding.y) endGroup() } companion object { // TODO move/delete private inline fun <R> withBool(block: (KMutableProperty0<Boolean>) -> R): R { Ref.bPtr++ return block(Ref::bool).also { Ref.bPtr-- } } private inline fun <R> withInt(block: (KMutableProperty0<Int>) -> R): R { Ref.iPtr++ return block(Ref::int).also { Ref.iPtr-- } } } }
0
Kotlin
0
0
887a3b955674475612f5abefc4bcb8538ea9fde7
6,596
imgui
MIT License
app/src/main/java/vegabobo/dsusideloader/installer/adb/AdbInstallationHandler.kt
VegaBobo
454,183,288
false
null
package vegabobo.dsusideloader.installer.adb import vegabobo.dsusideloader.core.StorageManager import vegabobo.dsusideloader.model.Session /** * Generate shell script with installation * Used only for installing over adb commands */ class AdbInstallationHandler( private val storageManager: StorageManager, val session: Session ) { fun generate(onGenerated: (String) -> Unit) { val installationScriptPath = GenerateInstallationScript( storageManager, session.getInstallationParameters(), session.preferences ).writeToFile() onGenerated(installationScriptPath) } }
47
null
69
981
70cb6da9ecf9ae19c72ea680b02f1a0e20c77653
645
DSU-Sideloader
Apache License 2.0
src/test/kotlin/dev/usbharu/hideout/activitypub/service/activity/follow/APSendFollowServiceImplTest.kt
usbharu
627,026,893
false
{"Kotlin": 1337734, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 341}
/* * Copyright (C) 2024 usbharu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.usbharu.hideout.activitypub.service.activity.follow import dev.usbharu.hideout.activitypub.domain.model.Follow import dev.usbharu.hideout.activitypub.service.common.APRequestService import dev.usbharu.hideout.application.config.ApplicationConfig import dev.usbharu.hideout.core.service.follow.SendFollowDto import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Test import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import utils.UserBuilder import java.net.URL class APSendFollowServiceImplTest { @Test fun `sendFollow フォローするユーザーのinboxにFollowオブジェクトが送られる`() = runTest { val apRequestService = mock<APRequestService>() val applicationConfig = ApplicationConfig(URL("https://example.com")) val apSendFollowServiceImpl = APSendFollowServiceImpl(apRequestService, applicationConfig) val sendFollowDto = SendFollowDto( UserBuilder.localUserOf(), UserBuilder.remoteUserOf() ) apSendFollowServiceImpl.sendFollow(sendFollowDto) val value = Follow( apObject = sendFollowDto.followTargetActorId.url, actor = sendFollowDto.actorId.url, id = "${applicationConfig.url}/follow/${sendFollowDto.actorId.id}/${sendFollowDto.followTargetActorId.id}" ) verify(apRequestService, times(1)).apPost( eq(sendFollowDto.followTargetActorId.inbox), eq(value), eq(sendFollowDto.actorId) ) } }
38
Kotlin
0
9
5512c43ffacf0480f652465ccf5f71b559387592
2,154
Hideout
Apache License 2.0
app/src/main/java/kz/oqu/android/model/repositories/lesson/LessonCallbacks.kt
abikko
362,209,725
false
null
package kz.oqu.android.model.repositories.lesson import kz.oqu.android.model.pojo.Lesson interface LessonCallbacks { fun onShowProgressBar() fun onHideProgressBar(arrayList: ArrayList<Lesson>) fun onFailure(text: String) }
0
Kotlin
0
2
5b9b8dd259634831a3057b50d4dc6425c421c216
240
oqutushy.kz
MIT License
libraries/arch/src/main/java/com/fappslab/seedcake/libraries/arch/testing/FileLoader.kt
F4bioo
693,834,465
false
{"Kotlin": 401014, "Python": 2583, "Shell": 900}
package com.fappslab.seedcake.libraries.arch.testing import androidx.annotation.VisibleForTesting import com.fappslab.seedcake.libraries.extension.emptyString import java.io.BufferedReader import java.io.FileNotFoundException import java.lang.reflect.Modifier @Suppress("MaxLineLength") @VisibleForTesting(otherwise = Modifier.PRIVATE) object FileLoader { fun readFromJsonFile(jsonFile: String): String { val classLoader = Thread.currentThread().contextClassLoader val inputStream = classLoader?.getResourceAsStream(jsonFile) ?: throw FileNotFoundException("Resource '$jsonFile' not found. Ensure it's in 'src/main/resources' or 'src/test/resources'.") return inputStream.bufferedReader() .use(BufferedReader::readText) .replace("\\s".toRegex(), emptyString()) } }
0
Kotlin
0
1
b126728e15261c877943736d592d7d269618a114
836
Seedcake
MIT License
android/src/main/kotlin/com/dgsd/android/solar/repository/SolanaApiRepository.kt
dlgrech
554,689,573
false
null
package com.dgsd.android.solar.repository import com.dgsd.android.solar.cache.CacheStrategy import com.dgsd.android.solar.common.model.Resource import com.dgsd.android.solar.model.LamportsWithTimestamp import com.dgsd.android.solar.model.TransactionOrSignature import com.dgsd.ksol.core.model.* import kotlinx.coroutines.flow.Flow import java.io.Closeable interface SolanaApiRepository : Closeable { fun getBalance( cacheStrategy: CacheStrategy = CacheStrategy.CACHE_IF_PRESENT, commitment: Commitment = Commitment.FINALIZED ): Flow<Resource<LamportsWithTimestamp>> fun getBalanceOfAccount( account: PublicKey, cacheStrategy: CacheStrategy = CacheStrategy.CACHE_IF_PRESENT, commitment: Commitment = Commitment.FINALIZED ): Flow<Resource<LamportsWithTimestamp>> fun getTransactions( cacheStrategy: CacheStrategy = CacheStrategy.CACHE_IF_PRESENT, beforeSignature: TransactionSignature? = null, commitment: Commitment = Commitment.FINALIZED ): Flow<Resource<List<Resource<TransactionOrSignature>>>> fun getTransaction( cacheStrategy: CacheStrategy = CacheStrategy.CACHE_IF_PRESENT, transactionSignature: TransactionSignature, commitment: Commitment = Commitment.FINALIZED ): Flow<Resource<Transaction>> fun getRecentBlockhash(): Flow<Resource<RecentBlockhashResult>> fun send( privateKey: PrivateKey, recipient: PublicKey, lamports: Lamports, memo: String? = null ): Flow<Resource<TransactionSignature>> fun signAndSend( privateKey: PrivateKey, localTransaction: LocalTransaction, ): Flow<Resource<TransactionSignature>> fun subscribeToUpdates( transactionSignature: TransactionSignature, commitment: Commitment = Commitment.FINALIZED ): SubscriptionHandle<TransactionSignatureStatus> }
0
Kotlin
0
2
71a011c48270c971b2f1328b5d9d741dedeb97df
1,799
solar-wallet
Apache License 2.0
src/Day03.kt
BionicCa
574,904,899
false
{"Kotlin": 20039}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 for (rucksack in input) { val chunks = rucksack.chunked(rucksack.length / 2) val commonElements = findCommonCharacter(chunks[0].toCharArray(), chunks[1].toCharArray()) val score = commonElements.sumOf { when { it.isLowerCase() -> it.code - 96 // a - z -> 1 - 26 else -> it.code - 38// A - Z -> 27 - 52 } } totalScore += score } return totalScore } fun part2(input: List<String>): Int { val chunks = input.windowed(3, step = 3) var totalScore = 0 for (rucksackGroup in chunks) { val commonElements = findCommonCharacter( findCommonCharacter(rucksackGroup[0].toCharArray(), rucksackGroup[1].toCharArray()).toCharArray(), rucksackGroup[2].toCharArray() ) val score = commonElements.sumOf { when { it.isLowerCase() -> it.code - 96 // a - z -> 1 - 26 else -> it.code - 38// A - Z -> 27 - 52 } } totalScore += score } return totalScore } val testInput = readInput("Day03_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed8bda8067386b6cd86ad9704bda5eac81bf0163
1,488
AdventOfCode2022
Apache License 2.0
bloc_weather/android/app/src/main/kotlin/com/vasilevkin/bloc_weather/MainActivity.kt
vasilevkin
296,285,861
false
{"Dart": 471677, "Swift": 3232, "Ruby": 1354, "Kotlin": 1080, "Objective-C": 304}
package com.vasilevkin.bloc_weather import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
c63d543d10ac2df577cea4277da58cf4a7eeaf26
132
flutter_architecture_evolution
MIT License
CustomBottomSheet/src/main/java/com/naserkarimi/custombottomsheet/StateChangedCallback.kt
naserkarimi
376,275,067
false
{"Gradle": 4, "Java Properties": 1, "Text": 1, "Markdown": 1, "INI": 1, "Proguard": 2, "Ignore List": 2, "Kotlin": 4, "XML": 17, "Java": 3}
package com.naserkarimi.custombottomsheet interface StateChangedCallback { fun onHidden() fun onCollapsed() fun onExpanded() }
1
null
1
1
335397bfa154e005cb481de168bfe59f08c1fe9f
139
CustomBottomSheet
Apache License 2.0
java-agent/src/commonMain/kotlin/com/epam/drill/agent/request/RequestHolder.kt
Drill4J
240,284,351
false
{"Kotlin": 225265, "Java": 57214, "Batchfile": 410, "Shell": 329}
/** * Copyright 2020 - 2022 EPAM Systems * * 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.epam.drill.agent.request import com.epam.drill.common.agent.request.DrillRequest import com.epam.drill.common.agent.request.RequestHolder expect object DrillRequestHolder : RequestHolder { override fun remove() override fun retrieve(): DrillRequest? override fun store(drillRequest: DrillRequest) fun store(drillRequest: ByteArray) fun dump(): ByteArray? fun init(isAsync: Boolean) }
8
Kotlin
2
5
bfbd54284a1e6b8cc22da594333f75217265489b
1,021
java-agent
Apache License 2.0
app/src/main/java/com/sedsoftware/yaptalker/presentation/provider/ThumbnailsProvider.kt
djkovrik
98,050,611
false
null
package com.sedsoftware.yaptalker.presentation.provider import android.widget.ImageView interface ThumbnailsProvider { fun loadThumbnail(videoUrl: String, imageView: ImageView) }
0
Kotlin
4
9
465c34c3dc0dd0488b637073fddf6cd797e78613
185
YapTalker
Apache License 2.0
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/filter/VcsLogClassicFilterUi.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.ui.filter import com.intellij.execution.ui.FragmentedSettingsUtil import com.intellij.ide.HelpTooltip import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.actionSystem.impl.FieldInplaceActionButtonLook import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ClientProperty import com.intellij.ui.DocumentAdapter import com.intellij.ui.SearchTextField import com.intellij.ui.components.SearchFieldWithExtension import com.intellij.util.EventDispatcher import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.VcsLogRangeFilter.RefRange import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.VcsLogStorage import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties.PropertiesChangeListener import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.VcsLogActionIds import com.intellij.vcs.log.ui.VcsLogColorManager import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcs.log.ui.filter.FilterModel.PairFilterModel import com.intellij.vcs.log.ui.filter.FilterModel.SingleFilterModel import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx.VcsLogFilterListener import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.VisiblePack import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import com.intellij.vcsUtil.VcsUtil import com.intellij.xml.util.XmlStringUtil import org.jetbrains.annotations.NonNls import java.awt.Component import java.awt.Dimension import java.awt.event.ActionEvent import java.util.function.Consumer import java.util.function.Supplier import java.util.regex.Pattern import javax.swing.Icon import javax.swing.JComponent import javax.swing.event.DocumentEvent open class VcsLogClassicFilterUi(private val logData: VcsLogData, filterConsumer: Consumer<VcsLogFilterCollection>, private val uiProperties: MainVcsLogUiProperties, private val colorManager: VcsLogColorManager, filters: VcsLogFilterCollection?, parentDisposable: Disposable) : VcsLogFilterUiEx { private var dataPack: VcsLogDataPack protected val branchFilterModel: BranchFilterModel protected val userFilterModel: SingleFilterModel<VcsLogUserFilter> protected val dateFilterModel: DateFilterModel protected val structureFilterModel: FileFilterModel protected val textFilterModel: TextFilterModel private val textFilterField: VcsLogTextFilterField private val filterListenerDispatcher = EventDispatcher.create(VcsLogFilterListener::class.java) init { dataPack = VisiblePack.EMPTY val dataPackGetter = Supplier { dataPack } branchFilterModel = BranchFilterModel(dataPackGetter, logData.storage, logData.roots, uiProperties, filters) userFilterModel = UserFilterModel(uiProperties, filters) dateFilterModel = DateFilterModel(uiProperties, filters) structureFilterModel = FileFilterModel(logData.logProviders.keys, uiProperties, filters) textFilterModel = TextFilterModel(uiProperties, filters, parentDisposable) val field = TextFilterField(textFilterModel, parentDisposable) val toolbar = createTextActionsToolbar(field.textEditor) textFilterField = MyVcsLogTextFilterField(SearchFieldWithExtension(toolbar.component, field)) val models = arrayOf(branchFilterModel, userFilterModel, dateFilterModel, structureFilterModel, textFilterModel) for (model in models) { model.addSetFilterListener { filterConsumer.accept(getFilters()) filterListenerDispatcher.multicaster.onFiltersChanged() branchFilterModel.onStructureFilterChanged(structureFilterModel.rootFilter, structureFilterModel.structureFilter) } } } override fun updateDataPack(newDataPack: VcsLogDataPack) { dataPack = newDataPack } override fun getTextFilterComponent(): VcsLogTextFilterField = textFilterField private class MyActionButton(action: AnAction, presentation: Presentation) : ActionButton(action, presentation, "Vcs.Log.SearchTextField", ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { init { updateIcon() } override fun getPopState(): Int { return if (isSelected) SELECTED else super.getPopState() } override fun getIcon(): Icon { if (isEnabled && isSelected) { val selectedIcon = myPresentation.selectedIcon if (selectedIcon != null) return selectedIcon } return super.getIcon() } } private class MyVcsLogTextFilterField(private val searchField: SearchFieldWithExtension) : VcsLogTextFilterField { override val component: JComponent get() = searchField override val focusedComponent: JComponent get() = searchField.textField override var text: String get() = searchField.textField.text set(s) { searchField.textField.text = s } } override fun createActionGroup(): ActionGroup { val actions = listOfNotNull(createBranchComponent(), createUserComponent(), createDateComponent(), createStructureFilterComponent()) return DefaultActionGroup(actions) } @RequiresEdt override fun getFilters(): VcsLogFilterCollection { return VcsLogFilterObject.collection(branchFilterModel.branchFilter, branchFilterModel.revisionFilter, branchFilterModel.rangeFilter, textFilterModel.filter1, textFilterModel.filter2, structureFilterModel.filter1, structureFilterModel.filter2, dateFilterModel.getFilter(), userFilterModel.getFilter()) } @RequiresEdt override fun setFilters(collection: VcsLogFilterCollection) { branchFilterModel.setFilter(BranchFilters(collection.get(VcsLogFilterCollection.BRANCH_FILTER), collection.get(VcsLogFilterCollection.REVISION_FILTER), collection.get(VcsLogFilterCollection.RANGE_FILTER))) structureFilterModel.setFilter(FilterPair(collection.get(VcsLogFilterCollection.STRUCTURE_FILTER), collection.get(VcsLogFilterCollection.ROOT_FILTER))) dateFilterModel.setFilter(collection.get(VcsLogFilterCollection.DATE_FILTER)) textFilterModel.setFilter(FilterPair(collection.get(VcsLogFilterCollection.TEXT_FILTER), collection.get(VcsLogFilterCollection.HASH_FILTER))) userFilterModel.setFilter(collection.get(VcsLogFilterCollection.USER_FILTER)) } protected open fun createBranchComponent(): AnAction? { return FilterActionComponent(VcsLogBundle.messagePointer("vcs.log.branch.filter.action.text")) { BranchFilterPopupComponent(uiProperties, branchFilterModel).initUi() } } protected fun createUserComponent(): AnAction? { return FilterActionComponent(VcsLogBundle.messagePointer("vcs.log.user.filter.action.text")) { UserFilterPopupComponent(uiProperties, logData, userFilterModel).initUi() } } protected fun createDateComponent(): AnAction? { return FilterActionComponent(VcsLogBundle.messagePointer("vcs.log.date.filter.action.text")) { DateFilterPopupComponent(dateFilterModel).initUi() } } protected fun createStructureFilterComponent(): AnAction? { return FilterActionComponent(VcsLogBundle.messagePointer("vcs.log.path.filter.action.text")) { StructureFilterPopupComponent(uiProperties, structureFilterModel, colorManager).initUi() } } override fun addFilterListener(listener: VcsLogFilterListener) { filterListenerDispatcher.addListener(listener) } protected class FilterActionComponent(dynamicText: Supplier<String?>, private val componentCreator: Supplier<out JComponent>) : DumbAwareAction(dynamicText), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String): JComponent = componentCreator.get() override fun actionPerformed(e: AnActionEvent) { val vcsLogUi = e.getData(VcsLogInternalDataKeys.MAIN_UI) if (vcsLogUi == null) return val actionComponent = UIUtil.uiTraverser(vcsLogUi.toolbar).traverse().find { component: Component? -> ClientProperty.get(component, CustomComponentAction.ACTION_KEY) === this } if (actionComponent is VcsLogPopupComponent) { actionComponent.showPopupMenu() } } } class BranchFilterModel internal constructor(private val dataPackProvider: Supplier<out VcsLogDataPack>, private val storage: VcsLogStorage, private val roots: Collection<VirtualFile>, properties: MainVcsLogUiProperties, filters: VcsLogFilterCollection?) : FilterModel<BranchFilters>(properties) { var visibleRoots: Collection<VirtualFile>? = null private set init { if (filters != null) { saveFilterToProperties(BranchFilters(filters.get(VcsLogFilterCollection.BRANCH_FILTER), filters.get(VcsLogFilterCollection.REVISION_FILTER), filters.get(VcsLogFilterCollection.RANGE_FILTER))) } } override fun setFilter(filter: BranchFilters?) { var newFilters = filter if (newFilters != null && newFilters.isEmpty()) newFilters = null var anyFilterDiffers = false if (newFilters?.branchFilter != _filter?.branchFilter) { if (newFilters?.branchFilter != null) VcsLogUsageTriggerCollector.triggerFilterSet(VcsLogFilterCollection.BRANCH_FILTER.name) anyFilterDiffers = true } if (newFilters?.revisionFilter != _filter?.revisionFilter) { if (newFilters?.revisionFilter != null) VcsLogUsageTriggerCollector.triggerFilterSet(VcsLogFilterCollection.REVISION_FILTER.name) anyFilterDiffers = true } if (newFilters?.rangeFilter != _filter?.rangeFilter) { if (newFilters?.rangeFilter != null) VcsLogUsageTriggerCollector.triggerFilterSet(VcsLogFilterCollection.RANGE_FILTER.name) anyFilterDiffers = true } if (anyFilterDiffers) { super.setFilter(newFilters) } } override fun saveFilterToProperties(filter: BranchFilters?) { uiProperties.saveFilterValues(VcsLogFilterCollection.BRANCH_FILTER.name, filter?.branchFilter?.let { getBranchFilterValues(it) }) uiProperties.saveFilterValues(VcsLogFilterCollection.REVISION_FILTER.name, filter?.revisionFilter?.let { getRevisionFilterValues(it) }) uiProperties.saveFilterValues(VcsLogFilterCollection.RANGE_FILTER.name, filter?.rangeFilter?.let { getRangeFilterValues(it) }) } override fun getFilterFromProperties(): BranchFilters? { val branchFilterValues = uiProperties.getFilterValues(VcsLogFilterCollection.BRANCH_FILTER.name) val branchFilter = branchFilterValues?.let { createBranchFilter(it) } val revisionFilterValues = uiProperties.getFilterValues(VcsLogFilterCollection.REVISION_FILTER.name) val revisionFilter = revisionFilterValues?.let { createRevisionFilter(it) } val rangeFilterValues = uiProperties.getFilterValues(VcsLogFilterCollection.RANGE_FILTER.name) val rangeFilter = rangeFilterValues?.let { createRangeFilter(it) } if (branchFilter == null && revisionFilter == null && rangeFilter == null) return null return BranchFilters(branchFilter, revisionFilter, rangeFilter) } fun onStructureFilterChanged(rootFilter: VcsLogRootFilter?, structureFilter: VcsLogStructureFilter?) { if (rootFilter == null && structureFilter == null) { visibleRoots = null } else { visibleRoots = VcsLogUtil.getAllVisibleRoots(roots, rootFilter, structureFilter) } } val dataPack: VcsLogDataPack get() = dataPackProvider.get() private fun createBranchFilter(values: List<String>): VcsLogBranchFilter { return VcsLogFilterObject.fromBranchPatterns(values, dataPack.refs.branches.mapTo(mutableSetOf()) { it.name }) } private fun createRevisionFilter(values: List<String>): VcsLogRevisionFilter { val pattern = Pattern.compile("\\[(.*)\\](" + VcsLogUtil.HASH_REGEX.pattern() + ")") return VcsLogFilterObject.fromCommits(values.mapNotNull { s: String -> val matcher = pattern.matcher(s) if (!matcher.matches()) { if (VcsLogUtil.isFullHash(s)) { val commitId = findCommitId(HashImpl.build(s)) if (commitId != null) return@mapNotNull commitId } LOG.warn("Could not parse '$s' while creating revision filter") return@mapNotNull null } val result = matcher.toMatchResult() val root = LocalFileSystem.getInstance().findFileByPath(result.group(1)) if (root == null) { LOG.warn("Root '" + result.group(1) + "' does not exist") return@mapNotNull null } else if (!roots.contains(root)) { LOG.warn("Root '" + result.group(1) + "' is not registered") return@mapNotNull null } CommitId(HashImpl.build(result.group(2)), root) }) } private fun findCommitId(hash: Hash): CommitId? { for (root in roots) { val commitId = CommitId(hash, root) if (storage.containsCommit(commitId)) { return commitId } } return null } fun createFilterFromPresentation(values: List<String>): BranchFilters? { val hashes = mutableListOf<String>() val branches = mutableListOf<String>() val ranges = mutableListOf<String>() for (s in values) { val twoDots = s.indexOf("..") if (twoDots > 0 && twoDots == s.lastIndexOf("..")) { ranges.add(s) } else if (VcsLogUtil.isFullHash(s)) { hashes.add(s) } else { branches.add(s) } } val branchFilter = if (branches.isEmpty()) null else createBranchFilter(branches) val hashFilter = if (hashes.isEmpty()) null else createRevisionFilter(hashes) val refDiffFilter = if (ranges.isEmpty()) null else createRangeFilter(ranges) return BranchFilters(branchFilter, hashFilter, refDiffFilter) } var branchFilter: VcsLogBranchFilter? get() = getFilter()?.branchFilter set(branchFilter) { setFilter(BranchFilters(branchFilter, null, null)) } val revisionFilter: VcsLogRevisionFilter? get() = getFilter()?.revisionFilter var rangeFilter: VcsLogRangeFilter? get() = getFilter()?.rangeFilter set(rangeFilter) { setFilter(BranchFilters(null, null, rangeFilter)) } companion object { private const val TWO_DOTS = ".." private fun createRangeFilter(values: List<String>): VcsLogRangeFilter? { val ranges = values.mapNotNull { value: String -> val twoDots = value.indexOf(TWO_DOTS) if (twoDots <= 0) { LOG.error("Incorrect range filter value: $values") return@mapNotNull null } RefRange(value.substring(0, twoDots), value.substring(twoDots + TWO_DOTS.length)) } if (ranges.isEmpty()) return null return VcsLogFilterObject.fromRange(ranges) } private fun getBranchFilterValues(filter: VcsLogBranchFilter): List<String> { return ArrayList(filter.textPresentation.sorted()) } private fun getRevisionFilterValues(filter: VcsLogRevisionFilter): List<String> { return filter.heads.map { id -> "[" + id.root.path + "]" + id.hash.asString() } } private fun getRangeFilterValues(rangeFilter: VcsLogRangeFilter): List<String> { return ArrayList(rangeFilter.getTextPresentation()) } private fun getRevisionFilter2Presentation(filter: VcsLogRevisionFilter): List<String> { return filter.heads.map { id -> id.hash.asString() } } @JvmStatic fun getFilterPresentation(filters: BranchFilters): List<String> { val branchFilterValues = filters.branchFilter?.let { getBranchFilterValues(it) } ?: emptyList() val revisionFilterValues = filters.revisionFilter?.let { getRevisionFilter2Presentation(it) } ?: emptyList() val rangeFilterValues = filters.rangeFilter?.let { getRangeFilterValues(filters.rangeFilter) } ?: emptyList() return branchFilterValues + revisionFilterValues + rangeFilterValues } } } protected class TextFilterModel internal constructor(properties: MainVcsLogUiProperties, filters: VcsLogFilterCollection?, parentDisposable: Disposable) : PairFilterModel<VcsLogTextFilter, VcsLogHashFilter>(VcsLogFilterCollection.TEXT_FILTER, VcsLogFilterCollection.HASH_FILTER, properties, filters) { init { if (filters != null) { val textFilter = filters.get(VcsLogFilterCollection.TEXT_FILTER) if (textFilter != null) { uiProperties.set(MainVcsLogUiProperties.TEXT_FILTER_MATCH_CASE, textFilter.matchesCase()) uiProperties.set(MainVcsLogUiProperties.TEXT_FILTER_REGEX, textFilter.isRegex) } } val listener: PropertiesChangeListener = object : PropertiesChangeListener { override fun <T> onPropertyChanged(property: VcsLogUiProperty<T>) { if (MainVcsLogUiProperties.TEXT_FILTER_REGEX == property || MainVcsLogUiProperties.TEXT_FILTER_MATCH_CASE == property) { if (filter1 != null) { _filter = getFilterFromProperties() notifyFiltersChanged() } } } } properties.addChangeListener(listener, parentDisposable) } override fun getFilterFromProperties(): FilterPair<VcsLogTextFilter, VcsLogHashFilter>? { val filterPair: FilterPair<VcsLogTextFilter, VcsLogHashFilter>? = super.getFilterFromProperties() if (filterPair == null) return null var textFilter = filterPair.filter1 var hashFilter = filterPair.filter2 // check filters correctness if (textFilter != null && textFilter.text.isBlank()) { LOG.warn("Saved text filter is empty. Removing.") textFilter = null } if (textFilter != null) { val hashFilterFromText = VcsLogFilterObject.fromHash(textFilter.text) if (hashFilter != hashFilterFromText) { LOG.warn("Saved hash filter " + hashFilter + " is inconsistent with text filter." + " Replacing with " + hashFilterFromText) hashFilter = hashFilterFromText } } else if (hashFilter != null && !hashFilter.hashes.isEmpty()) { textFilter = createTextFilter(StringUtil.join(hashFilter.hashes, " ")) LOG.warn("Saved hash filter " + hashFilter + " is inconsistent with empty text filter. Using text filter " + textFilter) } return FilterPair(textFilter, hashFilter) } val text: String get() = filter1?.text ?: "" override fun getFilter1Values(filter1: VcsLogTextFilter): List<String> = listOf(filter1.text) override fun getFilter2Values(filter2: VcsLogHashFilter): List<String> = ArrayList(filter2.hashes) override fun createFilter1(values: List<String>): VcsLogTextFilter = createTextFilter(values.first()) override fun createFilter2(values: List<String>): VcsLogHashFilter = VcsLogFilterObject.fromHashes(values) private fun createTextFilter(text: String): VcsLogTextFilter { return VcsLogFilterObject.fromPattern(text, uiProperties.get(MainVcsLogUiProperties.TEXT_FILTER_REGEX), uiProperties.get(MainVcsLogUiProperties.TEXT_FILTER_MATCH_CASE)) } fun setFilterText(text: String) { if (text.isBlank()) { setFilter(null) } else { val textFilter = createTextFilter(text) val hashFilter = VcsLogFilterObject.fromHash(text) setFilter(FilterPair(textFilter, hashFilter)) } } } class FileFilterModel(val roots: Set<VirtualFile>, uiProperties: MainVcsLogUiProperties, filters: VcsLogFilterCollection?) : PairFilterModel<VcsLogStructureFilter, VcsLogRootFilter>(VcsLogFilterCollection.STRUCTURE_FILTER, VcsLogFilterCollection.ROOT_FILTER, uiProperties, filters) { override fun getFilter1Values(filter1: VcsLogStructureFilter): List<String> = getFilterValues(filter1) override fun getFilter2Values(filter2: VcsLogRootFilter): List<String> = getRootFilterValues(filter2) override fun createFilter1(values: List<String>): VcsLogStructureFilter = createStructureFilter(values) override fun createFilter2(values: List<String>): VcsLogRootFilter? { val selectedRoots: MutableList<VirtualFile> = ArrayList() for (path in values) { val root = LocalFileSystem.getInstance().findFileByPath(path) if (root != null) { if (roots.contains(root)) { selectedRoots.add(root) } else { LOG.warn("Can not find VCS root for filtering $root") } } else { LOG.warn("Can not filter by root that does not exist $path") } } if (selectedRoots.isEmpty()) return null return VcsLogFilterObject.fromRoots(selectedRoots) } val rootFilter: VcsLogRootFilter? get() = filter2 var structureFilter: VcsLogStructureFilter? get() = filter1 private set(filter) { setFilter(FilterPair(filter, null)) } companion object { private const val DIR: @NonNls String = "dir:" private const val FILE: @NonNls String = "file:" fun getRootFilterValues(filter: VcsLogRootFilter): List<String> { return filter.roots.map { it.path } } @JvmStatic fun getFilterValues(filter: VcsLogStructureFilter): List<String> { return filter.files.map { path -> (if (path.isDirectory) DIR else FILE) + path.path } } @JvmStatic fun createStructureFilter(values: List<String>): VcsLogStructureFilter { return VcsLogFilterObject.fromPaths(values.map { path -> extractPath(path) }) } fun extractPath(path: String): FilePath { if (path.startsWith(DIR)) { return VcsUtil.getFilePath(path.substring(DIR.length), true) } else if (path.startsWith(FILE)) { return VcsUtil.getFilePath(path.substring(FILE.length), false) } return VcsUtil.getFilePath(path) } } } class DateFilterModel(uiProperties: MainVcsLogUiProperties, filters: VcsLogFilterCollection?) : SingleFilterModel<VcsLogDateFilter>(VcsLogFilterCollection.DATE_FILTER, uiProperties, filters) { override fun createFilter(values: List<String>): VcsLogDateFilter? { if (values.size != 2) { LOG.warn("Can not create date filter from $values before and after dates are required.") return null } val after = values[0] val before = values[1] try { return VcsLogFilterObject.fromDates(if (after.isEmpty()) 0 else after.toLong(), if (before.isEmpty()) 0 else before.toLong()) } catch (e: NumberFormatException) { LOG.warn("Can not create date filter from $values") } return null } override fun getFilterValues(filter: VcsLogDateFilter): List<String> = getDateValues(filter) companion object { fun getDateValues(filter: VcsLogDateFilter): List<String> { val after = filter.after val before = filter.before return listOf(after?.time?.toString() ?: "", before?.time?.toString() ?: "") } } } private inner class UserFilterModel(uiProperties: MainVcsLogUiProperties, filters: VcsLogFilterCollection?) : SingleFilterModel<VcsLogUserFilter>(VcsLogFilterCollection.USER_FILTER, uiProperties, filters) { override fun createFilter(values: List<String>): VcsLogUserFilter = VcsLogFilterObject.fromUserNames(values, logData) override fun getFilterValues(filter: VcsLogUserFilter): List<String> = ArrayList(filter.valuesAsText) } private inner class TextFilterField(private val textFilterModel: TextFilterModel, parentDisposable: Disposable) : SearchTextField(VCS_LOG_TEXT_FILTER_HISTORY), DataProvider { init { text = textFilterModel.text textEditor.emptyText.setText(VcsLogBundle.message("vcs.log.filter.text.hash.empty.text")) FragmentedSettingsUtil.setupPlaceholderVisibility(textEditor); textEditor.addActionListener { e: ActionEvent? -> applyFilter(true) } addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { if (isFilterOnTheFlyEnabled) applyFilter(false) } }) textFilterModel.addSetFilterListener { val modelText = textFilterModel.text if (!isSameFilterAs(modelText)) text = modelText } textEditor.toolTipText = createTooltipText() Disposer.register(parentDisposable) { hidePopup() } } private fun applyFilter(addToHistory: Boolean) { textFilterModel.setFilterText(text) if (addToHistory) addCurrentTextToHistory() } override fun onFieldCleared() { textFilterModel.setFilter(null) } override fun onFocusLost() { if (!isSameFilterAs(textFilterModel.text)) applyFilter(isFilterOnTheFlyEnabled) } private fun isSameFilterAs(otherText: String): Boolean { val thisText = text if (thisText.isNullOrBlank()) return otherText.isBlank() return thisText == otherText } override fun getData(dataId: String): Any? { if (VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId)) { return uiProperties } return null } } companion object { private const val VCS_LOG_TEXT_FILTER_HISTORY = "Vcs.Log.Text.Filter.History" private val LOG = Logger.getInstance(VcsLogClassicFilterUi::class.java) private fun createTooltipText(): @NlsContexts.Tooltip String { val text = VcsLogBundle.message("vcs.log.filter.text.hash.tooltip") val shortcut = HelpTooltip.getShortcutAsHtml(KeymapUtil.getFirstKeyboardShortcutText(VcsLogActionIds.VCS_LOG_FOCUS_TEXT_FILTER)) return XmlStringUtil.wrapInHtml(text + shortcut) } private val isFilterOnTheFlyEnabled: Boolean get() = Registry.`is`("vcs.log.filter.text.on.the.fly") private fun createTextActionsToolbar(editor: JComponent?): ActionToolbar { val actionManager = ActionManager.getInstance() val textActionGroup = actionManager.getAction(VcsLogActionIds.TEXT_FILTER_SETTINGS_ACTION_GROUP) as ActionGroup val toolbar: ActionToolbarImpl = object : ActionToolbarImpl(ActionPlaces.VCS_LOG_TOOLBAR_PLACE, textActionGroup, true) { override fun createToolbarButton(action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Supplier<out Dimension?>): ActionButton { val button = MyActionButton(action, presentation) button.isFocusable = true applyToolbarLook(look, presentation, button) return button } } toolbar.setCustomButtonLook(FieldInplaceActionButtonLook()) toolbar.setReservePlaceAutoPopupIcon(false) toolbar.targetComponent = editor toolbar.updateActionsImmediately() return toolbar } } }
250
null
5074
16,130
e7a787ae2af47a6694da9e0e3b1d8fcd0f397775
29,132
intellij-community
Apache License 2.0
jsonrpc-app/src/test/kotlin/org/apache/tuweni/jsonrpc/app/JSONRPCConfigTest.kt
Consensys
693,991,624
true
{"SVG": 2, "Java Properties": 2, "Markdown": 64, "Gradle": 64, "Shell": 3, "EditorConfig": 1, "YAML": 13760, "Git Attributes": 1, "Batchfile": 1, "Text": 33, "Ignore List": 2, "Git Config": 1, "Kotlin": 393, "TOML": 8, "Java": 443, "XML": 18, "JSON": 17343, "JavaScript": 4, "CSS": 1, "HTML": 8, "SQL": 5, "INI": 3, "ANTLR": 2, "Public Key": 1, "Dockerfile": 2}
// Copyright The Tuweni Authors // SPDX-License-Identifier: Apache-2.0 package org.apache.tuweni.jsonrpc.app import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class JSONRPCConfigTest { @Test fun testDefaultConfig() { val configAsString = JSONRPCConfig().config.toToml() assertEquals( """## Allowed JSON-RPC methods #allowedMethods = ["eth_", "net_version"] ## Allowed IP ranges #allowedRanges = ["0.0.0.0/0"] ## Whether the JSON-RPC server should authenticate incoming requests with HTTP Basic Authentication #basicAuth = false ## HTTP Basic Auth password #basicAuthPassword = "" ## HTTP Basic Auth realm #basicAuthRealm = "Apache Tuweni JSON-RPC proxy" ## HTTP Basic Auth username #basicAuthUsername = "" ## Enable caching #cacheEnabled = true ## Lifespan time for entries on cache in milliseconds #cacheLifespan = 5000 ## Max idle time for entries on cache in milliseconds #cacheMaxIdle = 1000 ## Location of cache storage #cacheStoragePath = "" ## Cached JSON-RPC methods #cachedMethods = ["eth_blockNumber", "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getTransactionReceipt", "eth_getTransactionByHash", "eth_getLogs"] ## File recording client connection fingerprints #clientFingerprintsFile = "fingerprints.txt" ## Enable basic authentication for the endpoint #endpointBasicAuthEnabled = false ## Basic authentication password for the endpoint #endpointBasicAuthPassword = "" ## Basic authentication username for the endpoint #endpointBasicAuthUsername = "" ## JSON-RPC endpoint #endpointUrl = "http://localhost:8545" ## Maximum concurrent requests #maxConcurrentRequests = 30 ## Metrics GRPC push endpoint #metricsGrpcEndpoint = "http://localhost:4317" ## Enable pushing metrics to gRPC service #metricsGrpcPushEnabled = false ## Metrics GRPC push timeout #metricsGrpcTimeout = 2000 ## Metric service network interface #metricsNetworkInterface = "localhost" ## Metric service port #metricsPort = 9090 ## Enable exposing metrics on the Prometheus endpoint #metricsPrometheusEnabled = false ## JSON-RPC server network interface #networkInterface = "127.0.0.1" ## Number of threads for each thread pool #numberOfThreads = 10 ## JSON-RPC server port #port = 18545 ## Rejected IP ranges #rejectedRanges = [] ## Server security mode: record, allowlist, ca, tofu #serverSecurity = "record" ## Whether the JSON-RPC server should serve data over SSL #ssl = false """.split("\n").joinToString(System.lineSeparator()), configAsString, ) } }
1
Java
2
0
d780a654afc90f5fd3c16540d592259487e0a190
2,513
tuweni
Apache License 2.0
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/components/Olingo4UriDsl.kt
orpiske
598,577,710
true
{"Text": 251, "Git Config": 1, "XML": 1790, "Batchfile": 4, "Shell": 21, "YAML": 70, "Maven POM": 593, "JSON": 2573, "Dockerfile": 5, "Markdown": 26, "Ignore List": 19, "Groovy": 164, "Git Attributes": 1, "Java": 21665, "Java Properties": 1066, "AsciiDoc": 1315, "INI": 22, "HTML": 151, "CSS": 2, "JavaScript": 32, "XSLT": 61, "OASv3-yaml": 8, "OASv3-json": 20, "OASv2-json": 6, "OASv2-yaml": 1, "Protocol Buffer": 5, "ASN.1": 1, "Thrift": 2, "SQL": 38, "GraphQL": 4, "Fluent": 9, "Public Key": 16, "Jsonnet": 2, "TOML": 2, "Rust": 1, "Apex": 3, "Erlang": 1, "Tcl": 5, "Mustache": 7, "XQuery": 5, "Ruby": 1, "RobotFramework": 7, "JAR Manifest": 47, "SVG": 2, "Kotlin": 497}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.camel.kotlin.components import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.Unit import org.apache.camel.kotlin.CamelDslMarker import org.apache.camel.kotlin.UriDsl /** * Communicate with OData 2.0 services using Apache Olingo. */ public fun UriDsl.olingo2(i: Olingo2UriDsl.() -> Unit) { Olingo2UriDsl(this).apply(i) } @CamelDslMarker public class Olingo2UriDsl( it: UriDsl, ) { private val it: UriDsl init { this.it = it this.it.component("olingo2") } private var apiName: String = "" private var methodName: String = "" /** * What kind of operation to perform */ public fun apiName(apiName: String) { this.apiName = apiName it.url("$apiName/$methodName") } /** * What sub operation to use for the selected operation */ public fun methodName(methodName: String) { this.methodName = methodName it.url("$apiName/$methodName") } /** * HTTP connection creation timeout in milliseconds, defaults to 30,000 (30 seconds) */ public fun connectTimeout(connectTimeout: String) { it.property("connectTimeout", connectTimeout) } /** * HTTP connection creation timeout in milliseconds, defaults to 30,000 (30 seconds) */ public fun connectTimeout(connectTimeout: Int) { it.property("connectTimeout", connectTimeout.toString()) } /** * Content-Type header value can be used to specify JSON or XML message format, defaults to * application/json;charset=utf-8 */ public fun contentType(contentType: String) { it.property("contentType", contentType) } /** * Custom entity provider read properties applied to all read operations. */ public fun entityProviderReadProperties(entityProviderReadProperties: String) { it.property("entityProviderReadProperties", entityProviderReadProperties) } /** * Custom entity provider write properties applied to create, update, patch, batch and merge * operations. For instance users can skip the Json object wrapper or enable content only mode when * sending request data. A service URI set in the properties will always be overwritten by the * serviceUri configuration parameter. Please consider to using the serviceUri configuration * parameter instead of setting the respective write property here. */ public fun entityProviderWriteProperties(entityProviderWriteProperties: String) { it.property("entityProviderWriteProperties", entityProviderWriteProperties) } /** * Set this to true to filter out results that have already been communicated by this component. */ public fun filterAlreadySeen(filterAlreadySeen: String) { it.property("filterAlreadySeen", filterAlreadySeen) } /** * Set this to true to filter out results that have already been communicated by this component. */ public fun filterAlreadySeen(filterAlreadySeen: Boolean) { it.property("filterAlreadySeen", filterAlreadySeen.toString()) } /** * Custom HTTP headers to inject into every request, this could include OAuth tokens, etc. */ public fun httpHeaders(httpHeaders: String) { it.property("httpHeaders", httpHeaders) } /** * Sets the name of a parameter to be passed in the exchange In Body */ public fun inBody(inBody: String) { it.property("inBody", inBody) } /** * HTTP proxy server configuration */ public fun proxy(proxy: String) { it.property("proxy", proxy) } /** * Target OData service base URI, e.g. http://services.odata.org/OData/OData.svc */ public fun serviceUri(serviceUri: String) { it.property("serviceUri", serviceUri) } /** * HTTP request timeout in milliseconds, defaults to 30,000 (30 seconds) */ public fun socketTimeout(socketTimeout: String) { it.property("socketTimeout", socketTimeout) } /** * HTTP request timeout in milliseconds, defaults to 30,000 (30 seconds) */ public fun socketTimeout(socketTimeout: Int) { it.property("socketTimeout", socketTimeout.toString()) } /** * If the polling consumer did not poll any files, you can enable this option to send an empty * message (no body) instead. */ public fun sendEmptyMessageWhenIdle(sendEmptyMessageWhenIdle: String) { it.property("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle) } /** * If the polling consumer did not poll any files, you can enable this option to send an empty * message (no body) instead. */ public fun sendEmptyMessageWhenIdle(sendEmptyMessageWhenIdle: Boolean) { it.property("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle.toString()) } /** * For endpoints that return an array or collection, a consumer endpoint will map every element to * distinct messages, unless splitResult is set to false. */ public fun splitResult(splitResult: String) { it.property("splitResult", splitResult) } /** * For endpoints that return an array or collection, a consumer endpoint will map every element to * distinct messages, unless splitResult is set to false. */ public fun splitResult(splitResult: Boolean) { it.property("splitResult", splitResult.toString()) } /** * Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions * (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the * likes, will now be processed as a message and handled by the routing Error Handler. Important: * This is only possible if the 3rd party component allows Camel to be alerted if an exception was * thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not * possible. In other situations we may improve the Camel component to hook into the 3rd party * component and make this possible for future releases. By default the consumer will use the * org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or * ERROR level and ignored. */ public fun bridgeErrorHandler(bridgeErrorHandler: String) { it.property("bridgeErrorHandler", bridgeErrorHandler) } /** * Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions * (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the * likes, will now be processed as a message and handled by the routing Error Handler. Important: * This is only possible if the 3rd party component allows Camel to be alerted if an exception was * thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not * possible. In other situations we may improve the Camel component to hook into the 3rd party * component and make this possible for future releases. By default the consumer will use the * org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or * ERROR level and ignored. */ public fun bridgeErrorHandler(bridgeErrorHandler: Boolean) { it.property("bridgeErrorHandler", bridgeErrorHandler.toString()) } /** * To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is * enabled then this option is not in use. By default the consumer will deal with exceptions, that * will be logged at WARN or ERROR level and ignored. */ public fun exceptionHandler(exceptionHandler: String) { it.property("exceptionHandler", exceptionHandler) } /** * Sets the exchange pattern when the consumer creates an exchange. */ public fun exchangePattern(exchangePattern: String) { it.property("exchangePattern", exchangePattern) } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom * implementation to control error handling usually occurred during the poll operation before an * Exchange have been created and being routed in Camel. */ public fun pollStrategy(pollStrategy: String) { it.property("pollStrategy", pollStrategy) } /** * Whether the producer should be started lazy (on the first message). By starting lazy you can * use this to allow CamelContext and routes to startup in situations where a producer may otherwise * fail during starting and cause the route to fail being started. By deferring this startup to be * lazy then the startup failure can be handled during routing messages via Camel's routing error * handlers. Beware that when the first message is processed then creating and starting the producer * may take a little time and prolong the total processing time of the processing. */ public fun lazyStartProducer(lazyStartProducer: String) { it.property("lazyStartProducer", lazyStartProducer) } /** * Whether the producer should be started lazy (on the first message). By starting lazy you can * use this to allow CamelContext and routes to startup in situations where a producer may otherwise * fail during starting and cause the route to fail being started. By deferring this startup to be * lazy then the startup failure can be handled during routing messages via Camel's routing error * handlers. Beware that when the first message is processed then creating and starting the producer * may take a little time and prolong the total processing time of the processing. */ public fun lazyStartProducer(lazyStartProducer: Boolean) { it.property("lazyStartProducer", lazyStartProducer.toString()) } /** * Custom HTTP async client builder for more complex HTTP client configuration, overrides * connectionTimeout, socketTimeout, proxy and sslContext. Note that a socketTimeout MUST be * specified in the builder, otherwise OData requests could block indefinitely */ public fun httpAsyncClientBuilder(httpAsyncClientBuilder: String) { it.property("httpAsyncClientBuilder", httpAsyncClientBuilder) } /** * Custom HTTP client builder for more complex HTTP client configuration, overrides * connectionTimeout, socketTimeout, proxy and sslContext. Note that a socketTimeout MUST be * specified in the builder, otherwise OData requests could block indefinitely */ public fun httpClientBuilder(httpClientBuilder: String) { it.property("httpClientBuilder", httpClientBuilder) } /** * The number of subsequent error polls (failed due some error) that should happen before the * backoffMultipler should kick-in. */ public fun backoffErrorThreshold(backoffErrorThreshold: String) { it.property("backoffErrorThreshold", backoffErrorThreshold) } /** * The number of subsequent error polls (failed due some error) that should happen before the * backoffMultipler should kick-in. */ public fun backoffErrorThreshold(backoffErrorThreshold: Int) { it.property("backoffErrorThreshold", backoffErrorThreshold.toString()) } /** * The number of subsequent idle polls that should happen before the backoffMultipler should * kick-in. */ public fun backoffIdleThreshold(backoffIdleThreshold: String) { it.property("backoffIdleThreshold", backoffIdleThreshold) } /** * The number of subsequent idle polls that should happen before the backoffMultipler should * kick-in. */ public fun backoffIdleThreshold(backoffIdleThreshold: Int) { it.property("backoffIdleThreshold", backoffIdleThreshold.toString()) } /** * To let the scheduled polling consumer backoff if there has been a number of subsequent * idles/errors in a row. The multiplier is then the number of polls that will be skipped before the * next actual attempt is happening again. When this option is in use then backoffIdleThreshold * and/or backoffErrorThreshold must also be configured. */ public fun backoffMultiplier(backoffMultiplier: String) { it.property("backoffMultiplier", backoffMultiplier) } /** * To let the scheduled polling consumer backoff if there has been a number of subsequent * idles/errors in a row. The multiplier is then the number of polls that will be skipped before the * next actual attempt is happening again. When this option is in use then backoffIdleThreshold * and/or backoffErrorThreshold must also be configured. */ public fun backoffMultiplier(backoffMultiplier: Int) { it.property("backoffMultiplier", backoffMultiplier.toString()) } /** * Milliseconds before the next poll. */ public fun delay(delay: String) { it.property("delay", delay) } /** * Milliseconds before the next poll. */ public fun delay(delay: Int) { it.property("delay", delay.toString()) } /** * If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the * previous run polled 1 or more messages. */ public fun greedy(greedy: String) { it.property("greedy", greedy) } /** * If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the * previous run polled 1 or more messages. */ public fun greedy(greedy: Boolean) { it.property("greedy", greedy.toString()) } /** * Milliseconds before the first poll starts. */ public fun initialDelay(initialDelay: String) { it.property("initialDelay", initialDelay) } /** * Milliseconds before the first poll starts. */ public fun initialDelay(initialDelay: Int) { it.property("initialDelay", initialDelay.toString()) } /** * Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only * fire once. If you set it to 5, it will only fire five times. A value of zero or negative means * fire forever. */ public fun repeatCount(repeatCount: String) { it.property("repeatCount", repeatCount) } /** * Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only * fire once. If you set it to 5, it will only fire five times. A value of zero or negative means * fire forever. */ public fun repeatCount(repeatCount: Int) { it.property("repeatCount", repeatCount.toString()) } /** * The consumer logs a start/complete log line when it polls. This option allows you to configure * the logging level for that. */ public fun runLoggingLevel(runLoggingLevel: String) { it.property("runLoggingLevel", runLoggingLevel) } /** * Allows for configuring a custom/shared thread pool to use for the consumer. By default each * consumer has its own single threaded thread pool. */ public fun scheduledExecutorService(scheduledExecutorService: String) { it.property("scheduledExecutorService", scheduledExecutorService) } /** * To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or * quartz for built in scheduler */ public fun scheduler(scheduler: String) { it.property("scheduler", scheduler) } /** * To configure additional properties when using a custom scheduler or any of the Quartz, Spring * based scheduler. */ public fun schedulerProperties(schedulerProperties: String) { it.property("schedulerProperties", schedulerProperties) } /** * Whether the scheduler should be auto started. */ public fun startScheduler(startScheduler: String) { it.property("startScheduler", startScheduler) } /** * Whether the scheduler should be auto started. */ public fun startScheduler(startScheduler: Boolean) { it.property("startScheduler", startScheduler.toString()) } /** * Time unit for initialDelay and delay options. */ public fun timeUnit(timeUnit: String) { it.property("timeUnit", timeUnit) } /** * Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. */ public fun useFixedDelay(useFixedDelay: String) { it.property("useFixedDelay", useFixedDelay) } /** * Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. */ public fun useFixedDelay(useFixedDelay: Boolean) { it.property("useFixedDelay", useFixedDelay.toString()) } /** * To configure security using SSLContextParameters */ public fun sslContextParameters(sslContextParameters: String) { it.property("sslContextParameters", sslContextParameters) } }
0
Java
1
1
65511a265752d23f5bbf4bb32cb3438c1d535f98
17,141
camel
Apache License 2.0
app/src/main/java/com/letitplay/maugry/letitplay/data_management/api/responses/UpdatedChannelResponse.kt
LetItPlay
113,900,291
false
null
package com.letitplay.maugry.letitplay.data_management.api.responses import com.google.gson.annotations.SerializedName import com.letitplay.maugry.letitplay.data_management.db.entity.Language data class UpdatedChannelResponse( @SerializedName("id") var id: Int, @SerializedName("lang") var lang: Language, @SerializedName("name") var name: String, @SerializedName("image") var imageUrl: String, @SerializedName("subscription_count") var subscriptionCount: Int, @SerializedName("tags") var tags: String?, @SerializedName("youtube_url") var youtubeUrl: String? )
8
Kotlin
1
0
74380c7cf5fe6ce8f307cd82d7e90f2e9704eacd
675
AndroidClient
Apache License 2.0
attic/photlin/src/photlinc/gen.kt
adolfoeliazat
93,302,907
false
{"Java": 30937521, "PHP": 7642921, "Kotlin": 2980528, "JavaScript": 2555709, "TypeScript": 222563, "HTML": 46734, "Batchfile": 23511, "Lex": 15020, "OCaml": 6730, "C#": 4124, "Protocol Buffer": 2621, "AutoHotkey": 2556, "Shell": 843, "Vim Script": 591, "Python": 62}
package photlinc import org.jetbrains.kotlin.js.backend.ast.JsVisitor import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsDoubleLiteral import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsIntLiteral import org.jetbrains.kotlin.js.backend.ast.JsVars.JsVar import org.jetbrains.kotlin.js.util.TextOutput import gnu.trove.THashSet import org.jetbrains.kotlin.backend.jvm.codegen.psiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.js.backend.JsConstructExpressionVisitor import org.jetbrains.kotlin.js.backend.JsFirstExpressionVisitor import org.jetbrains.kotlin.js.backend.JsPrecedenceVisitor import org.jetbrains.kotlin.js.backend.JsRequiresSemiVisitor import org.jetbrains.kotlin.js.translate.utils.name import org.jetbrains.kotlin.js.util.TextOutputImpl import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.annotations.argumentValue import org.jetbrains.kotlin.resolve.constants.BooleanValue import org.jetbrains.kotlin.resolve.constants.StringValue import java.util.* import photlin.* import vgrechka.* open class JsToStringGenerationVisitor2(out:TextOutput): JsVisitor() { protected var needSemi = true private var lineBreakAfterBlock = true /** * "Global" blocks are either the global block of a fragment, or a block * nested directly within some other global block. This definition matters * because the statements designated by statementEnds and statementStarts are * those that appear directly within these global blocks. */ private val globalBlocks = THashSet<JsBlock>() val p:TextOutput init{ p = out } override fun visitSingleLineComment(x: JsSingleLineComment) { p.print("// ${x.text}\n") } override fun visitPHPPlainCodeExpression(x: PHPPlainCodeExpression) { p.print(x.spewCode()) } override fun visitArrayAccess(x:JsArrayAccess) { printPair(x, x.getArrayExpression()) leftSquare() accept(x.getIndexExpression()) rightSquare() } override fun visitArray(x: JsArrayLiteral) { printDebugTag(x) fun fuck(gen: JsToStringGenerationVisitor2) { gen.p.print("array(") gen.printExpressions(x.getExpressions()) gen.p.print(")") } fuck(this) } private fun printExpressions(expressions:List<JsExpression>) { var notFirst = false for ((expressionIndex, expression) in expressions.withIndex()) { notFirst = sepCommaOptSpace(notFirst) && !(expression is JsDocComment) val isEnclosed = parenPushIfCommaExpression(expression) // if (expression.debugTag == "1646") { // "break on me" // } if (expression is JsArrayLiteral || expression.valueParameterDescriptor?.type?.typeName == "kotlin.Array") { pizdavalue(byReference = expression !is JsArrayLiteral) {gen-> gen.accept(expression)} } else { accept(expression) } if (isEnclosed) { rightParen() } } } private fun pizdavalue(byReference: Boolean = false, fuck: (JsToStringGenerationVisitor2) -> Unit) { val tag = PhotlincDebugGlobal.nextDebugTag() if (tag == PhotlincDebugGlobal.breakOnPizdavalue) { "break on me" } val varName = "pizdavalue" + tag val out = TextOutputImpl() val generator = JsToStringGenerationVisitor2(out) fuck(generator) val eq = when { byReference -> "=&" else -> "=" } printLineAbove("\$$varName $eq ${out.out};") p.print("\$$varName") } override fun visitBinaryExpression(binaryOperation: JsBinaryOperation) { val operator = binaryOperation.getOperator() val arg1 = binaryOperation.getArg1() val isExpressionEnclosed = parenPush(binaryOperation, arg1, !operator.isLeftAssociative()) accept(arg1) if (operator.isKeyword()) { _parenPopOrSpace(binaryOperation, arg1, !operator.isLeftAssociative()) } else if (operator !== JsBinaryOperator.COMMA) { if (isExpressionEnclosed) { rightParen() } spaceOpt() } printDebugTag(binaryOperation) if (binaryOperation.elvis) { p.print("?:") } else { p.print(run { val type = arg1.kotlinTypeName if (type == "kotlin.String") { if (operator.symbol == "+") return@run "." if (operator.symbol == "+=") return@run ".=" } return@run operator.symbol }) } // if (operator.symbol == "=") { // if (binaryOperation.arg2.kotlinTypeName == "kotlin.Array") { // p.print("&") // } // } val arg2 = binaryOperation.getArg2() val isParenOpened:Boolean if (operator === JsBinaryOperator.COMMA) { isParenOpened = false spaceOpt() } else if (arg2 is JsBinaryOperation && (arg2 as JsBinaryOperation).getOperator() === JsBinaryOperator.AND) { spaceOpt() leftParen() isParenOpened = true } else { if (spaceCalc(operator, arg2)) { isParenOpened = _parenPushOrSpace(binaryOperation, arg2, operator.isLeftAssociative()) } else { spaceOpt() isParenOpened = parenPush(binaryOperation, arg2, operator.isLeftAssociative()) } } accept(arg2) if (isParenOpened) { rightParen() } } override fun visitBlock(x:JsBlock) { printJsBlock(x, true) } override fun visitPHPClass(x: PHPClass) { printAnnotations(x.classDescriptor, x) val fuckingName = escapeIdent(x.className.ident) printDebugTag(x) p.print("class $fuckingName ") x.classDescriptor.phpSuperPrototypeNameRef?.let { val superClassName = (it.qualifier as JsNameRef).ident p.print("extends ${escapeIdent(superClassName)} ") } blockOpen() x.statements.forEach {accept(it); newlineOpt()} blockClose() p.newline() p.print("\$$fuckingName = new stdClassWithPhotlinProps(); // Fuck...") p.newline() } private fun printAnnotations(x: Annotated, node: JsNode) { val annotations = x.annotations if (!annotations.isEmpty()) { p.print("/**") for (ann in annotations) { val annAnnotations = ann.type.constructor.declarationDescriptor?.annotations if (annAnnotations != null) { val emitAnnotationAsPHPCommentAnnotation = annAnnotations.find { it.type.typeName == "photlin.EmitAnnotationAsPHPComment" } if (emitAnnotationAsPHPCommentAnnotation != null) { val annotationTypeName = ann.type.typeName ?: wtf("0afd9e3c-b8f5-4cef-8d82-45de409b8e6a") val nameArgValue = emitAnnotationAsPHPCommentAnnotation.argumentValue("name") as String val phpName = when (nameArgValue) { "" -> annotationTypeName.substringAfterLast(".") else -> nameArgValue } p.print(" @" + phpName) if (ann.allValueArguments.isNotEmpty()) { p.print("(") for ((key, value) in ann.allValueArguments) { p.print(key.name.asString()) p.print("=") when (value) { is StringValue -> { p.print(phpString(value.value, forceDoubleQuote = true)) } is BooleanValue -> { p.print(value.value.toString()) } else -> imf("7a2b3251-0044-4b96-a9c4-5ca3cbabe207") } } p.print(")") } } } } p.print(" **/ ") } } override fun visitBoolean(x:JsLiteral.JsBooleanLiteral) { if (x.getValue()) { p.print(CHARS_TRUE) } else { p.print(CHARS_FALSE) } } override fun visitBreak(x:JsBreak) { p.print(CHARS_BREAK) continueOrBreakLabel(x) } override fun visitContinue(x:JsContinue) { p.print(CHARS_CONTINUE) continueOrBreakLabel(x) } private fun continueOrBreakLabel(x:JsContinue) { val label = x.getLabel() if (label != null && label.getIdent() != null) { space() p.print("1") // XXX PHP... // p.print(escapeIdent(label.getIdent())) } } override fun visitCase(x:JsCase) { p.print(CHARS_CASE) space() accept(x.getCaseExpression()) _colon() newlineOpt() printSwitchMemberStatements(x) } private fun printSwitchMemberStatements(x:JsSwitchMember) { p.indentIn() for (stmt in x.getStatements()) { needSemi = true accept(stmt) if (needSemi) { semi() } newlineOpt() } p.indentOut() needSemi = false } override fun visitCatch(x: JsCatch) { spaceOpt() p.print(CHARS_CATCH) spaceOpt() leftParen() // val catchParam = ShitToShit.attrs(x).catchParam // if (catchParam != null) { // p.print(catchParam.typeReference!!.text + " $") // } accept(x.typeExpression) p.print(" $") nameDef(x.parameter.name) // Optional catch condition. // val catchCond = x.condition if (catchCond != null) { space() _if() space() accept(catchCond) } rightParen() spaceOpt() accept(x.body) } override fun visitConditional(x:JsConditional) { // Associativity: for the then and else branches, it is safe to insert // another // ternary expression, but if the test expression is a ternary, it should // get parentheses around it. printPair(x, x.getTestExpression(), true) spaceOpt() p.print('?') spaceOpt() printPair(x, x.getThenExpression()) spaceOpt() _colon() spaceOpt() printPair(x, x.getElseExpression()) } private fun printPair(parent:JsExpression, expression:JsExpression, wrongAssoc:Boolean = false) { val isNeedParen = parenCalc(parent, expression, wrongAssoc) if (isNeedParen) { leftParen() } accept(expression) if (isNeedParen) { rightParen() } } override fun visitDebugger(x:JsDebugger) { p.print(CHARS_DEBUGGER) } override fun visitDefault(x:JsDefault) { p.print(CHARS_DEFAULT) _colon() printSwitchMemberStatements(x) } override fun visitWhile(x:JsWhile) { _while() spaceOpt() leftParen() accept(x.getCondition()) rightParen() nestedPush(x.getBody()) accept(x.getBody()) nestedPop(x.getBody()) } override fun visitDoWhile(x:JsDoWhile) { p.print(CHARS_DO) nestedPush(x.getBody()) accept(x.getBody()) nestedPop(x.getBody()) if (needSemi) { semi() newlineOpt() } else { spaceOpt() needSemi = true } _while() spaceOpt() leftParen() accept(x.getCondition()) rightParen() } override fun visitEmpty(x:JsEmpty) {} override fun visitExpressionStatement(x:JsExpressionStatement) { val surroundWithParentheses = JsFirstExpressionVisitor.exec(x) if (surroundWithParentheses) { leftParen() } val expr = x.expression if (expr is JsFunction) { expr.shouldPrintName = true } accept(expr) if (surroundWithParentheses) { rightParen() } } override fun visitFor(x: JsFor) { _for() spaceOpt() leftParen() // The init expressions or var decl. // if (x.getInitExpression() != null) { accept(x.getInitExpression()) } else if (x.getInitVars() != null) { accept(x.getInitVars()) } semi() // The loop test. // if (x.getCondition() != null) { spaceOpt() accept(x.getCondition()) } semi() // The incr expression. // if (x.getIncrementExpression() != null) { spaceOpt() accept(x.getIncrementExpression()) } rightParen() nestedPush(x.getBody()) accept(x.getBody()) nestedPop(x.getBody()) } override fun visitForIn(x:JsForIn) { wtf("visitForIn 7cd8a5a3-136d-4a4a-bfd4-78502e2dd11c") // _for() // spaceOpt() // leftParen() // if (x.getIterVarName() != null) // { // printVar() // space() // nameDef(x.getIterVarName()) // if (x.getIterExpression() != null) // { // spaceOpt() // assignment() // spaceOpt() // accept(x.getIterExpression()) // } // } // else // { // // Just a name ref. // // // accept(x.getIterExpression()) // } // space() // p.print(CHARS_IN) // space() // accept(x.getObjectExpression()) // rightParen() // nestedPush(x.getBody()) // accept(x.getBody()) // nestedPop(x.getBody()) } override fun visitFunction(x: JsFunction) { val shouldDumpBodyToContainer = x.declarationDescriptor?.annotations ?.any {it.type.typeName == "photlin.PHPDumpBodyToContainer"} ?: false if (!shouldDumpBodyToContainer) { printDebugTag(x) p.print(CHARS_FUNCTION) if (x.declarationDescriptor != null) { val functionDescriptor = x.declarationDescriptor as? FunctionDescriptor ?: wtf("19b83dc5-1876-4a36-a82a-7feb392655d8") if (functionDescriptor.returnType?.typeName == "kotlin.Array") { p.print("&") } } space() if (x.getName() != null && x.shouldPrintName) { nameOf(x) } leftParen() var notFirst = false for (element in x.getParameters()) { val param = element as JsParameter notFirst = sepCommaOptSpace(notFirst) accept(param) } rightParen() space() if (x.useNames.isNotEmpty()) { p.print("use (") for ((i, nameRef) in x.useNames.withIndex()) { if (i > 0) p.print(", ") if (isByRefShit(nameRef)) p.print("&") p.print("$" + escapeIdent(nameRef.ident)) } p.print(")") } lineBreakAfterBlock = false } accept(x.getBody()) needSemi = true } override fun visitIf(x:JsIf) { _if() spaceOpt() leftParen() accept(x.getIfExpression()) rightParen() var thenStmt = x.getThenStatement() var elseStatement = x.getElseStatement() // @fucking if-then-else printing thenStmt = JsBlock(thenStmt) elseStatement = JsBlock(elseStatement) if (elseStatement != null && thenStmt is JsIf && (thenStmt as JsIf).getElseStatement() == null) { thenStmt = JsBlock(thenStmt) } nestedPush(thenStmt) accept(thenStmt) nestedPop(thenStmt) if (elseStatement != null) { if (needSemi) { semi() newlineOpt() } else { spaceOpt() needSemi = true } p.print(CHARS_ELSE) val elseIf = elseStatement is JsIf if (!elseIf) { nestedPush(elseStatement) } else { space() } accept(elseStatement) if (!elseIf) { nestedPop(elseStatement) } } } // override fun visitPHPVarRef(varRef: PHPVarRef) { // printDebugTag(varRef) // p.print("$" + escapeDollar(varRef.getIdent())) // } override fun visitPHPGlobalVarRef(varRef: PHPGlobalVarRef) { printDebugTag(varRef) p.print("\$GLOBALS['" + escapeIdent(varRef.getIdent()) + "']") } // override fun visitPHPFieldRef(x: PHPFieldRef) { // accept(x.receiver) // p.print("->${x.fieldName}") // } override fun visitPHPMethodCall(call: PHPMethodCall) { accept(call.receiver) printDebugTag(call, spaceBefore = true) p.print("->${call.methodName}") leftParen() printExpressions(call.arguments) rightParen() } override fun visitPHPStaticMethodCall(call: PHPStaticMethodCall) { p.print("${call.className}::${call.methodName}") leftParen() printExpressions(call.arguments) rightParen() } // override fun visitPHPInvocation(invocation: PHPInvocation) { //// val c = invocation.callee // accept(invocation.callee) // // leftParen() // printExpressions(invocation.arguments) // rightParen() // } override fun visitInvocation(invocation: JsInvocation) { printDebugTag(invocation) val callee = invocation.qualifier if (callee is JsNameRef) { if (callee.qualifier?.kotlinTypeName == "kotlin.String") { "break on me" val builtInFunction = when (callee.ident) { "charCodeAt" -> "Kotlin::charCodeAt" "substring" -> "Kotlin::substring" "split" -> "pizdasplit" else -> wtf("d140179a-26b4-4726-bd6d-be69c62f42ed callee.ident = ${callee.ident}") // else -> "pizdunishka" } p.print("$builtInFunction(") accept(callee.qualifier) p.print(", ") printExpressions(invocation.arguments) p.print(")") return } accept(callee) // printPair(invocation, callee) } else { pizdavalue {gen-> gen.accept(callee)} } leftParen() printExpressions(invocation.arguments) rightParen() } override fun visitLabel(x:JsLabel) { nameOf(x) _colon() spaceOpt() accept(x.getStatement()) } override fun visitNameRef(nameRef: JsNameRef) { printDebugTag(nameRef) if (nameRef.suppressWarnings) p.print("@") exhaustive=when (nameRef.kind) { PHPNameRefKind.STRING_LITERAL -> { if (nameRef.qualifier != null) { wtf("STRING_LITERAL with qualifier 210ac0a8-eaf1-44fe-933f-4e78a7cf07a6") } p.print("'" + escapeIdent(nameRef.ident) + "'") return } PHPNameRefKind.GLOBAL_VAR -> { if (nameRef.qualifier != null) { wtf("GLOBALVAR with qualifier 1325766c-29a4-44f9-b773-428a4f097e84") } p.print("\$GLOBALS['" + escapeIdent(nameRef.getIdent()) + "']") } PHPNameRefKind.VAR -> { if (nameRef.qualifier != null) { wtf("VAR with qualifier 562283b3-071e-4fac-bcae-6be7f2fbc1ba") } p.print("$" + escapeIdent(nameRef.ident)) return } PHPNameRefKind.FIELD -> { val qualifier = nameRef.qualifier if (qualifier != null) { if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") { val builtInFunction = when (nameRef.ident) { "length" -> "strlen" else -> wtf("39e634a3-a9c7-4cef-bc57-01bd2e4ae195 nameRef.ident = ${nameRef.ident}") } p.print("$builtInFunction(") accept(nameRef.qualifier) p.print(")") return } } accept(nameRef.qualifier) p.print("->${escapeIdent(nameRef.ident)}") return } PHPNameRefKind.STATIC -> { accept(nameRef.qualifier) p.print("::${escapeIdent(nameRef.ident)}") return } PHPNameRefKind.LAMBDA, PHPNameRefKind.LAMBDA_CREATOR -> { val varName = "pizda_" + PhotlincDebugGlobal.nextDebugTag() // if (varName == "pizda_3485") { // "break on me" // } val crappyPHPLambda = StringBuilder()-{s-> s.append("function(") val callableDescriptor = nameRef.callableDescriptor ?: wtf("ddb4e1a5-457a-4d51-b5d5-b999247e0b07") val paramDescriptors = when (nameRef.kind) { PHPNameRefKind.LAMBDA_CREATOR -> nameRef.additionalArgDescriptors ?: listOf() else -> callableDescriptor.valueParameters + (nameRef.additionalArgDescriptors ?: listOf()) } for ((i, valueParameter) in paramDescriptors.withIndex()) { if (i > 0) s.append(", ") if (valueParameter is ValueDescriptor) { if (valueParameter.type.typeName == "kotlin.Array") s.append("&") } s.append("\$p$i") } s.append(") {") s.append("return ${escapeIdent(nameRef.ident)}(") for (i in 0..paramDescriptors.lastIndex) { if (i > 0) s.append(", ") s.append("\$p$i") } s.append(");") s.append("}") } printLineAbove("\$$varName = $crappyPHPLambda;") p.print("\$$varName") return } PHPNameRefKind.DUNNO -> { val qualifier = nameRef.qualifier if (qualifier != null) { if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") { val builtInFunction = when (nameRef.ident) { "length" -> "strlen" else -> wtf("3c1a8c8c-4fe0-4d8b-bd4f-2bcab38a84f5 nameRef.ident = ${nameRef.ident}") } p.print("$builtInFunction(") accept(nameRef.qualifier) p.print(")") return } var enclose:Boolean if (qualifier is JsLiteral.JsValueLiteral) { // "42.foo" is not allowed, but "(42).foo" is. enclose = qualifier is JsNumberLiteral } else { enclose = parenCalc(nameRef, qualifier, false) } if (qualifier !is JsNameRef) enclose = false if (enclose) { leftParen() } if (qualifier !is JsNameRef) { // "break on me" pizdavalue {gen-> gen.accept(qualifier)} } else { accept(qualifier) } if (enclose) { rightParen() } p.print("->") } p.maybeIndent() beforeNodePrinted(nameRef) p.print(escapeIdent(nameRef.ident)) } } } private fun printLineAbove(s: String) { try { val out = (p as TextOutputImpl).out var index = out.length - 1 while (out[index] != '\n' && index > 0) { --index } if (out[index] == '\r' && index > 0) --index out.insert(index, "\n$s") } catch(e: StringIndexOutOfBoundsException) { "break on me" throw e } } private fun printDebugTag(shit: AbstractNode, spaceBefore: Boolean = false) { val debugTag = shit.debugTag if (debugTag != null) { if (debugTag == PhotlincDebugGlobal.breakOnDebugTag) { "break on me" } // val mappedFrom = shit.mappedFromDebugTag?.let {"<$it>"} ?: "" val mappedFrom = "" p.printTagged(spaceBefore.ifOrEmpty{" "} + debugTag + mappedFrom + "@") } } fun escapeIdent(s: String): String { // PHP reserved words and alike if (s == "die") return "die__photlin_umri_skotina" if (s == "const") return "const__photlin_konstantinovich" if (s == "split") return "split__photlin_v_zhopu_zalit" return s.replace("$", "__dollar__") } protected fun beforeNodePrinted(node:JsNode) {} override fun visitNew(x: JsNew) { printDebugTag(x) p.print(CHARS_NEW) space() val constructorExpression = x.getConstructorExpression() val needsParens = JsConstructExpressionVisitor.exec(constructorExpression) if (needsParens) { leftParen() } accept(constructorExpression) if (needsParens) { rightParen() } leftParen() printExpressions(x.getArguments()) rightParen() } override fun visitNull(x:JsNullLiteral) { printDebugTag(x) p.print(CHARS_NULL) } override fun visitInt(x:JsIntLiteral) { p.print(x.value) } override fun visitDouble(x:JsDoubleLiteral) { p.print(x.value) } override fun visitObjectLiteral(objectLiteral: JsObjectLiteral) { printDebugTag(objectLiteral) if (objectLiteral.propertyInitializers.isEmpty()) { p.print("new stdClassWithPhotlinProps()") } else { // imf("Generate non-empty object literal 653f3b11-ea9c-4f14-9b41-7d17a44c2d0d") p.print("array(") if (objectLiteral.isMultiline) { p.indentIn() } var notFirst = false for (item in objectLiteral.propertyInitializers) { if (notFirst) { p.print(',') } if (objectLiteral.isMultiline) { newlineOpt() } else if (notFirst) { spaceOpt() } notFirst = true val labelExpr = item.labelExpr // labels can be either string, integral, or decimal literals p.print("'") if (labelExpr is JsNameRef) { p.print((labelExpr as JsNameRef).ident) } else if (labelExpr is JsStringLiteral) { p.print((labelExpr as JsStringLiteral).value) } else { accept(labelExpr) } p.print("'") p.print(" => ") // _colon() space() val valueExpr = item.valueExpr val wasEnclosed = parenPushIfCommaExpression(valueExpr) accept(valueExpr) if (wasEnclosed) { rightParen() } } if (objectLiteral.isMultiline()) { p.indentOut() newlineOpt() } p.print(')') } } fun isByRefShit(node: JsNode): Boolean { return node.kotlinTypeName == "kotlin.Array" } override fun visitParameter(x: JsParameter) { printDebugTag(x) if (isByRefShit(x)) { p.print("&") } p.print("$" + escapeIdent(x.name.ident)) } override fun visitPostfixOperation(x:JsPostfixOperation) { val op = x.getOperator() val arg = x.getArg() // unary operators always associate correctly (I think) printPair(x, arg) p.print(op.getSymbol()) } override fun visitPrefixOperation(x:JsPrefixOperation) { val op = x.getOperator() p.print(op.getSymbol()) val arg = x.getArg() if (spaceCalc(op, arg)) { space() } // unary operators always associate correctly (I think) printPair(x, arg) } override fun visitProgram(x:JsProgram) { p.print("<JsProgram>") } override fun visitProgramFragment(x:JsProgramFragment) { p.print("<JsProgramFragment>") } override fun visitRegExp(x:JsRegExp) { slash() p.print(x.getPattern()) slash() val flags = x.getFlags() if (flags != null) { p.print(flags) } } override fun visitReturn(x:JsReturn) { printDebugTag(x) p.print(CHARS_RETURN) val expr = x.getExpression() if (expr != null) { space() accept(expr) } } override fun visitString(x:JsStringLiteral) { p.print(phpString(x.value, forceDoubleQuote = true)) } override fun visit(x:JsSwitch) { p.print(CHARS_SWITCH) spaceOpt() leftParen() accept(x.getExpression()) rightParen() spaceOpt() blockOpen() acceptList(x.getCases()) blockClose() } override fun visitThis(x:JsLiteral.JsThisRef) { p.print(CHARS_THIS) } override fun visitThrow(x: JsThrow) { printDebugTag(x) p.print(CHARS_THROW) space() accept(x.expression) } override fun visitTry(x:JsTry) { p.print(CHARS_TRY) spaceOpt() accept(x.getTryBlock()) acceptList(x.getCatches()) val finallyBlock = x.getFinallyBlock() if (finallyBlock != null) { p.print(CHARS_FINALLY) spaceOpt() accept(finallyBlock) } } override fun visit(v: JsVar) { v.propertyDescriptor?.let {printAnnotations(it, v)} v.visibility?.let {p.print("$it ")} printDebugTag(v) p.print("$" + escapeIdent(v.name.ident)) val initExpr = v.initExpression if (initExpr != null) { spaceOpt() // if (v.debugTag == DebugGlobal.breakOnDebugTag) { // "break on me" // } assignment(byRef = isByRefShit(v) && initExpr is JsNameRef) spaceOpt() val isEnclosed = parenPushIfCommaExpression(initExpr) accept(initExpr) if (isEnclosed) { rightParen() } } } override fun visitVars(vars: JsVars) { space() var sep = false for (v in vars) { if (sep) { if (vars.isMultiline) { newlineOpt() } spaceOpt() } else { sep = true } accept(v) p.print(';') } } override fun visitDocComment(comment:JsDocComment) { val asSingleLine = comment.getTags().size === 1 if (!asSingleLine) { newlineOpt() } p.print("/**") if (asSingleLine) { space() } else { p.newline() } var notFirst = false for (entry in comment.getTags().entries) { if (notFirst) { p.newline() p.print(' ') p.print('*') } else { notFirst = true } p.print('@') p.print(entry.key) val value = entry.value if (value != null) { space() if (value is CharSequence) { p.print(value as CharSequence) } else { visitNameRef(value as JsNameRef) } } if (!asSingleLine) { p.newline() } } if (asSingleLine) { space() } else { newlineOpt() } p.print('*') p.print('/') if (asSingleLine) { spaceOpt() } } protected fun newlineOpt() { if (!p.isCompact()) { p.newline() } // @debug // val breakOnLine = 37 // if (p.line == breakOnLine - 1) { // "break on me" // } } protected fun printJsBlock(x:JsBlock, _finalNewline:Boolean) { var finalNewline = _finalNewline if (!lineBreakAfterBlock) { finalNewline = false lineBreakAfterBlock = true } val needBraces = !x.isGlobalBlock() if (needBraces) { blockOpen() } val iterator = x.getStatements().iterator() while (iterator.hasNext()) { val isGlobal = x.isGlobalBlock() || globalBlocks.contains(x) val statement = iterator.next() if (statement is JsEmpty) { continue } needSemi = true var stmtIsGlobalBlock = false if (isGlobal) { if (statement is JsBlock) { // A block inside a global block is still considered global stmtIsGlobalBlock = true globalBlocks.add(statement as JsBlock) } } val commentedOut = statement is AbstractNode && statement.commentedOut if (commentedOut) p.print("/*") accept(statement) if (commentedOut) p.print("*/") if (stmtIsGlobalBlock) { globalBlocks.remove(statement) } if (needSemi) { /* * Special treatment of function declarations: If they are the only item in a * statement (i.e. not part of an assignment operation), just give them * a newline instead of a semi. */ val functionStmt = statement is JsExpressionStatement && (statement as JsExpressionStatement).getExpression() is JsFunction /* * Special treatment of the last statement in a block: only a few * statements at the end of a block require semicolons. */ val lastStatement = !iterator.hasNext() && needBraces && !JsRequiresSemiVisitor.exec(statement) if (functionStmt) { if (lastStatement) { newlineOpt() } else { p.newline() } } else { if (lastStatement) { p.printOpt(';') } else { semi() } newlineOpt() } } } if (needBraces) { // _blockClose() modified p.indentOut() p.print('}') if (finalNewline) { newlineOpt() } } needSemi = false } private fun assignment(byRef: Boolean) { p.print('=') if (byRef) p.print('&') } private fun blockClose() { p.indentOut() p.print('}') newlineOpt() } private fun blockOpen() { p.print('{') p.indentIn() newlineOpt() } private fun _colon() { p.print(':') } private fun _for() { p.print(CHARS_FOR) } private fun _if() { p.print(CHARS_IF) } private fun leftParen() { p.print('(') } private fun leftSquare() { p.print('[') } private fun nameDef(name: JsName) { // printDebugTag(name) p.print(escapeIdent(name.ident)) } private fun nameOf(hasName: HasName) { nameDef(hasName.name) } private fun nestedPop(statement:JsStatement):Boolean { val pop = !(statement is JsBlock) if (pop) { p.indentOut() } return pop } private fun nestedPush(statement:JsStatement):Boolean { val push = !(statement is JsBlock) if (push) { newlineOpt() p.indentIn() } else { spaceOpt() } return push } private fun _parenPopOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean { val doPop = parenCalc(parent, child, wrongAssoc) if (doPop) { rightParen() } else { space() } return doPop } private fun parenPush(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean { val doPush = parenCalc(parent, child, wrongAssoc) if (doPush) { leftParen() } return doPush } private fun parenPushIfCommaExpression(x:JsExpression):Boolean { val doPush = x is JsBinaryOperation && (x as JsBinaryOperation).getOperator() === JsBinaryOperator.COMMA if (doPush) { leftParen() } return doPush } private fun _parenPushOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean { val doPush = parenCalc(parent, child, wrongAssoc) if (doPush) { leftParen() } else { space() } return doPush } private fun rightParen() { p.print(')') } private fun rightSquare() { p.print(']') } private fun semi() { p.print(';') } private fun sepCommaOptSpace(sep:Boolean):Boolean { if (sep) { p.print(',') spaceOpt() } return true } private fun slash() { p.print('/') } private fun space() { p.print(' ') } private fun spaceOpt() { p.printOpt(' ') } private fun printVar() { p.print(CHARS_VAR) } private fun _while() { p.print(CHARS_WHILE) } companion object { private val CHARS_BREAK = "break".toCharArray() private val CHARS_CASE = "case".toCharArray() private val CHARS_CATCH = "catch".toCharArray() private val CHARS_CONTINUE = "continue".toCharArray() private val CHARS_DEBUGGER = "debugger".toCharArray() private val CHARS_DEFAULT = "default".toCharArray() private val CHARS_DO = "do".toCharArray() private val CHARS_ELSE = "else".toCharArray() private val CHARS_FALSE = "false".toCharArray() private val CHARS_FINALLY = "finally".toCharArray() private val CHARS_FOR = "for".toCharArray() private val CHARS_FUNCTION = "function".toCharArray() private val CHARS_IF = "if".toCharArray() private val CHARS_IN = "in".toCharArray() private val CHARS_NEW = "new".toCharArray() private val CHARS_NULL = "NULL".toCharArray() private val CHARS_RETURN = "return".toCharArray() private val CHARS_SWITCH = "switch".toCharArray() private val CHARS_THIS = "this".toCharArray() private val CHARS_THROW = "throw".toCharArray() private val CHARS_TRUE = "true".toCharArray() private val CHARS_TRY = "try".toCharArray() private val CHARS_VAR = "var".toCharArray() private val CHARS_WHILE = "while".toCharArray() private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') fun javaScriptString(value:String):CharSequence { return phpString(value, false) } /** * Generate JavaScript code that evaluates to the supplied string. Adapted * from {@link org.mozilla.javascript.ScriptRuntime#escapeString(String)} * . The difference is that we quote with either &quot; or &apos; depending on * which one is used less inside the string. */ fun phpString(chars: CharSequence, forceDoubleQuote: Boolean = false):CharSequence { val n = chars.length var quoteCount = 0 var aposCount = 0 for (i in 0..n - 1) { when (chars.get(i)) { '"' -> ++quoteCount '\'' -> ++aposCount } } val result = StringBuilder(n + 16) val quoteChar = if ((quoteCount < aposCount || forceDoubleQuote)) '"' else '\'' result.append(quoteChar) for (i in 0..n - 1) { val c = chars.get(i) if (' ' <= c && c <= '~' && c != quoteChar && c != '\\' && c != '$') { // an ordinary print character (like C isprint()) result.append(c) continue } var escape = -1 when (c) { '\b' -> escape = 'b'.toInt() // '\f' -> escape = 'f' '\n' -> escape = 'n'.toInt() '\r' -> escape = 'r'.toInt() '\t' -> escape = 't'.toInt() '"' -> escape = '"'.toInt() '\'' -> escape = '\''.toInt() '\\' -> escape = '\\'.toInt() '$' -> escape = '$'.toInt() }// only reach here if == quoteChar // only reach here if == quoteChar if (escape >= 0) { // an \escaped sort of character result.append('\\') result.append(escape.toChar()) } else { val hexSize:Int if (c.toInt() < 256) { // 2-digit hex result.append("\\x") hexSize = 2 } else { // Unicode. result.append("\\u") hexSize = 4 } // append hexadecimal form of ch left-padded with 0 var shift = (hexSize - 1) * 4 while (shift >= 0) { val digit = 0xf and (c.toInt() shr shift) result.append(HEX_DIGITS[digit]) shift -= 4 } } } result.append(quoteChar) escapeClosingTags(result) return result } /** * Escapes any closing XML tags embedded in <code>str</code>, which could * potentially cause a parse failure in a browser, for example, embedding a * closing <code>&lt;script&gt;</code> tag. * * @param str an unescaped literal; May be null */ private fun escapeClosingTags(str:StringBuilder) { if (str == null) { return } var index = 0 while (true) { index = str.indexOf("</", index) if (index == -1) break str.insert(index + 1, '\\') } } private fun parenCalc(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean { val parentPrec = JsPrecedenceVisitor.exec(parent) val childPrec = JsPrecedenceVisitor.exec(child) return parentPrec > childPrec || parentPrec == childPrec && wrongAssoc } /** * Decide whether, if <code>op</code> is printed followed by <code>arg</code>, * there needs to be a space between the operator and expression. * * @return <code>true</code> if a space needs to be printed */ private fun spaceCalc(op:JsOperator, arg:JsExpression):Boolean { if (op.isKeyword()) { return true } if (arg is JsBinaryOperation) { val binary = arg as JsBinaryOperation /* * If the binary operation has a higher precedence than op, then it won't * be parenthesized, so check the first argument of the binary operation. */ return binary.getOperator().getPrecedence() > op.getPrecedence() && spaceCalc(op, binary.getArg1()) } if (arg is JsPrefixOperation) { val op2 = (arg as JsPrefixOperation).getOperator() return (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG) && (op2 === JsUnaryOperator.DEC || op2 === JsUnaryOperator.NEG) || (op === JsBinaryOperator.ADD && op2 === JsUnaryOperator.INC) } if (arg is JsNumberLiteral && (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG)) { if (arg is JsIntLiteral) { return (arg as JsIntLiteral).value < 0 } else { assert(arg is JsDoubleLiteral) return (arg as JsDoubleLiteral).value < 0 } } return false } } }
1
null
1
1
6d40f5900d94037139ed97cdc926db90749d5768
48,644
fucking-everything
Apache License 2.0
src/main/kotlin/me/branchpanic/mods/stockpile/api/upgrade/Upgrade.kt
branchpanic
143,343,951
false
null
package me.branchpanic.mods.stockpile.api.upgrade import net.minecraft.item.ItemStack import net.minecraft.text.Text import net.minecraft.util.Identifier interface Upgrade { /** * The Identifier tying this Upgrade to an [UpgradeType]. */ val id: Identifier /** * The description of this Upgrade, often used in tooltips. */ val description: Text /** * Determines which upgrades in a given list conflict with this Upgrade. */ fun getConflictingUpgrades(upgrades: List<Upgrade>): List<Upgrade> = emptyList() /** * Gets an ItemStack representing this upgrade, used when removing upgrades with the Screwdriver. */ fun toStack(): ItemStack /** * Determines whether or not an upgrade can safely be removed from an UpgradeContainer without losing data. */ fun canSafelyBeRemovedFrom(context: UpgradeContainer): Boolean = false }
15
null
7
12
f99b43b46eda4c9e6cb3e51c168b3a2dc4f56f9e
918
stockpile
MIT License
core/support/src/main/kotlin/au/com/dius/pact/core/support/json/JsonValue.kt
Hazz223
267,132,672
false
{"Gradle": 30, "YAML": 6, "Markdown": 29, "INI": 7, "Shell": 3, "Text": 5, "Ignore List": 1, "Batchfile": 3, "EditorConfig": 1, "Groovy": 243, "Java": 175, "JSON": 645, "XML": 2, "Kotlin": 162, "ANTLR": 2, "Clojure": 5, "Scala": 59, "Java Properties": 1, "Dockerfile": 1}
package au.com.dius.pact.core.support.json import au.com.dius.pact.core.support.Json import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.google.gson.JsonPrimitive import org.apache.commons.lang3.StringEscapeUtils import java.math.BigDecimal import java.math.BigInteger sealed class JsonValue { data class Integer(val value: BigInteger) : JsonValue() data class Decimal(val value: BigDecimal) : JsonValue() data class StringValue(val value: String) : JsonValue() object True : JsonValue() object False : JsonValue() object Null : JsonValue() data class Array(val values: MutableList<JsonValue> = mutableListOf()) : JsonValue() { fun find(function: (JsonValue) -> Boolean) = values.find(function) operator fun set(i: Int, value: JsonValue) { values[i] = value } val size: Int get() = values.size fun addAll(jsonValue: JsonValue) { when (jsonValue) { is Array -> values.addAll(jsonValue.values) else -> values.add(jsonValue) } } fun last() = values.last() } data class Object(val entries: MutableMap<String, JsonValue>) : JsonValue() { constructor(vararg values: Pair<String, JsonValue>) : this(values.associate { it }.toMutableMap()) operator fun get(name: String) = entries[name] ?: Null override fun has(field: String) = entries.containsKey(field) operator fun set(key: String, value: Any?) { entries[key] = Json.toJson(value) } fun isEmpty() = entries.isEmpty() fun isNotEmpty() = entries.isNotEmpty() val size: Int get() = entries.size fun add(key: String, value: JsonValue) { entries[key] = value } } fun asObject(): Object { if (this is Object) { return this } else { throw UnsupportedOperationException("Expected an Object, but found a $this") } } fun asArray(): Array { if (this is Array) { return this } else { throw UnsupportedOperationException("Expected an Array, but found a $this") } } fun asString(): String { return if (this is StringValue) { value } else { serialise() } } fun asBoolean() = when (this) { is True -> true is False -> false else -> throw UnsupportedOperationException("Expected a Boolean, but found a $this") } fun asNumber(): Number = when (this) { is Integer -> this.value is Decimal -> this.value else -> throw UnsupportedOperationException("Expected a Number, but found a $this") } operator fun get(field: Any): JsonValue = when { this is Object -> this.asObject()[field.toString()] this is Array && field is Int -> this.values[field] else -> throw UnsupportedOperationException("Indexed lookups only work on Arrays and Objects, not $this") } open fun has(field: String) = when (this) { is Object -> this.entries.containsKey(field) else -> false } fun serialise(): String { return when (this) { is Null -> "null" is Decimal -> this.value.toString() is Integer -> this.value.toString() is StringValue -> "\"${StringEscapeUtils.escapeJson(this.value)}\"" is True -> "true" is False -> "false" is Array -> "[${this.values.joinToString(",") { it.serialise() }}]" is Object -> "{${this.entries.entries.joinToString(",") { "\"${it.key}\":" + it.value.serialise() }}}" } } fun toGson(): JsonElement { return when (this) { is Null -> JsonNull.INSTANCE is Decimal -> JsonPrimitive(this.value) is Integer -> JsonPrimitive(this.value) is StringValue -> JsonPrimitive(this.value) is True -> JsonPrimitive(true) is False -> JsonPrimitive(false) is Array -> { val array = JsonArray() this.values.forEach { array.add(it.toGson()) } array } is Object -> { val obj = JsonObject() this.entries.forEach { obj.add(it.key, it.value.toGson()) } obj } } } fun add(value: JsonValue) { if (this is Array) { this.values.add(value) } else { throw UnsupportedOperationException("You can only add single values to Arrays, not $this") } } fun size() = when (this) { is Array -> this.values.size is Object -> this.entries.size else -> 1 } fun type(): String { return when (this) { is StringValue -> "String" else -> this::class.java.simpleName } } fun unwrap(): Any? { return when (this) { is Null -> null is Decimal -> this.value is Integer -> this.value is StringValue -> this.value is True -> true is False -> false is Array -> this.values is Object -> this.entries } } val name: String get() { return this.javaClass.simpleName } val isBoolean: Boolean get() = when (this) { is True, is False -> true else -> false } val isNumber: Boolean get() = when (this) { is Integer, is Decimal -> true else -> false } val isString: Boolean get() = when (this) { is StringValue -> true else -> false } val isNull: Boolean get() = when (this) { is Null -> true else -> false } } fun <R> JsonValue?.map(transform: (JsonValue) -> R): List<R> = when { this == null -> emptyList() this is JsonValue.Array -> this.values.map(transform) else -> emptyList() } operator fun JsonValue?.get(field: Any): JsonValue = when { this == null -> JsonValue.Null else -> this[field] } operator fun JsonValue.Object?.get(field: Any): JsonValue = when { this == null -> JsonValue.Null else -> this[field] } fun JsonValue?.orNull() = this ?: JsonValue.Null
1
null
1
1
868ee1e2b998d0c89acfe28adfcdc4f03029b4bb
5,769
pact-jvm
Apache License 2.0
common/lib-sample-common/src/main/java/ru/surfstudio/android/sample/common/ui/base/loadstate/presentations/MainLoadingLoadStatePresentation.kt
surfstudio
175,407,898
false
null
package ru.surfstudio.android.sample.common.ui.base.loadstate.presentations import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.View import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import me.zhanghai.android.materialprogressbar.MaterialProgressBar import ru.surfstudio.android.core.mvp.loadstate.SimpleLoadStatePresentation import ru.surfstudio.android.custom.view.placeholder.PlaceHolderViewContainer import ru.surfstudio.android.sample.common.R import ru.surfstudio.android.sample.common.ui.base.loadstate.MainLoadingState /** * MainLoadingState presentation with a progressbar */ class MainLoadingLoadStatePresentation(private val placeHolder: PlaceHolderViewContainer) : SimpleLoadStatePresentation<MainLoadingState>() { @ColorInt private val progressBarColor: Int = ContextCompat.getColor(placeHolder.context, R.color.colorAccent) private val view: View by lazy { with(LayoutInflater.from(placeHolder.context).inflate( R.layout.placeholder_view_loading_strategy, placeHolder, false)) { colorProgressBar(this) return@lazy this } } override fun showState(state: MainLoadingState) { placeHolder.changeViewTo(view) placeHolder.show() } private fun colorProgressBar(view: View) { val progressBar: MaterialProgressBar = view.findViewById(R.id.placeholder_loading_pb) progressBar.supportIndeterminateTintList = ColorStateList.valueOf(progressBarColor) } }
1
Kotlin
2
27
5f68262ac148bc090c600121295f81c7ce3486c0
1,597
EasyAdapter
Apache License 2.0
desk360/src/main/java/com/teknasyon/desk360/themev2/Desk360TicketRecyclerView.kt
Teknasyon-Teknoloji
188,395,069
false
null
package com.teknasyon.desk360.themev2 import android.content.Context import android.graphics.Color import android.util.AttributeSet import androidx.recyclerview.widget.RecyclerView import com.teknasyon.desk360.helper.Desk360SDK class Desk360TicketRecyclerView : RecyclerView { init { this.setBackgroundColor(Color.parseColor(Desk360SDK.config?.data?.ticket_detail_screen?.chat_background_color)) } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super( context, attrs, defStyle ) }
2
null
1
14
d5cc69331db57812f2d053c6b09a24bd0eb4b7ea
685
desk360-android-sdk
MIT License
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/OnOfflineTilesConfiguredCallback.kt
FladioArmandika
281,600,947
false
{"Java Properties": 2, "Markdown": 12, "Gradle": 45, "Shell": 6, "YAML": 3, "Batchfile": 2, "JSON": 24, "Ignore List": 28, "Makefile": 1, "INI": 40, "Proguard": 16, "XML": 540, "HTML": 8, "Kotlin": 506, "Text": 13, "Java": 517, "JavaScript": 2, "Python": 2}
package com.mapbox.services.android.navigation.v5.navigation /** * Listener that needs to be added to [MapboxOfflineRouter.configure] to know when * offline data is initialized an [MapboxOfflineRouter.findRoute] could be called. */ interface OnOfflineTilesConfiguredCallback { /** * Called whe the offline data is initialized */ fun onConfigured() }
1
null
1
1
e5459ca9f1d836496330576ee18e4fd63732b8e2
373
mapbox-navigation-android
Apache License 2.0
src/main/kotlin/org/linguamachina/klinguamachina/generation/Compiler.kt
Lingua-Machina
254,106,597
false
{"Java": 165058, "Kotlin": 118787, "ANTLR": 3004, "Makefile": 1404}
package org.linguamachina.klinguamachina.generation interface Compiler<T> { fun compile(): T }
6
null
1
1
267c1c73b39ec57f235cb4ce3374b6f283b31eb7
100
KLinguaMachina
MIT License
trakt-api/src/main/java/net/simonvt/cathode/api/body/TokenRequest.kt
SimonVT
9,478,484
false
null
/* * Copyright (C) 2014 <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 net.simonvt.cathode.api.body import net.simonvt.cathode.api.enumeration.GrantType data class TokenRequest( val code: String?, val refresh_token: String?, val client_id: String, val client_secret: String, val redirect_uri: String, val grant_type: GrantType )
11
null
9
99
29d916efcd1dbb8ddac1fc2600b2bfbe6ee84c27
874
cathode
Apache License 2.0
app/src/main/java/ru/tech/cookhelper/presentation/ui/utils/compose/ColorUtils.kt
T8RIN
483,296,940
false
null
package ru.tech.cookhelper.presentation.ui.utils.compose import androidx.annotation.FloatRange import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import ru.tech.cookhelper.presentation.ui.theme.isDarkMode import androidx.core.graphics.ColorUtils as AndroidColorUtils object ColorUtils { fun Color.blend( color: Color, @FloatRange(from = 0.0, to = 1.0) fraction: Float = 0.2f ): Color = AndroidColorUtils.blendARGB(this.toArgb(), color.toArgb(), fraction).toColor() fun Color.darken( @FloatRange(from = 0.0, to = 1.0) fraction: Float = 0.2f ): Color = blend(color = Color.Black, fraction = fraction) @Composable fun Color.createSecondaryColor( @FloatRange(from = 0.0, to = 1.0) fraction: Float = 0.2f ): Color = if (isDarkMode()) lighten(fraction) else darken(fraction) @Composable fun Color.createInverseSecondaryColor( @FloatRange(from = 0.0, to = 1.0) fraction: Float = 0.2f ): Color = if (!isDarkMode()) lighten(fraction) else darken(fraction) fun Color.lighten( @FloatRange(from = 0.0, to = 1.0) fraction: Float = 0.2f ): Color = blend(color = Color.White, fraction = fraction) fun Int.toColor(): Color = Color(color = this) @Composable fun Color.harmonizeWithPrimary( @FloatRange( from = 0.0, to = 1.0 ) fraction: Float = 0.2f ): Color = blend(MaterialTheme.colorScheme.primary, fraction) }
1
Kotlin
10
91
cee8f8d8cd6bfc53e88c461edc1c9aaf43ce18c7
1,583
CookHelper
Apache License 2.0
src/main/kotlin/creational/builder/productionline/seasoningstage/Spice.kt
samirtf
267,724,557
false
null
package creational.builder.productionline.seasoningstage interface Spice { fun getBlazingDegree() }
0
Kotlin
0
0
9063512d40c2300d1e2bab2760627ee9ea1e4a71
105
design-patterns-kotlin
Apache License 2.0
layoutk_loadrefresh/src/main/java/com/mozhimen/xmlk/layoutk/loadrefresh/commons/ILoadRefreshListener.kt
mozhimen
747,030,456
false
null
package com.mozhimen.xmlk.layoutk.loadrefresh.commons /** * @ClassName ILoadRefreshListener * @Description TODO * @Author mozhimen / Kolin Zhao * @Date 2022/11/6 19:46 * @Version 1.0 */ interface ILoadRefreshListener { fun onRefreshOrLoad(isSuccess: Boolean) }
0
null
4
4
7888e57b6f71298cc95ab8538043844d9cbf1551
271
AXmlKit
Apache License 2.0
sykepenger-mediators/src/main/kotlin/no/nav/helse/spleis/VedtaksperiodeProbe.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis import net.logstash.logback.argument.StructuredArguments.keyValue import no.nav.helse.hendelser.Hendelseskontekst import no.nav.helse.hendelser.Påminnelse import no.nav.helse.person.PersonObserver import org.slf4j.LoggerFactory object VedtaksperiodeProbe : PersonObserver { private val log = LoggerFactory.getLogger(VedtaksperiodeProbe::class.java) override fun personEndret(hendelseskontekst: Hendelseskontekst) {} override fun vedtaksperiodeEndret(hendelseskontekst: Hendelseskontekst, event: PersonObserver.VedtaksperiodeEndretEvent) { log.info( "vedtaksperiode endret {}, {}, {}", keyValue("vedtaksperiodeId", hendelseskontekst.vedtaksperiodeId()), keyValue("tilstand", event.gjeldendeTilstand.name), keyValue("forrigeTilstand", event.forrigeTilstand.name) ) } override fun utbetalingEndret(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtbetalingEndretEvent) { log.info( "utbetaling endret {}, {}, {}", keyValue("utbetalingId", "${event.utbetalingId}"), keyValue("status", event.gjeldendeStatus), keyValue("forrigeStatus", event.forrigeStatus) ) } override fun vedtaksperiodePåminnet(hendelseskontekst: Hendelseskontekst, påminnelse: Påminnelse) { log.debug( "mottok påminnelse for vedtaksperiode: ${hendelseskontekst.vedtaksperiodeId()}", keyValue("påminnelsenr", "${påminnelse.antallGangerPåminnet()}"), keyValue("påminnelsestidspunkt", påminnelse.påminnelsestidspunkt().toString()), keyValue("vedtaksperiodeId", hendelseskontekst.vedtaksperiodeId()), keyValue("tilstand", påminnelse.tilstand().name), keyValue("tilstandsendringstidspunkt", påminnelse.tilstandsendringstidspunkt().toString()), keyValue("nestePåminnelsestidspunkt", påminnelse.nestePåminnelsestidspunkt().toString()) ) } private fun Hendelseskontekst.vedtaksperiodeId(): String { val keyValues = mutableMapOf<String, String>() appendTo(keyValues::set) return keyValues["vedtaksperiodeId"]!! } }
0
Kotlin
3
4
22fe9640780c8c8c13165c2efb0dfc4d96ba9965
2,210
helse-spleis
MIT License
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/BookClosed.kt
alexzhirkevich
636,411,288
false
{"Kotlin": 4456601, "Ruby": 2310, "Swift": 2101, "Shell": 856, "HTML": 762}
package io.github.alexzhirkevich.cupertino.icons.outlined import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons public val CupertinoIcons.Outlined.BookClosed: ImageVector get() { if (_bookClosed != null) { return _bookClosed!! } _bookClosed = Builder(name = "BookClosed", defaultWidth = 19.7109.dp, defaultHeight = 25.1133.dp, viewportWidth = 19.7109f, viewportHeight = 25.1133f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.5977f, 25.1133f) lineTo(18.7734f, 25.1133f) curveTo(19.2891f, 25.1133f, 19.7109f, 24.7031f, 19.7109f, 24.1758f) curveTo(19.7109f, 23.7656f, 19.4297f, 23.4023f, 19.0547f, 23.2734f) curveTo(17.5781f, 22.6875f, 17.2734f, 20.7773f, 18.7266f, 19.3125f) curveTo(19.1719f, 18.8672f, 19.7109f, 18.293f, 19.7109f, 17.1211f) lineTo(19.7109f, 3.6797f) curveTo(19.7109f, 1.2422f, 18.5039f, 0.0f, 16.0781f, 0.0f) lineTo(3.6328f, 0.0f) curveTo(1.207f, 0.0f, 0.0f, 1.2305f, 0.0f, 3.6797f) lineTo(0.0f, 21.4922f) curveTo(0.0f, 23.9062f, 1.2188f, 25.1133f, 3.5977f, 25.1133f) close() moveTo(1.8867f, 18.3398f) lineTo(1.8867f, 3.7148f) curveTo(1.8867f, 2.543f, 2.5078f, 1.8867f, 3.7148f, 1.8867f) lineTo(15.9844f, 1.8867f) curveTo(17.2031f, 1.8867f, 17.8242f, 2.543f, 17.8242f, 3.7148f) lineTo(17.8242f, 16.8633f) curveTo(17.8242f, 17.4961f, 17.4609f, 17.8594f, 16.8047f, 17.8594f) lineTo(3.7969f, 17.8594f) curveTo(3.0352f, 17.8594f, 2.4023f, 18.0234f, 1.8867f, 18.3398f) close() moveTo(3.7031f, 23.2266f) curveTo(2.5195f, 23.2266f, 1.8867f, 22.5938f, 1.8867f, 21.4805f) curveTo(1.8867f, 20.4258f, 2.6367f, 19.7461f, 3.8086f, 19.7461f) lineTo(15.832f, 19.7461f) curveTo(15.9844f, 19.7461f, 16.125f, 19.7344f, 16.2422f, 19.7109f) curveTo(15.6914f, 20.9297f, 15.7852f, 22.2188f, 16.4062f, 23.2266f) close() moveTo(3.2695f, 18.8672f) lineTo(4.8047f, 18.8672f) lineTo(4.8047f, 1.4297f) lineTo(3.2695f, 1.4297f) close() } } .build() return _bookClosed!! } private var _bookClosed: ImageVector? = null
1
Kotlin
14
362
60fd9234eb9f2df97bc8523ea2ed344ad7f58655
3,255
compose-cupertino
Apache License 2.0
app/src/androidTest/java/com/task/TestDataRepository.kt
tokgocode
636,235,038
false
null
package com.task import com.task.data.DataRepositorySource import com.task.data.Resource import com.task.data.dto.checkin.CheckInInputDto import com.task.data.dto.checkin.CheckInRecordResponse import com.task.data.dto.checkin.CheckInResponse import kotlinx.coroutines.flow.Flow import javax.inject.Inject class TestDataRepository @Inject constructor() : DataRepositorySource { override suspend fun checkIn(input: CheckInInputDto): Flow<Resource<CheckInResponse>> { TODO("Not yet implemented") } override suspend fun getCheckIns(stuNo: String): Flow<Resource<CheckInRecordResponse>> { TODO("Not yet implemented") } }
0
Kotlin
0
0
a63bdf684d8a6d0fa26bee39a63d67bebb2e5c8e
656
android-icheckin
Apache License 2.0
mediapickerlib/src/main/java/com/coursion/freakycoder/mediapicker/helper/Util.kt
abhirocks1211
130,378,087
false
null
package com.coursion.freakycoder.mediapicker.helper import android.content.res.ColorStateList import android.os.Build import android.support.design.widget.FloatingActionButton import android.support.v4.view.ViewCompat /** * Created by WrathChaos on 5.03.2018. */ class Util{ fun setButtonTint(button: FloatingActionButton, tint: ColorStateList) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { button.backgroundTintList = tint } else { ViewCompat.setBackgroundTintList(button, tint) } } }
0
Kotlin
0
0
c086714756471cb3f9e99260671e54d5efd3f213
562
MediaPickerLib
MIT License
app/app/src/main/java/com/barnivore/barnivore/helpers/PreferenceHelper.kt
JesseScott
99,703,426
false
null
package com.barnivore.barnivore.helpers /** * * Created by jessescott on 2017-08-08. * */ import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import android.text.TextUtils import android.util.Log class PreferenceHelper(context: Context) { private val TAG = PreferenceHelper::class.java.simpleName private var mContext: Context = context private var preferences: SharedPreferences init { preferences = PreferenceManager.getDefaultSharedPreferences(mContext) } // region - Boolean fun setPrefBooleanValueByKey(key: String, value: Boolean) { if (value !is Boolean) { return } Log.d(TAG, "Setting $key to $value") val editor = preferences.edit() editor.putBoolean(key, value) editor.apply() } fun getPrefBooleanValueByKey(key: String): Boolean { val value = preferences.getBoolean(key, false) Log.d(TAG, "Getting preference $key with value $value") return value } // endregion // region - String fun setPrefStringValueByKey(key: String, value: String) { if (value !is String) { return } if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) { return } Log.d(TAG, "Setting $key to $value") val editor = preferences.edit() editor.putString(key, value) editor.apply() } fun getPrefStringValueByKey(key: String): String { val value = preferences.getString(key, "") Log.d(TAG, "Getting preference $key with value $value") return value } // endregion }
0
Kotlin
0
0
702d829b3796d3744736b2f84a5e0d8bf6db702d
1,700
Barnivore-Android
MIT License
android_example/src/main/kotlin/com/quickbird/android_example/theme/Color.kt
QuickBirdEng
517,579,154
false
{"Kotlin": 36800}
package com.quickbird.android_example.theme import androidx.compose.ui.graphics.Color val MainColor = Color(0xFC105BA3)
4
Kotlin
2
59
789307ec5ebd2f043ed7d1975bafd4d841fd8099
122
kotlin-snapshot-testing
MIT License
app/src/main/java/com/simform/demo/RecyclerAdapter.kt
SimformSolutionsPvtLtd
379,198,133
false
null
package com.simform.demo import android.content.Context import android.graphics.BitmapFactory import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.pulltorefresh.R import kotlinx.android.synthetic.main.list_item.view.image_view_profile import kotlinx.android.synthetic.main.list_item.view.text_view_data2 import kotlinx.android.synthetic.main.list_item.view.text_view_data class RecyclerAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerAdapter.MyRecyclerViewHolder>() { private var items: ArrayList<Triple<String,String,Int>> = ArrayList() private var dataSet: ArrayList<Triple<String,String,Int>> = ArrayList() init { dataSet.apply { add(Triple("Thor","Odinson", R.drawable.thor)) add(Triple("Steve","Rogers",R.drawable.cap)) add(Triple("Elena","Gilbert",R.drawable.elena)) add(Triple("Demon","Salvatore",R.drawable.demon)) add(Triple("Stephan","Salvatore",R.drawable.stehpan)) add(Triple("Tony","Stark",R.drawable.tony)) add(Triple("Barney","Stinson",R.drawable.barney)) add(Triple("Ted","Mosby",R.drawable.ted)) add(Triple("Lightning","Mcqueen",R.drawable.mc)) } randomizeData() } inner class MyRecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false) return MyRecyclerViewHolder(view) } override fun onBindViewHolder(holder: MyRecyclerViewHolder, position: Int) { holder.itemView.text_view_data.text = items[position].first holder.itemView.text_view_data2.text = items[position].second holder.itemView.image_view_profile.setImageBitmap(BitmapFactory.decodeResource(context.resources,items[position].third)) } override fun getItemCount(): Int = items.size fun randomizeData() { items = ArrayList() items.apply { val n = (0..dataSet.size).random() for (i in 0..n) { val item = dataSet.random() if (!items.contains(item)) add(item) } } notifyDataSetChanged() } }
1
Kotlin
13
76
bfd47107c2f7f6d2fcf45858f86aa90dfbfa1ab3
2,402
SSPullToRefresh
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/callResolution/overloadsWithGenericAndGenericLambda.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// ISSUE: KT-50646 class Inv<T> fun <T> foo(c: Inv<T>, f: () -> T) {} fun <T> foo(c: Inv<T>, v: T) {} fun <T> test(x: Inv<T>, v: T) { foo(x) { v } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
156
kotlin
Apache License 2.0
app/src/main/java/com/jumbox/tekatekisilang/ManagerLevel.kt
jumadi59
189,327,960
false
null
package com.jumbox.tekatekisilang import android.util.Log import com.jumbox.tekatekisilang.model.TtsLevel import com.jumbox.tekatekisilang.model.TtsResponseMsg import com.jumbox.tekatekisilang.model.TtsSoal import com.jumbox.tekatekisilang.soal.Soal import com.jumbox.tekatekisilang.soal.Soal1 import com.jumbox.tekatekisilang.soal.Soal2 import com.jumbox.tekatekisilang.soal.Soal3 /** *Created by Jumadi Janjaya *13, December, 2018 *Jumbox Studios, *Bengkulu, Indonesia. */ class ManagerLevel { companion object { var TAG = "ManagerLevel" const val URL_SOAL = "http://apps.cumacoding.com/teka-teki_silang" lateinit var managerLevel: ManagerLevel fun instance(): ManagerLevel { managerLevel = ManagerLevel() return managerLevel } } private var levels: ArrayList<TtsLevel> = ArrayList() private var tts: TSilang? = null private var gLevel: Int = 0 private var gKotak = -1 init { addArrayLevels(Soal.soal10x10, TSilang.KOTAK_10X10) addArrayLevels(Soal.soal12x12, 12) addArrayLevels(Soal1.soal10x10, TSilang.KOTAK_10X10) addArrayLevels(Soal2.soal10x10, TSilang.KOTAK_10X10) addArrayLevels(Soal3.soal10x10, TSilang.KOTAK_10X10) addLevels(DataGame.get().loadLevelUnduhan()) downloadSoalOnline() } private fun downloadSoalOnline() { val ls = DataGame.get().loadLevelUnduhan() val params = HashMap<String, String>() params["user_project"] = "jumadi-12345" params["start_index"] = "${(ls.size)}" val request = HttpHandler(HttpHandler.REQUEST_METHOD_GET, URL_SOAL, params, object : HttpHandler.ResponseListener { override fun onSuccessResponse(string: String?) { if (string == null) return Log.d(TAG, string) if (string.contains("[")) { val data: TtsResponseMsg = Utils.utils.JsonToObject(string, TtsResponseMsg::class.java) if (data.message == 1) { if (data.data !=null) { DataGame.d!!.saveLevelUnduhan(data.data!!) addLevels(data.data!!) } } } else { Log.d(TAG, "Type not JSON") } } override fun onErrorResponse(string: String?) { Log.d(TAG, "error : $string") } }) request.start() } fun addLevels(levels: ArrayList<TtsLevel>) { this.levels.addAll(levels) } fun addArrayLevels(obj: Array<Array<Array<Any>>>, jumKotak: Int) { for ((i: Int, level: Array<Array<Any>>) in obj.withIndex()) { val arrSoal = ArrayList<TtsSoal>() for (soal in level) { val jawaban = soal[0] as String val clue = soal[1] as String val row = soal[2] as Int val col = soal[3] as Int var orentation: Boolean orentation = try { soal[4] as Boolean } catch (e: Exception) { val o = soal[4] as String o.toLowerCase() == "mendatar".toLowerCase() } arrSoal.add(TtsSoal(jawaban, clue, row, col, orentation)) } levels.add(TtsLevel(i, arrSoal, jumKotak)) } } fun setLevel(mLevel: Int) { val level = levels[mLevel] val soals = level.soals gLevel = mLevel gKotak = level.kotak tts = TSilang(level.kotak, level.kotak) for (soal in soals) { tts!!.add(soal.tts, soal.clue, soal.row, soal.colm, soal.orietation) } } fun levelCount(): Int { return levels.size } fun kotak(): Int { return gKotak } fun level(): Int { return gLevel } fun Tts(): TSilang { return this.tts!! } }
0
Kotlin
1
1
7f86b3d201ddc725ecb15c83bbb69e70f2723cd3
4,033
android-game-teka-teki-silang
MIT License
app/src/main/kotlin/org/andstatus/app/service/TimelineDownloader.kt
andstatus
3,040,264
false
{"Kotlin": 3385973, "XSLT": 14655, "HTML": 14046, "CSS": 4427, "Shell": 707}
/* * Copyright (c) 2013 yvolk (<NAME>), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.service import io.vavr.control.Try import org.andstatus.app.data.DataPruner import org.andstatus.app.data.DataUpdater import org.andstatus.app.timeline.meta.Timeline import org.andstatus.app.util.MyLog import org.andstatus.app.util.TryUtils /** * Downloads ("loads") different types of Timelines * (i.e. Tweets and Messages) from the Internet (e.g. from twitter.com server). * Then Store them into local database using [DataUpdater] * * @author <EMAIL> */ internal abstract class TimelineDownloader(execContext: CommandExecutionContext) : CommandExecutorStrategy(execContext) { override suspend fun execute(): Try<Boolean> { if (!isApiSupported(execContext.timeline.timelineType.connectionApiRoutine)) { MyLog.v(this) { (execContext.timeline.toString() + " is not supported for " + execContext.myAccount.getAccountName()) } return TryUtils.TRUE } MyLog.d( this, "Getting " + execContext.commandData.toCommandSummary(execContext.myContext) + " by " + execContext.myAccount.getAccountName() ) return download() } abstract suspend fun download(): Try<Boolean> protected val timeline: Timeline get() = execContext.timeline override fun onResultIsReady() { execContext.result.takeIf { it.executed }?.let { result -> timeline.onSyncEnded(execContext.myContext, result) if (result.downloadedCount > 0) { if (!result.hasError && !isStopping()) { DataPruner(execContext.myContext).prune() } MyLog.v(this, "Notifying of timeline changes") execContext.myContext.notifier.update() } } } protected fun isSyncYounger(): Boolean { return execContext.commandData.command != CommandEnum.GET_OLDER_TIMELINE } }
86
Kotlin
69
306
6166aded1f115e6e6a7e66ca3756f39f0434663e
2,578
andstatus
Apache License 2.0
app/src/main/java/com/wimank/craftmaster/tz/app/mvp/views/AchievementView.kt
WiMank
210,546,864
false
null
package com.wimank.craftmaster.tz.app.mvp.views import com.arellomobile.mvp.MvpView import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy import com.arellomobile.mvp.viewstate.strategy.SkipStrategy import com.arellomobile.mvp.viewstate.strategy.StateStrategyType import com.wimank.craftmaster.tz.app.room.entity.AchievementEntity @StateStrategyType(AddToEndSingleStrategy::class) interface AchievementView : MvpView { fun showAchievements(list: List<AchievementEntity>) @StateStrategyType(SkipStrategy::class) fun showError(message: Int) }
0
Kotlin
0
0
4195f13d8d050e950dad4567183955292c504908
572
Craft-Master-2.0
MIT License
app/src/main/java/cz/nestresuju/screens/diary/errors/DiaryErrorHandler.kt
johnondrej
371,166,772
false
null
package cz.nestresuju.screens.diary.errors import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar import cz.nestresuju.R import cz.nestresuju.model.errors.handlers.FragmentErrorHandler /** * Error handler for handling specific errors that can occur in diary screen. */ class DiaryErrorHandler : FragmentErrorHandler { override fun handleError(handlingView: Fragment, error: Throwable): Boolean { with(handlingView) { view?.let { return when (error) { is EmptyAnswerException -> { Snackbar.make(it, R.string.diary_error_empty_answer, Snackbar.LENGTH_LONG).show() true } else -> false } } } return false } }
0
Kotlin
0
0
8d7c54c00c865a370ed24a356abd2bfeeef4ed4b
842
nestresuju-android
Apache License 2.0
src/test/kotlin/com/github/sarxos/webcam/ScreenImage.kt
Kietyo
564,699,784
false
{"Kotlin": 276119}
package com.github.sarxos.webcam import java.awt.* import java.awt.image.BufferedImage import java.io.File import java.io.IOException import java.util.* import javax.imageio.ImageIO import javax.swing.JComponent import javax.swing.SwingUtilities /* * Convenience class to create and optionally save to a file a * BufferedImage of an area on the screen. Generally there are * four different scenarios. Create an image of: * * a) an entire component * b) a region of the component * c) the entire desktop * d) a region of the desktop * * The first two use the Swing paint() method to draw the * component image to the BufferedImage. The latter two use the * AWT Robot to create the BufferedImage. * * The created image can then be saved to a file by usig the * writeImage(...) method. The type of file must be supported by the * ImageIO write method. * * Although this class was originally designed to create an image of a * component on the screen it can be used to create an image of components * not displayed on a GUI. Behind the scenes the component will be given a * size and the component will be layed out. The default size will be the * preferred size of the component although you can invoke the setSize() * method on the component before invoking a createImage(...) method. The * default functionality should work in most cases. However the only * foolproof way to get a image to is make sure the component has been * added to a realized window with code something like the following: * * JFrame frame = new JFrame(); * frame.setContentPane( someComponent ); * frame.pack(); * ScreenImage.createImage( someComponent ); * */ object ScreenImage { private val types = listOf(*ImageIO.getWriterFileSuffixes()) /* * Create a BufferedImage for Swing components. The entire component will be captured to an * image. * @param component Swing component to create image from * @return image the image for the given region */ fun createImage(component: JComponent): BufferedImage { var d = component.size if (d.width == 0 || d.height == 0) { d = component.preferredSize component.size = d } val region = Rectangle(0, 0, d.width, d.height) return createImage(component, region) } /* * Create a BufferedImage for Swing components. All or part of the component can be captured to * an image. * @param component Swing component to create image from * @param region The region of the component to be captured to an image * @return image the image for the given region */ fun createImage(component: JComponent, region: Rectangle): BufferedImage { // Make sure the component has a size and has been layed out. // (necessary check for components not added to a realized frame) if (!component.isDisplayable) { var d = component.size if (d.width == 0 || d.height == 0) { d = component.preferredSize component.size = d } layoutComponent(component) } val image = BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB) val g2d = image.createGraphics() // Paint a background for non-opaque components, // otherwise the background will be black if (!component.isOpaque) { g2d.color = component.background g2d.fillRect(region.x, region.y, region.width, region.height) } g2d.translate(-region.x, -region.y) component.print(g2d) g2d.dispose() return image } /** * Convenience method to create a BufferedImage of the desktop * * @param fileName name of file to be created or null * @return image the image for the given region * @exception AWTException see Robot class constructors * @exception IOException if an error occurs during writing */ @Throws(AWTException::class, IOException::class) fun createDesktopImage(): BufferedImage { val d = Toolkit.getDefaultToolkit().screenSize val region = Rectangle(0, 0, d.width, d.height) return createImage(region) } /* * Create a BufferedImage for AWT components. This will include Swing components JFrame, JDialog * and JWindow which all extend from Component, not JComponent. * @param component AWT component to create image from * @return image the image for the given region * @exception AWTException see Robot class constructors */ @Throws(AWTException::class) fun createImage(component: Component): BufferedImage { val p = Point(0, 0) SwingUtilities.convertPointToScreen(p, component) val region = component.bounds region.x = p.x region.y = p.y return createImage(region) } /** * Create a BufferedImage from a rectangular region on the screen. * * @param region region on the screen to create image from * @return image the image for the given region * @exception AWTException see Robot class constructors */ @Throws(AWTException::class) fun createImage(region: Rectangle?): BufferedImage { return Robot().createScreenCapture(region) } /** * Write a BufferedImage to a File. * * @param image image to be written * @param fileName name of file to be created * @exception IOException if an error occurs during writing */ @Throws(IOException::class) fun writeImage(image: BufferedImage?, fileName: String?) { if (fileName == null) return val offset = fileName.lastIndexOf(".") if (offset == -1) { val message = "file suffix was not specified" throw IOException(message) } val type = fileName.substring(offset + 1) if (types.contains(type)) { ImageIO.write(image, type, File(fileName)) } else { val message = "unknown writer file suffix ($type)" throw IOException(message) } } fun layoutComponent(component: Component) { synchronized(component.treeLock) { component.doLayout() if (component is Container) { for (child in component.components) { layoutComponent(child) } } } } }
0
Kotlin
0
2
a67ebac2fb945a56dfac7f1f67f589eecdd58022
6,369
webcam-capture-kotlin
MIT License
feature/login/src/main/java/com/example/login/component/AppBar.kt
zhouquancheng-dev
678,103,314
false
{"Kotlin": 207288, "HTML": 3900}
package com.zqc.itinerary.ui.login.component import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarColors import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.zqc.itinerary.R @ExperimentalMaterial3Api @Composable fun UserTopAppBar( title: String, titleColor: Color = Color.Unspecified, iconTint: Color = LocalContentColor.current, topAppBarColors: TopAppBarColors = TopAppBarDefaults.topAppBarColors(), onBackClick: () -> Unit ) { TopAppBar( title = { Text( text = title, maxLines = 1, overflow = TextOverflow.Ellipsis, color = titleColor ) }, navigationIcon = { IconButton(onClick = { onBackClick() }) { Icon( imageVector = Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = stringResource(R.string.back_text), modifier = Modifier.size(30.dp), tint = iconTint ) } }, colors = topAppBarColors ) }
0
Kotlin
0
0
af4fd5feaa106297f1ce6fccc643fee28f9b2b80
1,790
Itinerary-android
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/mottak/repository/EttersendingVedleggRepository.kt
navikt
204,919,927
false
{"Kotlin": 442087, "Dockerfile": 178}
package no.nav.familie.ef.mottak.repository import no.nav.familie.ef.mottak.repository.domain.EttersendingVedlegg import no.nav.familie.ef.mottak.repository.util.InsertUpdateRepository import no.nav.familie.ef.mottak.repository.util.RepositoryInterface import org.springframework.data.jdbc.repository.query.Modifying import org.springframework.data.jdbc.repository.query.Query import org.springframework.stereotype.Repository import java.util.UUID @Repository interface EttersendingVedleggRepository : RepositoryInterface<EttersendingVedlegg, UUID>, InsertUpdateRepository<EttersendingVedlegg> { fun findByEttersendingId(ettersendingId: UUID): List<EttersendingVedlegg> @Query("SELECT ettersending_id from ettersending_vedlegg where id = :ettersendingVedleggId") fun findEttersendingIdById(ettersendingVedleggId: UUID): UUID @Modifying @Query("DELETE FROM ettersending_vedlegg WHERE ettersending_id = :ettersendingId") fun deleteAllByEttersendingId(ettersendingId: UUID) @Modifying @Query("UPDATE ettersending_vedlegg SET ettersending_id = :ettersendingId WHERE id = :id") fun oppdaterEttersendingIdForVedlegg( id: UUID, ettersendingId: UUID, ): Int }
0
Kotlin
2
0
5e850136165b6cf0a6c3826f0f9ca912075dc6ed
1,221
familie-ef-mottak
MIT License
app/src/main/kotlin/org/singularux/music/ui/screen/home/HomeDrawerSheet.kt
xNovo3000
676,984,345
false
null
package org.singularux.music.ui.screen.home import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Album import androidx.compose.material.icons.rounded.Info import androidx.compose.material.icons.rounded.MusicNote import androidx.compose.material.icons.rounded.People import androidx.compose.material.icons.rounded.QueueMusic import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import com.google.accompanist.drawablepainter.rememberDrawablePainter import org.singularux.music.R import org.singularux.music.ui.core.MusicTheme enum class SelectedSubRouteStub { TRACKS, ALBUMS, ARTISTS, PLAYLISTS } data class HomeDrawerSheetState( val selectedSubRoute: SelectedSubRouteStub ) enum class HomeDrawerSheetAction { TRACKS, ALBUMS, ARTISTS, PLAYLISTS, SETTINGS, INFO } @Composable fun HomeDrawerSheet( modifier: Modifier = Modifier, state: HomeDrawerSheetState, onAction: (HomeDrawerSheetAction) -> Unit ) { ModalDrawerSheet(modifier = modifier) { Column(modifier = Modifier.verticalScroll(state = rememberScrollState())) { // App header Row( modifier = Modifier.padding(24.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically ) { // App icon Image( modifier = Modifier.size(48.dp), painter = rememberDrawablePainter( drawable = ContextCompat.getDrawable(LocalContext.current, R.mipmap.ic_launcher) ), contentDescription = stringResource(id = R.string.manifest_app_name) ) // App name Text( modifier = Modifier.weight(1F), text = stringResource(id = R.string.manifest_app_name), style = MaterialTheme.typography.headlineMedium ) } // Library header HomeDrawerSheetSectionHeader( name = stringResource(id = R.string.home_drawer_sheet_library) ) // Tracks HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_tracks), icon = Icons.Rounded.MusicNote, isSelected = state.selectedSubRoute == SelectedSubRouteStub.TRACKS ), onClick = { onAction(HomeDrawerSheetAction.TRACKS) } ) // Albums HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_albums), icon = Icons.Rounded.Album, isSelected = state.selectedSubRoute == SelectedSubRouteStub.ALBUMS ), onClick = { onAction(HomeDrawerSheetAction.ALBUMS) } ) // Artists HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_artists), icon = Icons.Rounded.People, isSelected = state.selectedSubRoute == SelectedSubRouteStub.ARTISTS ), onClick = { onAction(HomeDrawerSheetAction.ARTISTS) } ) // Playlists HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_playlists), icon = Icons.Rounded.QueueMusic, isSelected = state.selectedSubRoute == SelectedSubRouteStub.PLAYLISTS ), onClick = { onAction(HomeDrawerSheetAction.PLAYLISTS) } ) // Divider Divider( modifier = Modifier .padding(horizontal = 20.dp) .padding(top = 8.dp) ) // More header HomeDrawerSheetSectionHeader( name = stringResource(id = R.string.home_drawer_sheet_more) ) // Settings HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_settings), icon = Icons.Rounded.Settings, isSelected = false ), onClick = { onAction(HomeDrawerSheetAction.SETTINGS) } ) // Info HomeDrawerSheetItem( state = HomeDrawerSheetItemState( name = stringResource(id = R.string.home_drawer_sheet_info), icon = Icons.Rounded.Info, isSelected = false ), onClick = { onAction(HomeDrawerSheetAction.INFO) } ) } } } @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO) @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun Preview() { MusicTheme { HomeDrawerSheet( state = HomeDrawerSheetState(selectedSubRoute = SelectedSubRouteStub.PLAYLISTS), onAction = {} ) } }
0
Kotlin
0
0
ee501fe7764838c0585b37a805936e616babfcaa
6,287
SingularUX-Music
MIT License
src/test/kotlin/_50to100/Task73Test.kt
embuc
735,933,359
false
{"Kotlin": 136592, "Java": 79261}
package _50to100 import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import se.embuc._50to100.Task73 class Task73Test { @Test fun solve() { assertEquals(7295372, Task73().solve()) assertEquals(7295372, JTask73().solve()) } }
0
Kotlin
0
1
74af4e8537be183d43fa26d1a08032d7785ab862
269
projecteuler
MIT License
feature/solve-problem/src/main/kotlin/team/duckie/app/android/feature/solve/problem/screen/QuizScreen.kt
duckie-team
503,869,663
false
null
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ @file:OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class, ) package team.duckie.app.android.feature.solve.problem.screen import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.launch import team.duckie.app.android.domain.exam.model.Answer import team.duckie.app.android.domain.exam.model.Problem.Companion.isSubjective import team.duckie.app.android.feature.solve.problem.R import team.duckie.app.android.feature.solve.problem.answer.answerSection import team.duckie.app.android.feature.solve.problem.common.ButtonBottomBar import team.duckie.app.android.feature.solve.problem.common.TimerTopBar import team.duckie.app.android.feature.solve.problem.question.questionSection import team.duckie.app.android.feature.solve.problem.viewmodel.state.InputAnswer import team.duckie.app.android.feature.solve.problem.viewmodel.state.SolveProblemState import team.duckie.app.android.common.compose.ui.dialog.DuckieDialog import team.duckie.app.android.common.compose.isCurrentPage import team.duckie.app.android.common.compose.ui.Spacer import team.duckie.app.android.common.kotlin.exception.duckieResponseFieldNpe import team.duckie.app.android.feature.solve.problem.common.FlexibleSubjectiveQuestionSection private const val QuizTopAppBarLayoutId = "QuizTopAppBar" private const val QuizContentLayoutId = "QuizContent" private const val QuizBottomBarLayoutId = "QuizBottomBar" @Composable internal fun QuizScreen( state: SolveProblemState, pagerState: PagerState, progress: () -> Float, stopExam: () -> Unit, finishQuiz: (Int, Boolean) -> Unit, onNextPage: (Int, InputAnswer, Int) -> Unit, startTimer: () -> Unit, ) { val totalPage = remember { state.totalPage } val coroutineScope = rememberCoroutineScope() var examExitDialogVisible by remember { mutableStateOf(false) } val timeOver by remember { derivedStateOf { progress() == 0f } } val inputAnswers = remember { mutableStateListOf( elements = Array( size = state.quizProblems.size, init = { InputAnswer() }, ), ) } LaunchedEffect(pagerState.targetPage) { startTimer() } LaunchedEffect(timeOver) { if (timeOver) { finishQuiz(pagerState.currentPage, false) } } DuckieDialog( title = stringResource(id = R.string.quit_exam), message = stringResource(id = R.string.not_saved), leftButtonText = stringResource(id = R.string.cancel), leftButtonOnClick = { examExitDialogVisible = false }, rightButtonText = stringResource(id = R.string.quit), rightButtonOnClick = stopExam, visible = examExitDialogVisible, onDismissRequest = { examExitDialogVisible = false }, ) Layout( content = { TimerTopBar( modifier = Modifier.layoutId(QuizTopAppBarLayoutId), onCloseClick = { examExitDialogVisible = true }, progress = progress, ) ContentSection( modifier = Modifier.layoutId(QuizContentLayoutId), pagerState = pagerState, state = state, inputAnswers = inputAnswers.toImmutableList(), updateInputAnswers = { index, answer -> inputAnswers[index] = answer }, ) ButtonBottomBar( modifier = Modifier .layoutId(QuizBottomBarLayoutId) .fillMaxWidth(), isLastPage = pagerState.currentPage == totalPage - 1, onRightButtonClick = { coroutineScope.launch { val maximumPage = totalPage - 1 if (pagerState.currentPage == maximumPage) { finishQuiz(pagerState.currentPage, true) } else { onNextPage( pagerState.currentPage, inputAnswers[pagerState.currentPage], maximumPage, ) } } }, ) }, measurePolicy = screenMeasurePolicy( topLayoutId = QuizTopAppBarLayoutId, contentLayoutId = QuizContentLayoutId, bottomLayoutId = QuizBottomBarLayoutId, ), ) } @Composable private fun ContentSection( modifier: Modifier = Modifier, pagerState: PagerState, state: SolveProblemState, inputAnswers: ImmutableList<InputAnswer>, updateInputAnswers: (page: Int, inputAnswer: InputAnswer) -> Unit, ) { val keyboardController = LocalSoftwareKeyboardController.current HorizontalPager( modifier = modifier, pageCount = state.totalPage, state = pagerState, userScrollEnabled = false, ) { pageIndex -> val problem = state.quizProblems[pageIndex] val requestFocus by remember(key1 = pagerState.currentPage) { derivedStateOf { pagerState.isCurrentPage(pageIndex) } } LaunchedEffect(key1 = requestFocus) { if (!problem.isSubjective()) { keyboardController?.hide() } } when { // for keyboard flexible image height problem.isSubjective() && problem.question.isImage() -> FlexibleSubjectiveQuestionSection( problem = problem, pageIndex = pageIndex, inputAnswers = inputAnswers, updateInputAnswers = updateInputAnswers, requestFocus = requestFocus, keyboardController = keyboardController, ) else -> LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(space = 24.dp), ) { item { Spacer(modifier = Modifier.padding(top = 16.dp)) } questionSection( page = pageIndex, question = problem.question, ) val answer = problem.answer answerSection( pageIndex = pageIndex, answer = when (answer) { is Answer.Short -> Answer.Short( problem.correctAnswer ?: duckieResponseFieldNpe("null 이 되면 안됩니다."), ) is Answer.Choice, is Answer.ImageChoice -> answer else -> duckieResponseFieldNpe("해당 분기로 빠질 수 없는 AnswerType 입니다.") }, inputAnswers = inputAnswers, updateInputAnswers = updateInputAnswers, requestFocus = requestFocus, keyboardController = keyboardController, ) } } } }
19
Kotlin
2
34
4fa7edae1fd24811ec278b0e24236c247f98dff0
8,613
duckie-android
MIT License
app/src/main/java/io/github/mklkj/filmowy/api/pojo/FilmPerson.kt
mklkj
166,846,534
false
{"HTML": 181836, "Kotlin": 179891}
package io.github.mklkj.filmowy.api.pojo data class FilmPerson( val filmId: Int, val assocType: AssocType, val personId: Long, val assocName: String?, val assocAttributes: String?, val personName: String, val personImagePath: String? ) { enum class AssocType(val id: Int) { UNKNOWN(0), DIRECTOR(1), SCREENWRITER(2), MUSIC(3), CINEMATOGRAPHER(4), ORIGINAL_MATERIALS(5), ACTOR(6), SELF(7), VOICE(8), PRODUCER(9), MONTAGE(10), COSTUME_DESIGNER(11), ARCHIVAL_MATERIALS(12), GUEST(13); companion object { private val values = values() fun getById(id: Int) = values.firstOrNull { it.id == id } ?: UNKNOWN } } }
1
HTML
0
7
e7f01ad5d0771254e907e59aa4df4ef0e6fd7293
795
filmowy
Apache License 2.0
src/integrationTest/kotlin/uk/gov/justice/digital/hmpps/jobsboard/api/controller/jobs/JobsGetShould.kt
ministryofjustice
775,484,528
false
{"Kotlin": 167612, "Dockerfile": 1146}
package uk.gov.justice.digital.hmpps.jobsboard.api.controller.jobs import org.junit.jupiter.api.Test import org.springframework.http.HttpStatus.CREATED class JobsGetShould : JobsTestCase() { @Test fun `retrieve an existing Job`() { assertAddEmployer( id = "bf392249-b360-4e3e-81a0-8497047987e8", body = amazonBody, expectedStatus = CREATED, ) val jobId = assertAddJobIsCreated(body = amazonForkliftOperatorJobBody) assertGetJobIsOK( jobId = jobId, expectedResponse = amazonForkliftOperatorJobResponse(jobCreationTime), ) } @Test fun `retrieve an existing Job with all optional fields empty`() { assertAddEmployer( id = "182e9a24-6edb-48a6-a84f-b7061f004a97", body = abcConstructionBody, expectedStatus = CREATED, ) val jobId = assertAddJobIsCreated(body = abcConstructionJobBody) assertGetJobIsOK( jobId = jobId, expectedResponse = abcConstructionJobResponse(jobCreationTime), ) } @Test fun `return null on empty optional fields`() { assertAddEmployer( id = "89de6c84-3372-4546-bbc1-9d1dc9ceb354", body = tescoBody, expectedStatus = CREATED, ) val jobId = assertAddJobIsCreated(body = tescoWarehouseHandlerJobBody) assertGetJobIsOK( jobId = jobId, expectedResponse = tescoWarehouseHandlerJobBody, ) } @Test fun `retrieve a default paginated empty Jobs list`() { assertGetJobIsOK( expectedResponse = expectedResponseListOf(), ) } @Test fun `retrieve a default paginated Jobs list`() { givenThreeJobsAreCreated() assertGetJobIsOK( expectedResponse = expectedResponseListOf( amazonForkliftOperatorJobItemListResponse(jobCreationTime), tescoWarehouseHandlerJobItemListResponse(jobCreationTime), abcConstructionJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a custom paginated Jobs list`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "page=1&size=1", expectedResponse = expectedResponseListOf( size = 1, page = 1, totalElements = 3, amazonForkliftOperatorJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by full Job title`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=Forklift operator", expectedResponse = expectedResponseListOf( amazonForkliftOperatorJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by incomplete Job title`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=operator", expectedResponse = expectedResponseListOf( amazonForkliftOperatorJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by full Employer name`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=Tesco", expectedResponse = expectedResponseListOf( tescoWarehouseHandlerJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by incomplete Employer name`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=Tes", expectedResponse = expectedResponseListOf( tescoWarehouseHandlerJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by job sector`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "sector=retail", expectedResponse = expectedResponseListOf( amazonForkliftOperatorJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list filtered by Job title OR Employer name AND job sector`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=tesco&sector=retail", expectedResponse = expectedResponseListOf(), ) } @Test fun `retrieve a default paginated Jobs list filtered by incomplete Job title OR Employer name AND job sector`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=er&sector=construction", expectedResponse = expectedResponseListOf( abcConstructionJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a custom paginated Jobs list filtered by Job title OR Employer name AND job sector`() { givenThreeJobsAreCreated() assertGetJobIsOK( parameters = "jobTitleOrEmployerName=Tesco&sector=warehousing&page=0&size=1", expectedResponse = expectedResponseListOf( size = 1, page = 0, totalElements = 1, tescoWarehouseHandlerJobItemListResponse(jobCreationTime), ), ) } @Test fun `retrieve a default paginated Jobs list sorted by job title, in ascending order, by default`() { givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByJobTitle( expectedJobTitlesSorted = listOf( "Apprentice plasterer", "Forklift operator", "Warehouse handler", ), ) } @Test fun `retrieve a default paginated Jobs list sorted by job title, in ascending order`() { givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByJobTitle( parameters = "sortBy=jobTitle&sortOrder=asc", expectedJobTitlesSorted = listOf( "Apprentice plasterer", "Forklift operator", "Warehouse handler", ), ) } @Test fun `retrieve a default paginated Jobs list sorted by job title, in descending order`() { givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByJobTitle( parameters = "sortBy=jobTitle&sortOrder=desc", expectedJobTitlesSorted = listOf( "Warehouse handler", "Forklift operator", "Apprentice plasterer", ), ) } @Test fun `retrieve a default paginated Jobs list sorted by creation date, in ascending order, by default`() { givenJobsMustHaveDifferentCreationTimes() givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByDate( parameters = "sortBy=createdAt", expectedSortingOrder = "asc", ) } @Test fun `retrieve a default paginated Jobs list sorted by creation date, in ascending order`() { val sortingOrder = "asc" givenJobsMustHaveDifferentCreationTimes() givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByDate( parameters = "sortBy=createdAt&sortOrder=$sortingOrder", expectedSortingOrder = sortingOrder, ) } @Test fun `retrieve a default paginated Jobs list sorted by creation date, in descending order`() { val sortingOrder = "desc" givenJobsMustHaveDifferentCreationTimes() givenThreeJobsAreCreated() assertGetJobIsOKAndSortedByDate( parameters = "sortBy=createdAt&sortOrder=$sortingOrder", expectedSortingOrder = sortingOrder, ) } private fun givenJobsMustHaveDifferentCreationTimes() { givenCurrentTimeIsStrictlyIncreasing(jobCreationTime) } private fun givenThreeJobsAreCreated() { assertAddEmployer( id = "89de6c84-3372-4546-bbc1-9d1dc9ceb354", body = tescoBody, expectedStatus = CREATED, ) assertAddEmployer( id = "bf392249-b360-4e3e-81a0-8497047987e8", body = amazonBody, expectedStatus = CREATED, ) assertAddEmployer( id = "182e9a24-6edb-48a6-a84f-b7061f004a97", body = abcConstructionBody, expectedStatus = CREATED, ) assertAddJobIsCreated( body = tescoWarehouseHandlerJobBody, ) assertAddJobIsCreated( body = amazonForkliftOperatorJobBody, ) assertAddJobIsCreated( body = abcConstructionJobBody, ) } }
3
Kotlin
0
1
f821551ec9a18686b0dafe343377857b683e47b0
7,976
hmpps-jobs-board-api
MIT License
src/commonMain/kotlin/baaahs/show/live/LinkedPatch.kt
baaahs
174,897,412
false
{"Kotlin": 4817609, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56277, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.show.live import baaahs.app.ui.patchmod.PatchMod import baaahs.gl.patch.Component import baaahs.gl.patch.ProgramLinker import baaahs.gl.patch.ProgramNode import baaahs.gl.patch.ShaderComponent import baaahs.gl.shader.OpenShader import baaahs.gl.shader.OutputPort import baaahs.show.Stream import baaahs.util.Logger class LinkedPatch( val shader: OpenShader, incomingLinks: Map<String, ProgramNode>, val stream: Stream, val priority: Float, val injectedPorts: Set<String> = emptySet(), val patchMods: List<PatchMod> = emptyList(), val modsNode: ProgramNode? = null ) : ProgramNode { override val title: String get() = shader.title override val outputPort: OutputPort get() = shader.outputPort val isPatchMod get() = modsNode != null val unmoddedIncomingLinks = incomingLinks val incomingLinks = incomingLinks.mapValues { (inputPortId, link) -> var redirectableLink = link patchMods.forEach { patchMod -> val oldLink = redirectableLink redirectableLink = patchMod.maybeWrapLink(this, inputPortId, redirectableLink, shader) ?: redirectableLink if (redirectableLink !== oldLink) logger.debug { "Redirected $oldLink via $redirectableLink." } } redirectableLink } val passThroughUniforms = shader.glslCode.globalInputVars.filter { it.isPassThrough } override fun getNodeId(programLinker: ProgramLinker): String = programLinker.idFor(shader.shader) override fun traverse(programLinker: ProgramLinker) { programLinker.visit(shader) incomingLinks.forEach { (_, link) -> programLinker.visit(link) } } override fun buildComponent( id: String, index: Int, prefix: String, findUpstreamComponent: (ProgramNode) -> Component ): Component { return ShaderComponent(id, index, prefix, this, findUpstreamComponent) } override fun toString(): String = "LinkedPatch(shader=${shader.title})" companion object { private val logger = Logger<LinkedPatch>() } }
113
Kotlin
13
40
e895b295f951668acdce0371b791e0316a633da6
2,144
sparklemotion
MIT License
app/src/test/java/com/actively/statistics/StatisticsViewModelTest.kt
actively-pw
671,584,612
false
{"Kotlin": 364808}
package com.actively.statistics import app.cash.turbine.test import com.actively.R import com.actively.activity.Discipline import com.actively.statistics.usecase.GetStatisticsUseCase import com.actively.stubs.stubStatPage import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import kotlin.time.Duration.Companion.milliseconds @OptIn(ExperimentalCoroutinesApi::class) class StatisticsViewModelTest : FunSpec({ isolationMode = IsolationMode.InstancePerTest coroutineTestScope = true val getStatisticsUseCase = mockk<GetStatisticsUseCase>() coEvery { getStatisticsUseCase() } coAnswers { delay(500.milliseconds) Result.success( listOf( stubStatPage(sport = Discipline.Cycling), stubStatPage(sport = Discipline.Running), stubStatPage(sport = Discipline.NordicWalking) ) ) } val statTabFactory = StatTabFactory() context("state test") { test("init state is correct") { val viewModel = StatisticsViewModel(getStatisticsUseCase, statTabFactory) viewModel.state.test { awaitItem() shouldBe StatisticsState( tabs = listOf( StatTab(R.string.cycling), StatTab(R.string.running), StatTab(R.string.nordic_walking) ), selectedTab = 0, isLoading = true, isError = false ) } } test("loads state on init") { val viewModel = StatisticsViewModel(getStatisticsUseCase, statTabFactory) viewModel.state.test { awaitItem() awaitItem() shouldBe StatisticsState( tabs = listOf(cyclingState(), runningState(), nordicWalingState()), selectedTab = 0, isLoading = false, isError = false ) } } test("sets error flag if getStatisticsUseCase failed") { coEvery { getStatisticsUseCase() } coAnswers { delay(500.milliseconds) Result.failure(Exception()) } val viewModel = StatisticsViewModel(getStatisticsUseCase, statTabFactory) viewModel.state.test { awaitItem() awaitItem() shouldBe StatisticsState( tabs = listOf( StatTab(sport = R.string.cycling), StatTab(sport = R.string.running), StatTab(sport = R.string.nordic_walking), ), selectedTab = 0, isLoading = false, isError = true ) } } } context("actions") { val viewModel = StatisticsViewModel(getStatisticsUseCase, statTabFactory) test("onSelectTab properly updates selected tab index") { viewModel.state.test { awaitItem() awaitItem() viewModel.onSelectTab(2) awaitItem() shouldBe StatisticsState( tabs = listOf(cyclingState(), runningState(), nordicWalingState()), selectedTab = 2, isLoading = false, isError = false ) viewModel.onSelectTab(1) awaitItem() shouldBe StatisticsState( tabs = listOf(cyclingState(), runningState(), nordicWalingState()), selectedTab = 1, isLoading = false, isError = false ) viewModel.onSelectTab(0) awaitItem() shouldBe StatisticsState( tabs = listOf(cyclingState(), runningState(), nordicWalingState()), selectedTab = 0, isLoading = false, isError = false ) viewModel.onSelectTab(2) awaitItem() shouldBe StatisticsState( tabs = listOf(cyclingState(), runningState(), nordicWalingState()), selectedTab = 2, isLoading = false, isError = false ) } } } beforeTest { Dispatchers.setMain(UnconfinedTestDispatcher()) } afterTest { Dispatchers.resetMain() } }) private fun runningState() = StatTab( sport = R.string.running, avgWeekly = listOf( LabeledValue(R.string.runs, "1"), LabeledValue(R.string.time, "1h 0m"), LabeledValue(R.string.distance, "10 km"), ), yearToDate = listOf( LabeledValue(R.string.runs, "10"), LabeledValue(R.string.time, "10h 0m"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.elevation_gain, "1000 m"), ), allTime = listOf( LabeledValue(R.string.runs, "10"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.longest_run, "10 km"), ) ) private fun cyclingState() = StatTab( sport = R.string.cycling, avgWeekly = listOf( LabeledValue(R.string.rides, "1"), LabeledValue(R.string.time, "1h 0m"), LabeledValue(R.string.distance, "10 km"), ), yearToDate = listOf( LabeledValue(R.string.rides, "10"), LabeledValue(R.string.time, "10h 0m"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.elevation_gain, "1000 m"), ), allTime = listOf( LabeledValue(R.string.rides, "10"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.longest_ride, "10 km"), ) ) private fun nordicWalingState() = StatTab( sport = R.string.nordic_walking, avgWeekly = listOf( LabeledValue(R.string.walks, "1"), LabeledValue(R.string.time, "1h 0m"), LabeledValue(R.string.distance, "10 km"), ), yearToDate = listOf( LabeledValue(R.string.walks, "10"), LabeledValue(R.string.time, "10h 0m"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.elevation_gain, "1000 m"), ), allTime = listOf( LabeledValue(R.string.walks, "10"), LabeledValue(R.string.distance, "100 km"), LabeledValue(R.string.longest_walk, "10 km"), ) )
0
Kotlin
0
0
33c791dfa6ce82a6ccacb1b5cdb39d2a26302ef4
6,867
actively-mobile
MIT License
core/src/main/kotlin/org/neo4j/graphql/QueryContext.kt
neo4j-graphql
147,095,795
false
null
package org.neo4j.graphql data class QueryContext @JvmOverloads constructor( /** * if true the <code>__typename</code> will always be returned for interfaces, no matter if it was queried or not */ var queryTypeOfInterfaces: Boolean = false, /** * If set alternative approaches for query translation will be used */ var optimizedQuery: Set<OptimizationStrategy>? = null ) { enum class OptimizationStrategy { /** * If used, filter queries will be converted to cypher matches */ FILTER_AS_MATCH } }
58
null
37
94
95a63e0e1b0e1c43ab09246a463fea3de99ede87
609
neo4j-graphql-java
Apache License 2.0
data/src/main/java/com/saeedlotfi/limlam/data/mapper/ThemeDoMapper.kt
lotfi-workbox
603,992,478
false
null
package com.saeedlotfi.limlam.data.mapper import com.saeedlotfi.limlam.data.model.ThemeDbModel import com.saeedlotfi.limlam.domain.model.ThemeDoModel import io.realm.RealmList fun ThemeDoModel.asDatabaseModel(): ThemeDbModel { return ThemeDbModel( name = this.name, backgrounds = this.backgrounds, selectionBackgrounds = this.selectionBackgrounds, paleBackgrounds = this.paleBackgrounds, windowBackground = this.windowBackground, textsAndIcons = this.textsAndIcons, textHint = this.textHint, strokeColor = this.strokeColor, topOfWindows = this.topOfWindows, topOfWindowTexts = this.topOfWindowTexts, undoBar = this.undoBar, startShadow = this.startShadow, endShadow = this.endShadow, rippleColor = this.rippleColor, id = this.id, ) } fun ThemeDbModel.asDomainModel(): ThemeDoModel { return ThemeDoModel( name = this.name, backgrounds = this.backgrounds, selectionBackgrounds = this.selectionBackgrounds, paleBackgrounds = this.paleBackgrounds, windowBackground = this.windowBackground, textsAndIcons = this.textsAndIcons, textHint = this.textHint, strokeColor = this.strokeColor, topOfWindows = this.topOfWindows, topOfWindowTexts = this.topOfWindowTexts, undoBar = this.undoBar, startShadow = this.startShadow, endShadow = this.endShadow, rippleColor = this.rippleColor, id = this.id, ) } fun List<ThemeDoModel>.asDatabaseModel(): RealmList<ThemeDbModel> { return RealmList<ThemeDbModel>().also { list -> list.addAll(this.map { it.asDatabaseModel() }) } } fun List<ThemeDbModel>.asDomainModel(): List<ThemeDoModel> = this.map { it.asDomainModel() }
0
Kotlin
0
0
8964b2b259d96252b1381e844d23ba3c15e85001
1,830
limlam
Apache License 2.0
plugin/src/main/kotlin/ru/cian/huawei/publish/HuaweiPublishPlugin.kt
cianru
234,567,962
false
{"Kotlin": 89181}
package ru.cian.huawei.publish import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.api.variant.ApplicationVariant import com.android.build.api.variant.VariantSelector import com.android.build.gradle.AppPlugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.register import org.gradle.kotlin.dsl.withType class HuaweiPublishPlugin : Plugin<Project> { override fun apply(project: Project) { project.plugins.withType<AppPlugin> { configureHuaweiPublish(project) } } private fun configureHuaweiPublish(project: Project) { project.extensions.create<HuaweiPublishExtension>( HuaweiPublishExtension.MAIN_EXTENSION_NAME, project ) val androidComponents = project.extensions.getByType<ApplicationAndroidComponentsExtension>() androidComponents.onVariants(androidComponents.selector().all() as VariantSelector) { variant -> createTask(project, variant) } } @Suppress("DefaultLocale") private fun createTask( project: Project, variant: ApplicationVariant, ) { val variantName = variant.name.capitalize() val publishTaskName = "${HuaweiPublishTask.TASK_NAME}$variantName" val publishTask = project.tasks.register<HuaweiPublishTask>(publishTaskName, variant) scheduleTasksOrder(publishTask, project, variantName) } private fun scheduleTasksOrder( publishTask: TaskProvider<HuaweiPublishTask>, project: Project, variantName: String ) { project.gradle.projectsEvaluated { mustRunAfter(project, publishTask, "assemble$variantName") mustRunAfter(project, publishTask, "bundle$variantName") } } private fun mustRunAfter( project: Project, publishTask: TaskProvider<HuaweiPublishTask>, taskBeforeName: String, ) { if (project.tasks.findByName(taskBeforeName) != null) { val assembleTask = project.tasks.named(taskBeforeName).get() publishTask.get().mustRunAfter(assembleTask) } } }
4
Kotlin
22
113
64b57d5615f6738d458e53404905d1c11babc0ce
2,311
huawei-appgallery-publish-gradle-plugin
Apache License 2.0
app/src/main/java/com/dilsahozkan/papafood/common/PageIndicator.kt
dilekdilsahozkan
810,291,020
false
{"Kotlin": 95375}
package com.dilsahozkan.papafood.common import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @Composable fun PageIndicator(pageCount: Int, currentPage: Int, modifier: Modifier) { Row( horizontalArrangement = Arrangement.Absolute.Center, verticalAlignment = Alignment.CenterVertically, modifier = modifier ) { repeat(pageCount){ IndicatorDot(isSelected = it == currentPage, modifier= modifier) } } }
0
Kotlin
0
0
58c528af3a474136ea3d4946425c3ced79889a5a
628
PapaFood
MIT License
src/test/java/com/github/greennick/properties/generic/BooleanExtensionsTest.kt
green-nick
170,363,475
false
null
package com.github.greennick.properties.generic import com.github.greennick.properties.propertyOf import com.github.greennick.properties.triggerPropertyOf import org.junit.Test class BooleanExtensionsTest { @Test fun `not creates property with opposite value`() { val init = true val property = propertyOf(init) val oppositeProperty = !property assert(oppositeProperty.value != init) } @Test fun `opposite property listen parent's changes`() { val property = propertyOf(true) val oppositeProperty = !property val newValue = false property.value = false assert(oppositeProperty.value != newValue) } @Test fun `toggle changes property's value`() { val init = true val property = propertyOf(init) property.toggle() assert(property.value != init) } @Test fun `double toggle return property's value to begin`() { val init = true val property = propertyOf(init) property.toggle() property.toggle() assert(property.value == init) } @Test fun `subscribeOnTrue called on true`() { var called = 0 val property = triggerPropertyOf(true) property.subscribeOnTrue { called++ } property.value = true assert(called == 2) } @Test fun `subscribeOnTrue isn't called on false`() { var called = 0 val property = triggerPropertyOf(false) property.subscribeOnTrue { called++ } property.value = false assert(called == 0) } @Test fun `subscribeOnFalse called on false`() { var called = 0 val property = triggerPropertyOf(false) property.subscribeOnFalse { called++ } property.value = false assert(called == 2) } @Test fun `subscribeOnFalse isn't called on true`() { var called = 0 val property = triggerPropertyOf(true) property.subscribeOnFalse { called++ } property.value = true assert(called == 0) } }
0
Kotlin
0
8
969741bf9750634e7c5a673c7551746fc4a1e1ab
2,103
properties
MIT License
core/src/main/kotlin/org/galois/core/engine/GaloisEngine.kt
fcarne
361,818,657
false
null
package org.galois.core.engine import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import org.galois.core.provider.GaloisJCE import org.galois.core.provider.decodeHex import org.galois.core.provider.fpe.FPEParameterSpec import org.galois.core.provider.fpe.dff.DFFParameterSpec import org.galois.core.provider.fpe.dff.DFF_ALGORITHM_NAME import org.galois.core.provider.fpe.ff3.FF3ParameterSpec import org.galois.core.provider.ope.aicd.AICDParameterSpec import org.galois.core.provider.ope.aicd.AICD_ALGORITHM_NAME import org.galois.core.provider.ope.fope.FOPEParameterSpec import org.galois.core.provider.ope.fope.FOPE_ALGORITHM_NAME import org.galois.core.provider.ope.pore.POREParameterSpec import org.galois.core.provider.ope.pore.PORE_ALGORITHM_NAME import org.galois.core.provider.ppe.cryptopan.CRYPTOPAN_ALGORITHM_NAME import org.galois.core.provider.ppe.cryptopan.CryptoPAnParameterSpec import org.galois.core.provider.ppe.hpcbc.HPCBCParameterSpec import org.galois.core.provider.ppe.hpcbc.HPCBC_ALGORITHM_NAME import org.galois.core.provider.toHexString import tech.tablesaw.api.StringColumn import tech.tablesaw.api.Table import tech.tablesaw.columns.Column import java.math.BigDecimal import java.math.BigInteger import java.net.InetAddress import java.nio.ByteBuffer import java.security.InvalidKeyException import java.security.spec.AlgorithmParameterSpec import java.util.* import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.SecretKeySpec import kotlin.experimental.and import kotlin.experimental.or import kotlin.math.ceil import kotlin.math.log2 class GaloisEngine(private val dataset: Table, configuration: EngineConfiguration) { private val configuration: EngineConfiguration init { GaloisJCE.add() this.configuration = configuration.clone() val columns = configuration.encryptionDetails.map { it.columnName } val nonExistentColumns = columns.minus(dataset.columnNames()) require(nonExistentColumns.isEmpty()) { "Columns $nonExistentColumns do not exist in the dataset" } val duplicateColumns = columns.groupingBy { it }.eachCount().filter { it.value > 1 } require(duplicateColumns.isEmpty()) { "Each column must appear only once: ${duplicateColumns.keys} appeared more than once" } val ciphers = configuration.encryptionDetails.map { it.cipher } val notSupportedCiphers = ciphers.minus(GaloisJCE.supportedAlgorithms) require(notSupportedCiphers.isEmpty()) { "Ciphers $notSupportedCiphers are not yet supported" } if (configuration.mode == EngineMode.DECRYPT) { val nullKeys = configuration.encryptionDetails.filter { it.key == null } require(nullKeys.isEmpty()) { "In DECRYPT mode all keys must be explicitly set" } val nullTweak = configuration.encryptionDetails.filter { it.cipher in GaloisJCE.fpeAlgorithms && it.params.cipherSpecific["tweak"] == null } require(nullTweak.isEmpty()) { "In DECRYPT mode, tweaks for must be explicitly set. Set them for columns ${nullTweak.map { it.columnName }}" } } } suspend fun compute(): Table = coroutineScope { val result = dataset.copy() val columns = configuration.encryptionDetails.map { async { columnDoFinal(it, dataset.column(it.columnName)) } } val computedColumns = columns.map { it.await() } computedColumns.forEach { result.replaceColumn(it) } result } private suspend fun columnDoFinal(detail: EncryptionDetail, column: Column<*>): Column<*> = coroutineScope { val computedColumn = StringColumn.create(column.name()) val (secretKey, parameters) = getKeyAndParameters(detail, column) val cipher = getCipher(detail, secretKey, parameters) val computedTaxonomy = detail.params.taxonomyTree?.let { async { taxonomyTreeDoFinal(it, detail, secretKey, parameters) } } column.forEach { value -> val cell = if (detail.cipher in GaloisJCE.fpeAlgorithms && value is Double) BigDecimal(value).toPlainString() else value.toString() val input = plaintextToByteArray(cell, detail) val output = cipher.doFinal(input) computedColumn.append(byteArrayToCiphertext(output, detail)) } computedTaxonomy?.await() computedColumn } private fun taxonomyTreeDoFinal( taxonomyTree: TaxonomyTree, detail: EncryptionDetail, secretKey: SecretKey, parameters: AlgorithmParameterSpec? ) { val cipher = getCipher(detail, secretKey, parameters) taxonomyNodeDoFinal(taxonomyTree.root, cipher, detail) } private fun taxonomyNodeDoFinal(node: TaxonomyNode, cipher: Cipher, detail: EncryptionDetail) { val input = plaintextToByteArray(node.cat.toString(), detail) val output = cipher.doFinal(input) node.cat = byteArrayToCiphertext(output, detail) node.subcats?.forEach { subNode -> taxonomyNodeDoFinal(subNode, cipher, detail) } } private fun plaintextToByteArray(plaintext: String, detail: EncryptionDetail): ByteArray { val suffixMode = detail.cipher in GaloisJCE.ppeAlgorithms && detail.params.cipherSpecific["suffix"] == true val ipMode = detail.cipher in GaloisJCE.ppeAlgorithms && detail.params.cipherSpecific.containsKey("ip") val opMode = configuration.mode return when { detail.cipher in GaloisJCE.opeAlgorithms && opMode == EngineMode.ENCRYPT -> ByteBuffer.allocate(Long.SIZE_BYTES).putLong(plaintext.toLong()).array() detail.cipher in GaloisJCE.opeAlgorithms && opMode == EngineMode.DECRYPT -> BigInteger(plaintext).toByteArray() ipMode && !suffixMode -> InetAddress.getByName(plaintext).address ipMode && suffixMode -> InetAddress.getByName(plaintext).address.reverseBits() suffixMode && opMode == EngineMode.ENCRYPT -> plaintext.reversed().toByteArray() suffixMode && opMode == EngineMode.DECRYPT -> Base64.getDecoder().decode(plaintext.reversed()) detail.cipher in GaloisJCE.fpeAlgorithms -> plaintext.toByteArray() ((!suffixMode && !ipMode) || detail.cipher in GaloisJCE.symmetricAlgorithms) && opMode == EngineMode.ENCRYPT -> plaintext.toByteArray() else -> Base64.getDecoder().decode(plaintext) } } private fun byteArrayToCiphertext(byteArray: ByteArray, detail: EncryptionDetail): String { val suffixMode = detail.cipher in GaloisJCE.ppeAlgorithms && detail.params.cipherSpecific["suffix"] == true val ipMode = detail.cipher in GaloisJCE.ppeAlgorithms && detail.params.cipherSpecific.containsKey("ip") val opMode = configuration.mode return when { detail.cipher in GaloisJCE.opeAlgorithms && opMode == EngineMode.ENCRYPT -> BigInteger(byteArray).toString() detail.cipher in GaloisJCE.opeAlgorithms && opMode == EngineMode.DECRYPT -> ByteBuffer.wrap(byteArray).long.toString() ipMode && !suffixMode -> InetAddress.getByAddress(byteArray).hostAddress ipMode && suffixMode -> InetAddress.getByAddress(byteArray.reverseBits()).hostAddress suffixMode && opMode == EngineMode.ENCRYPT -> Base64.getEncoder().encodeToString(byteArray).reversed() suffixMode && opMode == EngineMode.DECRYPT -> String(byteArray).reversed() detail.cipher in GaloisJCE.fpeAlgorithms -> String(byteArray) ((!suffixMode && !ipMode) || detail.cipher in GaloisJCE.symmetricAlgorithms) && opMode == EngineMode.ENCRYPT -> Base64.getEncoder().encodeToString(byteArray) else -> String(byteArray) } } private fun getKeyAndParameters( detail: EncryptionDetail, column: Column<*> ): Pair<SecretKey, AlgorithmParameterSpec?> { val parameterSpec = getParameterSpec(detail, column) val secretKey: SecretKey if (detail.key != null) { secretKey = SecretKeySpec(Base64.getDecoder().decode(detail.key), detail.cipher) } else { val keyGenerator = KeyGenerator.getInstance(detail.cipher) // if it's an opeScheme or HPCBC+ set parameters if (detail.cipher in GaloisJCE.opeAlgorithms + HPCBC_ALGORITHM_NAME) keyGenerator.init(parameterSpec) // set keySize, after the parameters since an algorithm key size may depend on these parameters if (detail.cipher != AICD_ALGORITHM_NAME) detail.params.keySize?.let { keyGenerator.init(it) } secretKey = keyGenerator.generateKey() detail.key = Base64.getEncoder().encodeToString(secretKey.encoded) } return Pair(secretKey, parameterSpec) } private fun getParameterSpec(detail: EncryptionDetail, column: Column<*>): AlgorithmParameterSpec? { val values = column.toMutableList() if (detail.params.taxonomyTree != null) values.addAll(detail.params.taxonomyTree.root.toList()) return when { detail.cipher == AICD_ALGORITHM_NAME && configuration.mode == EngineMode.ENCRYPT -> { val parameterSpec = AICDParameterSpec() parameterSpec.m = (detail.params.cipherSpecific["m"] as? Long ?: values.maxByOrNull { it.toString().toLong() }).toString().toLong() parameterSpec } detail.cipher == FOPE_ALGORITHM_NAME && configuration.mode == EngineMode.ENCRYPT -> { val parameterSpec = FOPEParameterSpec() parameterSpec.d = (detail.params.cipherSpecific["d"] as? Number)?.toByte() ?: ceil(log2(values.maxByOrNull { it.toString().toLong() }.toString().toDouble())).toInt().toByte() parameterSpec.tau = detail.params.cipherSpecific["tau"] as? Int ?: parameterSpec.tau parameterSpec } detail.cipher == PORE_ALGORITHM_NAME && configuration.mode == EngineMode.ENCRYPT -> { val parameterSpec = POREParameterSpec() parameterSpec.n = (detail.params.cipherSpecific["n"] as? Number)?.toByte() ?: ceil(log2(values.maxByOrNull { it.toString().toLong() }.toString().toDouble())).toInt().toByte() parameterSpec.q = (detail.params.cipherSpecific["q"] as? Number)?.toShort() ?: parameterSpec.q parameterSpec } detail.cipher == CRYPTOPAN_ALGORITHM_NAME -> { val ipMode = detail.params.cipherSpecific["ip"] val parameterSpec = CryptoPAnParameterSpec() parameterSpec.maxLength = when (ipMode) { "4" -> 4 "6" -> 16 else -> detail.params.cipherSpecific["max_length"] as? Int ?: values.maxByOrNull { it.toString().length }.toString().length } parameterSpec } detail.cipher == HPCBC_ALGORITHM_NAME -> { val parameterSpec = HPCBCParameterSpec() parameterSpec.integrityCheck = detail.params.cipherSpecific["integrity_check"] as? Boolean ?: false parameterSpec.blockSize = detail.params.cipherSpecific["block_size"] as? Int ?: parameterSpec.blockSize parameterSpec } detail.cipher in GaloisJCE.fpeAlgorithms -> { val parameterSpec: FPEParameterSpec = if (detail.cipher == DFF_ALGORITHM_NAME) DFFParameterSpec() else FF3ParameterSpec() parameterSpec.radix = detail.params.cipherSpecific["radix"] as? Int ?: parameterSpec.radix parameterSpec.tweak = (detail.params.cipherSpecific["tweak"] as? String)?.decodeHex() ?: GaloisJCE.random.generateSeed(parameterSpec.maxTLen).also { detail.params.cipherSpecific["tweak"] = it.toHexString() } parameterSpec } else -> null } } private fun getCipher(detail: EncryptionDetail, secretKey: SecretKey, parameters: AlgorithmParameterSpec?): Cipher { val cipher = Cipher.getInstance(detail.cipher) val opMode = if (configuration.mode == EngineMode.ENCRYPT) Cipher.ENCRYPT_MODE else Cipher.DECRYPT_MODE try { if (detail.cipher in GaloisJCE.opeAlgorithms + GaloisJCE.symmetricAlgorithms) cipher.init(opMode, secretKey) else cipher.init(opMode, secretKey, parameters) } catch (e: InvalidKeyException) { throw InvalidKeyException( """Invalid key for ${detail.columnName}: |${e.localizedMessage}""".trimMargin() ) } return cipher } fun tidyConfiguration(): EngineConfiguration { val clone = configuration.clone() clone.encryptionDetails.forEach { if (configuration.mode == EngineMode.DECRYPT) { it.key = null it.params.keySize = null } when (it.cipher) { in GaloisJCE.opeAlgorithms + GaloisJCE.symmetricAlgorithms -> it.params.cipherSpecific.clear() CRYPTOPAN_ALGORITHM_NAME -> it.params.cipherSpecific.keys.retainAll( listOf("ip", "suffix", "max_length") ) HPCBC_ALGORITHM_NAME -> it.params.cipherSpecific.keys.retainAll(listOf("ip", "suffix", "block_size")) in GaloisJCE.fpeAlgorithms -> it.params.cipherSpecific.keys.retainAll(listOf("radix", "tweak")) } } clone.mode = if (configuration.mode == EngineMode.ENCRYPT) EngineMode.DECRYPT else EngineMode.ENCRYPT return clone } } private fun ByteArray.reverseBits(): ByteArray { val reverse = ByteArray(size) for (j in indices) { for (i in 0..7) { reverse[lastIndex - j] = reverse[lastIndex - j] shl 1 reverse[lastIndex - j] = reverse[lastIndex - j] or (this[j] and 0x1) this[j] = this[j] shr 1 } } return reverse } private infix fun Byte.shl(i: Int) = (this.toInt() shl i and 0xFF).toByte() private infix fun Byte.shr(i: Int) = (this.toInt() shl i and 0xFF).toByte()
0
Kotlin
0
0
dbcb3ae1e9d824f88b361b9dbbad5e3356135db1
14,641
Galois
Apache License 2.0
rest-authentication/src/main/kotlin/com/github/skiedrowski/tools/rest/authentication/server/AuthenticationFeature.kt
skiedrowski
113,460,824
false
null
package com.github.skiedrowski.tools.rest.authentication.server import com.github.skiedrowski.tools.rest.authentication.AuthenticationNotRequired import javax.inject.Inject import javax.ws.rs.container.DynamicFeature import javax.ws.rs.container.ResourceInfo import javax.ws.rs.core.FeatureContext import javax.ws.rs.ext.Provider @Provider class AuthenticationFeature @Inject constructor( private val authenticationProvider: HTTPBasicAuthenticationProvider) : DynamicFeature { override fun configure(resourceInfo: ResourceInfo, context: FeatureContext) { val method = resourceInfo.resourceMethod if (!method.isAnnotationPresent(AuthenticationNotRequired::class.java)) { context.register(AuthenticationFilter(authenticationProvider)) } } }
0
Kotlin
0
0
7919a1dc809fd1fa43ce48fdd72a4e9a88893626
793
rest-tools
MIT License
src/main/kotlin/strategy/behavior/quacking/MuteQuack.kt
Jason-Adam
271,697,189
false
null
package strategy.behavior.quacking class MuteQuack() : QuackBehavior { override fun quack() { println("<<< silence >>>") } }
0
Kotlin
0
0
d0867b814af23648557648e3f56281c90de3b84f
142
kotlin-design-patterns
The Unlicense
klock/src/commonTest/kotlin/com/soywiz/klock/DateRangeTest.kt
AndreasMattsson
204,931,298
true
{"Kotlin": 154563, "Shell": 2318, "Batchfile": 1483}
package com.soywiz.klock import kotlin.test.* class DateRangeTest { val date1 = DateTime(2018, Month.December, 24) val date2 = DateTime(2018, Month.November, 26) val date3 = DateTime(2017, Month.November, 26) val date4 = DateTime(1, Month.November, 26) val christmas = DateTime(2018, Month.December, 25) @Test fun test() { val src = DateTime(2000, Month.January, 10) val dst = DateTime(2000, Month.February, 20) val other = DateTime(2000, Month.February, 1) val outside1 = DateTime(2000, Month.January, 9) val outside2 = DateTime(2000, Month.February, 21) assertTrue(other in (src .. dst)) assertTrue(src in (src .. dst)) assertTrue(dst in (src .. dst)) assertTrue(src in (src until dst)) assertTrue(dst !in (src until dst)) assertTrue(outside1 !in (src .. dst)) assertTrue(outside2 !in (src .. dst)) assertTrue(outside1 !in (src until dst)) assertTrue(outside2 !in (src until dst)) } @Test fun testDaysUntilChristmas() { assertEquals("1D", (date1 until christmas).span.toString()) assertEquals("29D", (date2 until christmas).span.toString(includeWeeks = false)) assertEquals("1Y 29D", (date3 until christmas).span.toString(includeWeeks = false)) assertEquals("2017Y 29D", (date4 until christmas).span.toString(includeWeeks = false)) } @Test fun testDaysUntilChristmasRev() { assertEquals("-1D", (christmas until date1).span.toString()) assertEquals("-29D", (christmas until date2).span.toString(includeWeeks = false)) assertEquals("-1Y -29D", (christmas until date3).span.toString(includeWeeks = false)) assertEquals("-2017Y -29D", (christmas until date4).span.toString(includeWeeks = false)) } }
0
Kotlin
0
0
1ac26e2b0655686240d920f2b9a6eb11fdb184cf
1,840
klock
Apache License 2.0
idbdata/src/main/java/com/gmail/eamosse/idbdata/repository/MovieRepository.kt
DevLoris
242,684,191
true
{"Kotlin": 102230}
package com.gmail.eamosse.idbdata.repository import android.util.Log import com.gmail.eamosse.idbdata.api.response.* import com.gmail.eamosse.idbdata.api.response.toCategory import com.gmail.eamosse.idbdata.api.response.toEntity import com.gmail.eamosse.idbdata.api.response.toToken import com.gmail.eamosse.idbdata.data.* import com.gmail.eamosse.idbdata.datasources.LocalDataSource import com.gmail.eamosse.idbdata.datasources.OnlineDataSource import com.gmail.eamosse.idbdata.extensions.safeCall import com.gmail.eamosse.idbdata.local.entities.FavoriteMovie import com.gmail.eamosse.idbdata.utils.Result import org.koin.core.KoinComponent import org.koin.core.inject /** * La classe permettant de gérer les données de l'application */ class MovieRepository : KoinComponent { //Gestion des sources de données locales private val local: LocalDataSource by inject() //Gestion des sources de données en lignes private val online: OnlineDataSource by inject() /** * Récupérer le token permettant de consommer les ressources sur le serveur * Le résultat du datasource est converti en instance d'objets publiques */ suspend fun getToken(): Result<Token> { return when(val result = online.getToken()) { is Result.Succes -> { //save the response in the local database local.saveToken(result.data.toEntity()) //return the response Result.Succes(result.data.toToken()) } is Result.Error -> result } } suspend fun getCategories(): Result<List<Category>> { return when(val result = online.getCategories()) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val categories = result.data.map { it.toCategory() } Result.Succes(categories) } is Result.Error -> result } } suspend fun getDiscover(id:Int, page:Int = 0): Result<List<Discover>> { return when(val result = online.getDiscover(id, page)) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toDiscover() } Result.Succes(discover) } is Result.Error -> result } } /** * Get a movie by ID * @param int id * @return Result<Movie> */ suspend fun getMovie(id:Int): Result<Movie> { return when(val result = online.getMovie(id)) { is Result.Succes -> { Result.Succes(result.data.toMovie()) } is Result.Error -> result } } /** * Get a movie by ID * @param int id */ suspend fun getSimilarMovies(id:Int): Result<List<SimilarMovie>> { return when(val result = online.getSimilarMovies(id)) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toSimilarMovie() } Result.Succes(discover) } is Result.Error -> result } } /** * Get vdieos of a movie by ID * @param int id */ suspend fun getVideosOfMovie(id:Int): Result<List<VideoMovie>> { return when(val result = online.getVideos(id)) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toVideo() } Result.Succes(discover) } is Result.Error -> result } } /** * Get trending movies */ suspend fun getTrendingMovies(): Result<List<Trending>> { return when(val result = online.getTrendingMovies()) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toTrending() } Result.Succes(discover) } is Result.Error -> result } } /** * Get trending movies */ suspend fun getTrendingPeoples(): Result<List<Person>> { return when(val result = online.getTrendingPeoples()) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toPerson() } Result.Succes(discover) } is Result.Error -> result } } /** * Get trending movies */ suspend fun getSearch(query:String): Result<List<Discover>> { return when(val result = online.getSearch(query)) { is Result.Succes -> { // On utilise la fonction map pour convertir les catégories de la réponse serveur // en liste de categories d'objets de l'application val discover = result.data.map { it.toDiscover() } Result.Succes(discover) } is Result.Error -> result } } /** * Get trending movies */ suspend fun getMovieActors(movieId: Int): Result<List<Actor>> { return when(val result = online.getMovieActor(movieId)) { is Result.Succes -> { val discover = result.data.map { it.toActor() } Result.Succes(discover) } is Result.Error -> result } } /** * Get actor */ suspend fun getActor(id: Int): Result<Actor> { return when(val result = online.getActor(id)) { is Result.Succes -> Result.Succes(result.data.toActor()) is Result.Error -> result } } /** * Get actor movies */ suspend fun getActorMovies(id: Int): Result<List<ActorMovies>> { return when(val result = online.getActorMovies(id)) { is Result.Succes -> { val movies = result.data.map { it.toMovie() } Result.Succes(movies) } is Result.Error -> result } } suspend fun postRating(movie:Int, rating:Float, session:String) { online.postRating(movie, rating, session) } suspend fun getFavoritesMovies() : List<FavoriteMovie> { return local.getFavoritesMovies(); } }
0
Kotlin
0
0
ffde1346853912326f89b47d604c2e3975f052dc
7,290
the-movie-app
Apache License 2.0
app/src/main/java/com/chris/dictionmaster/di/modules/ApiModule.kt
christyansegecs
748,753,751
false
{"Kotlin": 30962}
package com.chris.dictionmaster.di.modules import com.chris.dictionmaster.api.DictionaryAPI import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val apiModule = module { single { provideDictionaryAPI() } } fun provideDictionaryAPI(): DictionaryAPI { return Retrofit.Builder() .baseUrl("https://api.dictionaryapi.dev/") .addConverterFactory(GsonConverterFactory.create()) .build().create(DictionaryAPI::class.java) }
0
Kotlin
0
0
711c2b014a1207519ded447829ed914f92647982
503
DictionMaster
Apache License 2.0
app/src/main/java/ch/abwesend/privatecontacts/view/permission/IPermissionProvider.kt
fgubler
462,182,037
false
{"Kotlin": 1123936, "Java": 369326}
/* * Private Contacts * Copyright (c) 2023. * <NAME> */ package ch.abwesend.privatecontacts.view.permission interface IPermissionProvider { val callPermissionHelper: CallPermissionHelper val contactPermissionHelper: AndroidContactPermissionHelper val callScreeningRoleHelper: CallScreeningRoleHelper } data class PermissionProvider( override val callPermissionHelper: CallPermissionHelper, override val contactPermissionHelper: AndroidContactPermissionHelper, override val callScreeningRoleHelper: CallScreeningRoleHelper, ) : IPermissionProvider
2
Kotlin
1
9
fe855a8b3154186f255435f7f6847b00014bf101
578
PrivateContacts
Apache License 2.0
src/main/kotlin/ui/controller/Controller.kt
hyunjung-choi
848,331,879
false
{"Kotlin": 16748}
package org.sessac.ui.controller import domain.model.MovieInfo import kotlinx.coroutines.runBlocking import org.sessac.domain.usecase.MovieUseCase import org.sessac.ui.InputView import org.sessac.ui.OutputView class Controller( private val inputView: InputView, private val outputView: OutputView, private val movieUseCase: MovieUseCase ) { fun start() = runBlocking { outputView.printCinemaArt() while (true) { outputView.showMenu() when (inputView.chooseMenu()) { "1" -> handleMovieBooking() "2" -> getBookingInfo() "0" -> break else -> outputView.showInvalidInputMessage() } } } private suspend fun handleMovieBooking() { val movieInfos = movieUseCase.getAllMovies() val movieIndex = selectMovie(movieInfos) if (movieIndex == -1) return val movieInfo = movieInfos[movieIndex] val movieManager = movieUseCase.loadMovie(movieInfo) outputView.printSeatArt() movieUseCase.displaySeats(movieManager) val row = inputView.getRowNumber() - 1 val col = inputView.getColumnNumber() - 1 val success = movieUseCase.bookSeat(movieManager, row, col) movieUseCase.displaySeats(movieManager) if (success) { outputView.showBookingSuccess() movieUseCase.saveBookingInfo( MovieInfo(movieInfo.title, movieInfo.emoji, row + 1, col + 1) ) } else outputView.showBookingFailure() } private suspend fun getBookingInfo() { val bookingInfo = movieUseCase.getBookingInfo() outputView.showBookingInfo(bookingInfo) } private fun selectMovie(movieInfos: List<MovieInfo>): Int { outputView.showMovieList(movieInfos.map { it.emoji + it.title }) val choice = inputView.getMovieNumber() - 1 // 사용자 입력을 1부터 시작한다고 가정 return if (choice in movieInfos.indices) choice else -1 } }
0
Kotlin
0
0
23a19f971e4feff9854815817e58cded8c91e1d9
2,016
kotlin-movie-console-app
MIT License
navigator-android/src/main/java/dev/funkymuse/fosho/navigator/android/AndroidBottomSheet.kt
FunkyMuse
713,433,647
false
{"Kotlin": 254630}
package dev.funkymuse.fosho.navigator.android import androidx.compose.foundation.layout.ColumnScope import androidx.compose.runtime.Composable import dev.funkymuse.fosho.navigator.codegen.argument.ArgumentContract import dev.funkymuse.fosho.navigator.codegen.contract.BottomSheet interface AndroidBottomSheet : NavigationDestination, BottomSheet { val argumentsList: List<ArgumentContract> get() = emptyList() @Composable fun ColumnScope.Content() }
0
Kotlin
1
24
21632d154713f7fa35595317589aeabefb563725
473
foSho
Apache License 2.0
library/src/main/java/com/github/pelmenstar1/rangecalendar/Border.kt
pelmenstar1
454,918,220
false
null
package com.github.pelmenstar1.rangecalendar import android.graphics.DashPathEffect import android.graphics.Paint import android.graphics.RectF import androidx.annotation.ColorInt /** * Represents information needed for drawing border around some shape. */ class Border { private var pathEffect: DashPathEffect? = null /** * Stroke width of border */ val width: Float /** * Array with even length of floats specifying "on" and "off" length intervals of dashes */ val dashPathIntervals: FloatArray? /** * An offset into the [dashPathIntervals] array (mod the sum of all of the intervals) */ val dashPathPhase: Float /** * Color of border expressed by color int. * * If border color is initially specified by color long, color is converted to sRGB color space * and it causes additional allocations. */ @get:ColorInt val color: Int /** * Constructs [Border] instance using color specified by color int and stroke width. * * @param color color of the border. * @param width stroke width of the border in pixels. */ constructor(@ColorInt color: Int, width: Float) { this.color = color this.width = width dashPathIntervals = null dashPathPhase = 0f } /** * Constructs [Border] instance with dashed line. * * @param color color of the border. * @param width stroke width of the border. * @param dashPathIntervals array with even length of floats specifying "on" and "off" length intervals of dashes * @param dashPathPhase an offset into the [dashPathIntervals] array (mod the sum of all of the intervals) */ constructor( @ColorInt color: Int, width: Float, dashPathIntervals: FloatArray, dashPathPhase: Float ) { this.color = color this.width = width this.dashPathIntervals = dashPathIntervals this.dashPathPhase = dashPathPhase } /** * Mutates [Paint] instance to apply [Border] to the paint setting its style, stroke width, color, and path effect. */ fun applyToPaint(paint: Paint) { if (pathEffect == null && dashPathIntervals != null) { pathEffect = DashPathEffect(dashPathIntervals, dashPathPhase) } paint.color = color paint.style = Paint.Style.STROKE paint.strokeWidth = width paint.pathEffect = pathEffect } } internal fun RectF.adjustForBorder(strokeWidth: Float) { val half = strokeWidth * 0.5f left += half top += half right -= half bottom -= half } /** * Represents all the supported animation types for border */ enum class BorderAnimationType { /** * Only internal shape of border is animated, stroke width is not. */ ONLY_SHAPE, /** * Only stroke width of border is animated, internal shape is not. */ ONLY_WIDTH, /** * Both internal shape of border and stroke width are animated */ SHAPE_AND_WIDTH }
2
Kotlin
0
11
b67bfeb8783dab29a9939f77159c2ad00d2ce88c
3,063
RangeCalendar
MIT License
src/main/kotlin/me/bzvol/fifimod/item/ModArmorMaterials.kt
bzvol
508,218,419
false
{"Kotlin": 162220}
package me.bzvol.fifimod.item import me.bzvol.fifimod.FifiMod import net.minecraft.sounds.SoundEvent import net.minecraft.sounds.SoundEvents import net.minecraft.world.entity.EquipmentSlot import net.minecraft.world.item.ArmorMaterial import net.minecraft.world.item.crafting.Ingredient enum class ModArmorMaterials( private val materialName: String, private val durabilityMultiplier: Int, private val slotProtections: List<Int>, private val enchantmentValue: Int, private val sound: SoundEvent, private val toughness: Float, private val knockbackResistance: Float, private val repairIngredient: () -> Ingredient ) : ArmorMaterial { BRONZE("bronze", 15, listOf(2, 5, 6, 2), 9, SoundEvents.ARMOR_EQUIP_IRON, 0f, 0f, { Ingredient.of(ModItems.BRONZE_INGOT) }), STEEL("steel", 15, listOf(2, 5, 6, 2), 9, SoundEvents.ARMOR_EQUIP_IRON, 0f, 0f, { Ingredient.of(ModItems.STEEL) }), FIFI("fifi", 45, listOf(3, 6, 8, 3), 30, SoundEvents.ARMOR_EQUIP_NETHERITE, 4f, 0.3f, { Ingredient.of(ModItems.FIFI) }), PIG_IRON("pig_iron", 30, listOf(3, 6, 8, 3), 10, SoundEvents.ARMOR_EQUIP_DIAMOND, 2f, 0f, { Ingredient.of(ModItems.PIG_IRON_INGOT) }); override fun getDurabilityForSlot(pSlot: EquipmentSlot): Int = HEALTH_PER_SLOT[pSlot.index] * this.durabilityMultiplier override fun getDefenseForSlot(pSlot: EquipmentSlot): Int = this.slotProtections[pSlot.index] override fun getEnchantmentValue(): Int = this.enchantmentValue override fun getEquipSound(): SoundEvent = this.sound override fun getRepairIngredient(): Ingredient = this.repairIngredient.invoke() override fun getName(): String = "${FifiMod.MOD_ID}:${this.materialName}" override fun getToughness(): Float = this.toughness override fun getKnockbackResistance(): Float = this.knockbackResistance companion object { val HEALTH_PER_SLOT: List<Int> = listOf(13, 15, 16, 11) } }
0
Kotlin
0
0
95903762a1876342bfeae2b11c272f71d97621a3
1,974
FifiMod
MIT License
compiler/src/main/kotlin/pers/shawxingkwok/phone/server/KSFun.getServerRouteContent.kt
ShawxingKwok
702,423,277
false
{"Kotlin": 122297}
package pers.shawxingkwok.phone.server import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import pers.shawxingkwok.ksputil.CodeFormatter import pers.shawxingkwok.ksputil.resolver import pers.shawxingkwok.ksputil.simpleName import pers.shawxingkwok.ktutil.fastLazy import pers.shawxingkwok.phone.* import pers.shawxingkwok.phone.Kind import pers.shawxingkwok.phone.getMethodInfo import pers.shawxingkwok.phone.kind import pers.shawxingkwok.phone.pathEnd import pers.shawxingkwok.phone.server.parts.getServerParametersPart context (CodeFormatter) internal fun KSFunctionDeclaration.getServerRouteContent(ksclass: KSClassDeclaration): String { val retType = when(val kind = kind){ is Kind.WebSocket -> return getServerWebSocketContent(ksclass, kind) is Kind.Manual -> kind.tagType is Kind.Common -> kind.returnType is Kind.PartialContent -> kind.tagType } val (methodName, withForm) = getMethodInfo(ksclass) val start = methodName.replaceFirstChar { it.lowercase() } return buildString { """ $start("/$pathEnd"){ """.trimStart() .let(::append) when{ parameters.none() -> {} withForm -> append("val params = call.${Decls().receiveParameters}()\n\n") else -> append("val params = call.request.queryParameters\n\n") } val invokePart = buildString { append("${ksclass.apiPropNameInPhone}.${simpleName()}(") append(getServerParametersPart(ksclass, start)) append(")()") } @Suppress("LocalVariableName") val `val text = encode~~` by fastLazy { "val text = encode(ret, ${retType.getSerializerText()}, ${getCipherTextForReturn(ksclass)})" } val isUnit = retType == resolver.builtIns.unitType if (kind is Kind.Common) when{ isUnit -> """ $invokePart call.response.status(HttpStatusCode.OK) """ retType.isMarkedNullable -> """ val ret = $invokePart if (ret == null) ~call.response.status(HttpStatusCode.NoContent)!~ else{ $`val text = encode~~` call.respondText(text) call.response.status(HttpStatusCode.OK) } """ else -> """ val ret = $invokePart $`val text = encode~~` call.respondText(text) call.response.status(HttpStatusCode.OK) """ } .trimStart().let(::append) else { when{ kind is Kind.PartialContent -> append("val (ret, file) = $invokePart\n\n") // Manual isUnit -> append("$invokePart\n\n") else -> append("val ret = $invokePart\n\n") } when{ isUnit -> {} retType.isMarkedNullable -> { """ if (ret != null){ $`val text = encode~~` call.response.header("Phone-Tag", text) } """.trimStart() .let(::append) } else -> """ $`val text = encode~~` call.response.header("Phone-Tag", text) """.trimStart() .let(::append) } if (kind is Kind.PartialContent) { append("call.response.status(HttpStatusCode.OK)\n") append("call.respondFile(file)\n") }else // Manual append("call.response.status(HttpStatusCode.OK)\n") } append("}") } }
0
Kotlin
0
0
402c4c6c351bb743736a6fb50724a177be6dc95e
4,282
Phone
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/incentivesapi/service/NearestPrisonIncentiveLevelServiceTest.kt
ministryofjustice
445,553,088
false
null
package uk.gov.justice.digital.hmpps.incentivesapi.service import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import uk.gov.justice.digital.hmpps.incentivesapi.config.DataIntegrityException import uk.gov.justice.digital.hmpps.incentivesapi.dto.IncentiveLevel class NearestPrisonIncentiveLevelServiceTest { private val incentiveLevelService: IncentiveLevelAuditedService = mock() private val prisonIncentiveLevelService: PrisonIncentiveLevelAuditedService = mock() private val nearestPrisonIncentiveLevelService = NearestPrisonIncentiveLevelService(incentiveLevelService, prisonIncentiveLevelService) @Nested inner class `finding nearest levels` { private val prisonId = "MDI" @BeforeEach fun setup(): Unit = runBlocking { whenever(incentiveLevelService.getAllIncentiveLevels()).thenReturn( listOf( IncentiveLevel(code = "BAS", name = "Basic"), IncentiveLevel(code = "ENT", name = "Entry", active = false), IncentiveLevel(code = "STD", name = "Standard"), IncentiveLevel(code = "ENH", name = "Enhanced"), IncentiveLevel(code = "EN2", name = "Enhanced 2"), IncentiveLevel(code = "EN3", name = "Enhanced 3"), ), ) } @Test fun `when target level is available`(): Unit = runBlocking { // the case for most transfers (most prisons use the same set of levels) whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), ), ) for (level in listOf("BAS", "STD", "ENH")) { assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, level)).isEqualTo(level) } } @Test fun `when target level is not present, nor is there a higher one`(): Unit = runBlocking { // can happen when transferring from a prison that has high levels to a typical prison whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "EN2")).isEqualTo("ENH") } @Test fun `when target and many other high levels are unavailable`(): Unit = runBlocking { // exaggerated version of transferring from a prison that has high levels to another prison whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS", defaultOnAdmission = true, active = true), prisonIncentiveLevel(prisonId, "ENT", active = true), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = false), prisonIncentiveLevel(prisonId, "ENH", active = false), prisonIncentiveLevel(prisonId, "EN2", active = false), prisonIncentiveLevel(prisonId, "EN3", active = false), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "EN3")).isEqualTo("BAS") } @Test fun `when target level is not present, but there is a higher one higher`(): Unit = runBlocking { // not likely to happen, but covers case where a prison may have mistakenly removed a level whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), prisonIncentiveLevel(prisonId, "EN3"), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "EN2")).isEqualTo("EN3") } @Test fun `when target and many other low levels are unavailable`(): Unit = runBlocking { // exaggerated version of prisons with predominantly high levels whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS", active = false), prisonIncentiveLevel(prisonId, "ENT"), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = false), prisonIncentiveLevel(prisonId, "ENH", active = false), prisonIncentiveLevel(prisonId, "EN2"), prisonIncentiveLevel(prisonId, "EN3", defaultOnAdmission = true), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "BAS")).isEqualTo("EN2") } @Test fun `when target level is present but inactive`(): Unit = runBlocking { // can happen when a prison disables a high level whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), prisonIncentiveLevel(prisonId, "EN2", active = false), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "EN2")).isEqualTo("ENH") } @Test fun `when target level is globally inactive`(): Unit = runBlocking { // unlikely to happen, but feasible if a prisoner has not had a review in a long time whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "ENT")).isEqualTo("STD") } @Test fun `falls back to the prison's default when target is not found`(): Unit = runBlocking { // extreme edge case when a level is globally removed whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), // default & active prisonIncentiveLevel(prisonId, "STD"), prisonIncentiveLevel(prisonId, "ENH"), ), ) assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "ABC")).isEqualTo("STD") } @Test fun `fails when target is not found and there is no default`(): Unit = runBlocking { // extreme edge case when a level is globally removed AND the prison does not have a default set but standard is available whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = true), prisonIncentiveLevel(prisonId, "ENH"), ), ) assertThatThrownBy { runBlocking { assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "ABC")) } }.isInstanceOf(DataIntegrityException::class.java) } @Test fun `fails when target is not found and there is no default or standard`(): Unit = runBlocking { // extreme edge case when a level is globally removed AND the prison does not have a default set AND standard is unavailable whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS"), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = false), prisonIncentiveLevel(prisonId, "ENH"), ), ) assertThatThrownBy { runBlocking { assertThat(nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "ABC")) } }.isInstanceOf(DataIntegrityException::class.java) } @Test fun `fails when a prison does not have any available levels`(): Unit = runBlocking { // extreme edge case when the prison does not have any levels whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS", active = false), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = false), prisonIncentiveLevel(prisonId, "ENH", active = false), ), ) assertThatThrownBy { runBlocking { nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "STD") } }.isInstanceOf(DataIntegrityException::class.java) } @Test fun `fails when there are no available levels in a prison because a default cannot be chosen`(): Unit = runBlocking { // extreme edge case when a level is globally removed AND the prison does not have any levels whenever(prisonIncentiveLevelService.getActivePrisonIncentiveLevels(prisonId)).thenReturn( listOf( prisonIncentiveLevel(prisonId, "BAS", active = false), prisonIncentiveLevel(prisonId, "STD", defaultOnAdmission = false, active = false), prisonIncentiveLevel(prisonId, "ENH", active = false), ), ) assertThatThrownBy { runBlocking { nearestPrisonIncentiveLevelService.findNearestHighestLevel(prisonId, "ABC") } }.isInstanceOf(DataIntegrityException::class.java) } } }
4
null
1
3
5e0385eb256f64623f521a70acfa3166bcbfb82f
10,016
hmpps-incentives-api
MIT License
src/test/kotlin/com/kalikov/game/TankStateNormalTest.kt
kalikov
696,277,791
false
{"Kotlin": 423521}
package com.kalikov.game import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import kotlin.test.assertTrue class TankStateNormalTest { private lateinit var game: Game private lateinit var pauseManager: PauseManager private lateinit var tank: Tank private lateinit var state: TankStateNormal @BeforeEach fun beforeEach() { game = mockGame(clock = TestClock()) pauseManager = mock() tank = mockPlayerTank(game, pauseManager) state = TankStateNormal(game.imageManager, tank) tank.state = state } @Test fun `should allow movement`() { assertTrue(state.canMove) } @Test fun `should allow shooting`() { assertTrue(state.canShoot) } }
0
Kotlin
0
0
71e178ea0b7746998808cbc602cd30b5f5a2bf1c
793
battle-city
MIT License
src/main/kotlin/no/nav/arbeidsplassen/importapi/MicronautConfig.kt
navikt
236,483,368
false
null
package no.nav.arbeidsplassen.importapi import io.micronaut.context.annotation.Factory import no.nav.pam.yrkeskategorimapper.StyrkCodeConverter import jakarta.inject.Singleton @Factory class MicronautConfig { @Singleton fun styrkCodeConverter(): StyrkCodeConverter { return StyrkCodeConverter() } }
0
Kotlin
0
4
de2f1f01409d7ce02129f68709b21cf609f3426f
324
pam-import-api
MIT License
src/main/kotlin/eu/wojciechzurek/mattermost/attendancebot/events/commands/CommandSubscriber.kt
wojciech-zurek
251,014,723
false
null
package eu.wojciechzurek.mattermost.attendancebot.events.commands import eu.wojciechzurek.mattermost.attendancebot.ConfigReloadedEvent import eu.wojciechzurek.mattermost.attendancebot.api.mattermost.Event import eu.wojciechzurek.mattermost.attendancebot.api.mattermost.Post import eu.wojciechzurek.mattermost.attendancebot.events.CommandType import eu.wojciechzurek.mattermost.attendancebot.events.PostedEventSubscriber import eu.wojciechzurek.mattermost.attendancebot.loggerFor import eu.wojciechzurek.mattermost.attendancebot.services.ConfigService import eu.wojciechzurek.mattermost.attendancebot.services.MattermostService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.ApplicationListener import org.springframework.context.MessageSource abstract class CommandSubscriber : PostedEventSubscriber(), ApplicationListener<ApplicationReadyEvent> { private val logger = loggerFor(this.javaClass) @Autowired protected lateinit var mattermostService: MattermostService @Autowired protected lateinit var configService: ConfigService @Autowired protected lateinit var messageSource: MessageSource private val prefix = ".prefix" abstract fun getName(): String abstract fun getHelp(): String abstract fun getCommandType(): CommandType abstract fun onEvent(event: Event, message: String) private fun getPrefix(): String = getName() + prefix override fun onApplicationEvent(event: ApplicationReadyEvent) { botService.setCommand(getCommandType(), getPrefix()) botService.setHelp(getPrefix(), getHelp()) } override fun filter(event: Event): Boolean { return (event.data.post?.message?.trimStart()?.startsWith(configService.get(getPrefix())) ?: false) && super.filter(event) } override fun onEvent(event: Event) { logger.info("Command: {}", getName()) onEvent(event, event.data.post?.message?.removePrefix(configService.get(getPrefix()))?.trim()!!) } override fun onError(event: Event, e: Exception) { val post = Post( // userId = it.data.post!!.userId, channelId = event.data.post?.channelId!!, message = "${event.data.senderName}\n" + "command error!\n" + "exception:\n" + "```\n" + "${e.message}!\n" + "```\n" + "usage: ${configService.get(getPrefix()) + " " + getHelp()}" ) mattermostService.post(post) } }
0
Kotlin
0
0
5dabc91deffcfa3ac0d0bc2f915f6b62061a4b0b
2,690
mattermost-attendance-bot
MIT License
src/main/kotlin/dev/schlaubi/musicbot/module/music/playlist/commands/RemoveCommand.kt
Korsti
414,297,572
true
{"Kotlin": 265776, "Dockerfile": 199, "Shell": 97}
package dev.schlaubi.musicbot.module.music.playlist.commands import com.kotlindiscord.kord.extensions.commands.converters.impl.int import com.kotlindiscord.kord.extensions.types.respond import dev.schlaubi.musicbot.utils.database import dev.schlaubi.musicbot.utils.format class PlaylistRemoveArguments : PlaylistArguments() { val index by int("index", "The index of the track to remove") } fun PlaylistModule.removeCommand() = ephemeralSubCommand(::PlaylistRemoveArguments) { name = "remove" description = "Removes a Track from the playlist" action { checkPermissions { playlist -> val index = arguments.index - 1 val item = playlist.songs.getOrNull(index) if (item == null) { respond { content = translate("commands.playlist.remove.too_high_index") } return@action } database.playlists.save( playlist.copy( songs = playlist.songs.toMutableList().apply { removeAt(index) // this might be a dupe, so we remove by index } ) ) respond { content = translate("commands.playlist.remove.removed", arrayOf(item.format(), playlist.name)) } } } }
0
null
0
0
488ac29bf58aac7aa30a41de296e5a908524b492
1,356
mikmusic
MIT License
app/src/main/java/com/haoyh/luckynumberview/lucknumber/LuckyNumberView.kt
haoyh
284,584,215
false
null
package com.haoyh.luckynumberview.lucknumber import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View import android.view.animation.LinearInterpolator import com.haoyh.luckynumberview.R import kotlin.math.absoluteValue /** * @FileName: LuckNumberView * @Description: happy hash 选择数字及显示加载中奖号码动画 view * @Author: haoyanhui * @Date: 2020-07-24 16:42 */ class LuckyNumberView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val TAG = "hyh" companion object { const val strokeResId = R.mipmap.bg_animator val defNumResId = arrayOf( R.mipmap.bg_hphash_zero_def, R.mipmap.bg_hphash_one_def, R.mipmap.bg_hphash_two_def, R.mipmap.bg_hphash_three_def, R.mipmap.bg_hphash_four_def, R.mipmap.bg_hphash_five_def, R.mipmap.bg_hphash_six_def, R.mipmap.bg_hphash_seven_def, R.mipmap.bg_hphash_eight_def, R.mipmap.bg_hphash_nine_def ) val checkedNumResId = arrayOf( R.mipmap.bg_hphash_zero_checked, R.mipmap.bg_hphash_one_checked, R.mipmap.bg_hphash_two_checked, R.mipmap.bg_hphash_three_checked, R.mipmap.bg_hphash_four_checked, R.mipmap.bg_hphash_five_checked, R.mipmap.bg_hphash_six_checked, R.mipmap.bg_hphash_seven_checked, R.mipmap.bg_hphash_eight_checked, R.mipmap.bg_hphash_nine_checked ) val SECOND = 1000L } // item 点击事件接口 interface OnItemClickListener { fun onItemClick(index: String) } // 显示中奖结果动画结束事件接口 interface OnLuckNumberAnimationEndListener { fun onLuckNumberAnimationEnd() } private var mOnItemClickListener: OnItemClickListener? = null fun setOnItemClickListener(listener: OnItemClickListener) { this.mOnItemClickListener = listener } private var mOnLuckNumberAnimationEndListener: OnLuckNumberAnimationEndListener? = null fun setOnLuckNumberAnimationEndListener(listener: OnLuckNumberAnimationEndListener) { this.mOnLuckNumberAnimationEndListener = listener } // 存放数字 bitmap private var mDefBitmapList: MutableList<Bitmap> private var mCheckedBitmapList: MutableList<Bitmap> // 动画 bitmap private var mStorkBitmap: Bitmap // 画笔 private var mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) // 每行的个数 private val mRowCount = 5 // 预留安全距离 private var mSafeMargin = 5f // 水平边距,最左/最右 需要除以 2 private var marginL = 5f // 垂直边距,最上/最下 需要除以 2 private var marginT = 5f // 存储矩形的集合 private var mNumberRects: MutableList<RectF> // 矩形的宽和高 private var mRectW = 52f private var mRectH = 55f // 按下时点击的 item 项,确保一次点击是在同一个按钮上 private var mLastClickIndex = "" // 动画类型 var mAnimatorMode = AnimatorMode.MODE_TRANSLATION // 动画相关 // JUMP 类型时 private var mLuckSpinJumpLoadingAnimator: ValueAnimator? = null // 有中奖结果之后的动画 private var mLuckSpinJumpResultAnimator: ValueAnimator? = null // 移动的index private var mCurrentMoveIndex = -1 // TRANSLATION 类型时 private var mLuckSpinTranslateLoadingAnimatorSet: AnimatorSet? = null // 移动图片隐藏 rectF private val mHiddenRectF = RectF(0f, 0f, 0f, 0f) private val mHiddenRect = Rect(0, 0, 0, 0) // 当前移动的坐标 private var mCurrentRectF: RectF? = null // 当前选中的 数字 var mChoosedItemList: MutableList<String> = mutableListOf() set(value) { field = value invalidate() } // 开始动画 var startAnimation: Boolean = false set(value) { field = value if (value) { startMoveAnimation() } } // 中奖码 var mLuckNumber: String = "" set(value) { field = value stopMoveAnimation() } // 隐藏滑块 var mHiddenAnimatorView: Boolean = false set(value) { field = value if (value) { hiddenAnimatorView() } } init { mNumberRects = mutableListOf() // 初始化图片相关信息 mStorkBitmap = BitmapFactory.decodeResource(resources, strokeResId) mDefBitmapList = mutableListOf() defNumResId.forEach { mDefBitmapList.add(BitmapFactory.decodeResource(resources, it)) } mCheckedBitmapList = mutableListOf() checkedNumResId.forEach { mCheckedBitmapList.add(BitmapFactory.decodeResource(resources, it)) } mRectW = dp2px(mRectW) mRectH = dp2px(mRectH) mSafeMargin = dp2px(mSafeMargin) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // 计算水平、垂直边距 marginL = (w.toFloat() - (mRowCount * mRectW) - mSafeMargin * 2) / mRowCount.toFloat() marginT = (h.toFloat() - (2f * mRectH) - mSafeMargin * 2) / 2f mNumberRects.clear() initRect() } // 画矩形 private fun initRect() { var l: Float var t: Float var r: Float var b: Float var rectf: RectF? // 第一行 for (i in 0 until mRowCount) { l = i * mRectW + marginL * i + marginL / 2 + mSafeMargin t = marginT / 2 + mSafeMargin r = i * mRectW + marginL * i + marginL / 2 + mRectW + mSafeMargin b = mRectH + marginT / 2 + mSafeMargin rectf = RectF(l, t, r, b) mNumberRects.add(rectf) } // 第二行 for (i in 0 until mRowCount) { l = i * mRectW + marginL * i + marginL / 2 + mSafeMargin t = mRectH + marginT + mSafeMargin r = i * mRectW + marginL * i + marginL / 2 + mRectW + mSafeMargin b = mRectH * 2 + marginT / 2 + marginT + mSafeMargin rectf = RectF(l, t, r, b) mNumberRects.add(rectf) } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas?.let { // 画数字 drawNumberRects(it) // 画移动图片 drawMoveImage(it) } } // 画 9 个数字 private fun drawNumberRects(canvas: Canvas) { mNumberRects.forEachIndexed { index, rectF -> if (mChoosedItemList.contains(index.toString())) { canvas.drawBitmap(mCheckedBitmapList[index], rectF.left, rectF.top, mPaint) } else { canvas.drawBitmap(mDefBitmapList[index], rectF.left, rectF.top, mPaint) } } } // 画动画时平移的 bitmap private fun drawMoveImage(canvas: Canvas) { if (mAnimatorMode == AnimatorMode.MODE_JUMP) { if (mCurrentMoveIndex in 0..mNumberRects.size) { // 平移bitmap 同 数字bitmap 不同,所以需要重新计算坐标 val left = mNumberRects[mCurrentMoveIndex].left - (mRectW - mStorkBitmap.width).absoluteValue.div(2) val top = mNumberRects[mCurrentMoveIndex].top - (mRectH - mStorkBitmap.height).absoluteValue.div(2) canvas.drawBitmap(mStorkBitmap, left, top, mPaint) } } else if (mAnimatorMode == AnimatorMode.MODE_TRANSLATION) { mCurrentRectF?.let { if (it != mHiddenRectF) { val left = it.left - (mRectW - mStorkBitmap.width).absoluteValue.div(2) val top = it.top - (mRectH - mStorkBitmap.height).absoluteValue.div(2) canvas.drawBitmap(mStorkBitmap, left, top, mPaint) } else { // 使移动图片不可见 canvas.drawBitmap(mStorkBitmap, Rect(it.left.toInt(), it.top.toInt(), it.right.toInt(), it.bottom.toInt()), mHiddenRect, mPaint) } } } } override fun onTouchEvent(event: MotionEvent?): Boolean { event?.let { if (it.action == MotionEvent.ACTION_DOWN) { mNumberRects.forEachIndexed { index, rectF -> if (rectF.contains(event.x, event.y)) { // 点击了某个按钮,返回 index mLastClickIndex = index.toString() Log.d(TAG, "down 点击了 $index") return true } } return true } if (it.action == MotionEvent.ACTION_UP) { mNumberRects.forEachIndexed { index, rectF -> if (rectF.contains(event.x, event.y)) { // 点击了某个按钮,返回 index Log.d(TAG, "up 点击了 $index") if (mLastClickIndex == index.toString()) { // 点击监听回调 mOnItemClickListener?.onItemClick(mLastClickIndex) } return true } } } } return super.onTouchEvent(event) } // 开始平移动画 private fun startMoveAnimation() { if (mAnimatorMode == AnimatorMode.MODE_JUMP) { mLuckSpinJumpLoadingAnimator = ValueAnimator.ofInt(0, mNumberRects.size).apply { setInterpolatorAndDuration() repeatCount = ValueAnimator.INFINITE addUpdateListener { val i: Int = (it.animatedValue) as Int mCurrentMoveIndex = i % mNumberRects.size invalidate() } start() } } else if (mAnimatorMode == AnimatorMode.MODE_TRANSLATION) { // 平移动画相当于画两条平行线,第一条线的起点、终点坐标对应 0、4 的坐标,第二条线的起点、终点坐标对应 5、9 的坐标 // 从左到右的移动 第一条线 val topLine = ValueAnimator.ofObject(RectFEvaluator(), mNumberRects[0], mNumberRects[4]).apply { setInterpolatorAndDuration() addUpdateListener { mCurrentRectF = it.animatedValue as RectF invalidate() } } // 从左到右的移动 第二条线 val bottomLine = ValueAnimator.ofObject(RectFEvaluator(), mNumberRects[5], mNumberRects[9]) .apply { setInterpolatorAndDuration() addUpdateListener { mCurrentRectF = it.animatedValue as RectF invalidate() } } mLuckSpinTranslateLoadingAnimatorSet = AnimatorSet().apply { play(topLine).before(bottomLine) addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { // 实现重复执行该动画 start() } }) start() } } } // 暂停平移动画,并开启结果锁定中奖码的动画 private fun stopMoveAnimation() { // 开始最后一轮动画,动画结束选中中奖数字 if (mAnimatorMode == AnimatorMode.MODE_JUMP) { if (mLuckNumber.isEmpty()) { mLuckSpinJumpLoadingAnimator?.cancel() mOnLuckNumberAnimationEndListener?.onLuckNumberAnimationEnd() } else { mLuckSpinJumpResultAnimator = ValueAnimator.ofInt(mCurrentMoveIndex, mLuckNumber.toInt() + mNumberRects.size) .apply { setInterpolatorAndDuration() removeAllUpdateListeners() addUpdateListener { val i: Int = (it.animatedValue) as Int mCurrentMoveIndex = i % mNumberRects.size invalidate() } addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { super.onAnimationStart(animation) mLuckSpinJumpLoadingAnimator?.cancel() } override fun onAnimationEnd(animation: Animator?) { super.onAnimationEnd(animation) mOnLuckNumberAnimationEndListener?.onLuckNumberAnimationEnd() } }) start() } } } else if (mAnimatorMode == AnimatorMode.MODE_TRANSLATION) { // 根据当前位置画到指定暂停的位置 if (mLuckNumber.isEmpty()) { mLuckSpinTranslateLoadingAnimatorSet?.pause() mLuckSpinTranslateLoadingAnimatorSet?.removeAllListeners() mOnLuckNumberAnimationEndListener?.onLuckNumberAnimationEnd() hiddenAnimatorView() } else { // 继续画线 // 起点是 mCurrentRectF 的坐标 // 终点就是中奖码对应的坐标 val endRectF = mNumberRects[mLuckNumber.toInt()] // 需要判断起点、终点位于哪儿条(第一/二)条线上 // 仍然是画线,动画不需要重复 mCurrentRectF?.let { currentRectF -> // 第一条线的坐标,通过数字0同数字4的坐标可以得到 val topLineRectF = RectF(mNumberRects[0].left, mNumberRects[0].top, mNumberRects[4].right, mNumberRects[0].bottom) // 第一条线的坐标,通过数字5同数字9的坐标可以得到 val bottomLineRectF = RectF(mNumberRects[5].left, mNumberRects[5].top, mNumberRects[9].right, mNumberRects[5].bottom) val fullLine = mNumberRects[4].left - mNumberRects[0].left var startInTop = false var endInTop = false if (topLineRectF.contains(currentRectF)) { Log.d(TAG, "起点在 topLine") startInTop = true } if (bottomLineRectF.contains(currentRectF)) { Log.d(TAG, "起点在 bottomLine") startInTop = false } if (topLineRectF.contains(endRectF)) { Log.d(TAG, "终点在 topLine") endInTop = true } if (bottomLineRectF.contains(endRectF)) { Log.d(TAG, "终点在 bottomLine") endInTop = false } // 第一条线的坐标:起点(mCurrentRectF) 到所在线的终点值 val topLineEnd: RectF topLineEnd = if (startInTop) { mNumberRects[4] } else { mNumberRects[9] } val topLineAnimator = ValueAnimator.ofObject(RectFEvaluator(), currentRectF, topLineEnd).apply { interpolator = LinearInterpolator() // 计算时间,起点到终点的距离占完整线的比例 * SECOND duration = ((topLineEnd.left - currentRectF.left).div(fullLine) * SECOND).toLong() addUpdateListener { mCurrentRectF = it.animatedValue as RectF invalidate() } } // 第二条线(只有当起点、终点在同一条线上时才需要添加) var middleLineAnimator: ValueAnimator? = null var middleLineStart: RectF? = null var middleLineEnd: RectF? = null if (startInTop && endInTop) { middleLineStart = mNumberRects[5] middleLineEnd = mNumberRects[9] } if (!startInTop && !endInTop) { middleLineStart = mNumberRects[0] middleLineEnd = mNumberRects[4] } middleLineStart?.let { start -> middleLineEnd?.let { end -> middleLineAnimator = ValueAnimator.ofObject(RectFEvaluator(), start, end).apply { setInterpolatorAndDuration() addUpdateListener { mCurrentRectF = it.animatedValue as RectF invalidate() } } Log.d(TAG, "需要画中间线") } } // 第三条线的坐标:所在线的起点值到 终点(中奖码对应的坐标) val bottomLineStart: RectF bottomLineStart = if (endInTop) { mNumberRects[0] } else { mNumberRects[5] } val bottomLineAnimator = ValueAnimator.ofObject(RectFEvaluator(), bottomLineStart, endRectF) .apply { interpolator = LinearInterpolator() // 计算时间,起点到终点的距离占完整线的比例 * SECOND duration = ((endRectF.left - bottomLineStart.left).div(fullLine) * SECOND).toLong() addUpdateListener { mCurrentRectF = it.animatedValue as RectF invalidate() } } AnimatorSet().apply { topLineAnimator?.let { if (null != middleLineAnimator) { play(middleLineAnimator).after(topLineAnimator).before(bottomLineAnimator) } else { play(topLineAnimator).before(bottomLineAnimator) } } addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { // 结束加载时动画 mLuckSpinTranslateLoadingAnimatorSet?.pause() } override fun onAnimationEnd(animation: Animator?) { // 通知页面动画结束 mOnLuckNumberAnimationEndListener?.onLuckNumberAnimationEnd() } }) start() } } } } } // 设置动画差值器和动画时长 private fun ValueAnimator?.setInterpolatorAndDuration() { this?.let { interpolator = LinearInterpolator() duration = SECOND } } // 隐藏动画滑块 private fun hiddenAnimatorView() { mCurrentRectF = mHiddenRectF invalidate() } fun onDestroy() { mLuckSpinJumpLoadingAnimator?.cancel() mLuckSpinJumpResultAnimator?.cancel() } private fun dp2px(dp: Float): Float { return (resources.displayMetrics.density * dp + 0.5).toFloat() } }
0
Kotlin
0
1
0f0c2aa38974ce02068767318a9db36909ec9873
19,250
LuckyNumberView
Apache License 2.0
projects/soc-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/controller/DetailController.kt
ministryofjustice
500,855,647
false
{"Kotlin": 3073554, "HTML": 50359, "D2": 27334, "Ruby": 22218, "Shell": 12351, "SCSS": 5460, "JavaScript": 2970, "HCL": 2708, "Dockerfile": 2102}
package uk.gov.justice.digital.hmpps.controller import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.service.DetailService @RestController class DetailController(private val detailService: DetailService) { @PreAuthorize("hasAnyRole('ROLE_SOC_PROBATION_CASE','PROBATION_API__SOC__CASE_DETAIL')") @GetMapping(value = ["/detail/{value}"]) fun convictions( @PathVariable value: String, @RequestParam(required = false, defaultValue = "CRN") type: IdentifierType ) = detailService.getDetails(value, type) }
6
Kotlin
0
2
fb5efdbdedcdc6e88c25c529af94ebaeba419c7f
822
hmpps-probation-integration-services
MIT License
src/main/kotlin/th/nstda/thongkum/tele_api/config/Config.kt
lionants02
578,446,115
false
{"Kotlin": 12303, "Batchfile": 207, "Dockerfile": 174}
package th.nstda.thongkum.tele_api.config interface Config { val openviduDefaultUrl: String val openviduDefaultSecret: String val hikariConfigFile: String val apiKey: String } /** * Application config */ val config: Config by lazy { ConfigWithSystemEnv() }
0
Kotlin
0
0
5ea65230659143a2bce07037c8d5c8c9ff862b18
276
tele_api_ktor_template
Apache License 2.0
shared/presentation/src/commonMain/kotlin/com/moonlightbutterfly/rigplay/gamedetails/controller/GameDetailsController.kt
Dragoonov
653,808,838
false
null
package com.moonlightbutterfly.rigplay.gamedetails.controller import com.arkivanov.essenty.lifecycle.Lifecycle import com.arkivanov.essenty.lifecycle.doOnDestroy import com.arkivanov.mvikotlin.core.binder.BinderLifecycleMode import com.arkivanov.mvikotlin.extensions.coroutines.bind import com.arkivanov.mvikotlin.extensions.coroutines.events import com.arkivanov.mvikotlin.extensions.coroutines.states import com.moonlightbutterfly.rigplay.dispatchers.Dispatchers import com.moonlightbutterfly.rigplay.gamedetails.eventToIntent import com.moonlightbutterfly.rigplay.gamedetails.stateToModel import com.moonlightbutterfly.rigplay.gamedetails.store.GameDetailsStore import com.moonlightbutterfly.rigplay.gamedetails.view.GameDetailsView import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull internal class GameDetailsController( lifecycle: Lifecycle, private val store: GameDetailsStore, private val dispatchers: Dispatchers, ) { init { lifecycle.doOnDestroy(store::dispose) } fun onViewCreated(view: GameDetailsView, viewLifecycle: Lifecycle) { bind(viewLifecycle, BinderLifecycleMode.START_STOP, dispatchers.unconfined) { view.events.mapNotNull(eventToIntent) bindTo store store.states.map(stateToModel) bindTo view } } }
0
Kotlin
0
0
c8a45a5db1fbe73f1801b67dbdd0b70a1757b380
1,325
RigPlay
Apache License 2.0
backend/src/test/kotlin/com/mobilispect/backend/data/agency/OneStopAgencyIDTest.kt
alandovskis
502,662,711
false
{"Kotlin": 358753, "Shell": 472, "Swift": 345}
package com.mobilispect.backend.data.agency import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class OneStopAgencyIDTest { @Test fun agencyNotCreatedIfIDMissingGeoHash() { assertThrows<IllegalArgumentException> { OneStopAgencyID("o--a") } } @Test fun agencyNotCreatedIfIDMissingName() { assertThrows<IllegalArgumentException> { OneStopAgencyID("o-a-") } } @Test fun idIsAcceptedIfHasGeohashAndName() { OneStopAgencyID("o-a-b") } @Test fun idIsAcceptedIfMissingGeohashButHasName() { OneStopAgencyID("o-orleans~express~ca") } }
2
Kotlin
0
1
7b48fafb75d432509e71107d501b6c7e2563bd00
685
mobilispect
Apache License 2.0
common/src/main/java/io/github/pelmenstar1/digiDict/common/binarySerialization/PrimitiveValueWriter.kt
pelmenstar1
512,710,767
false
null
package io.github.pelmenstar1.digiDict.common.binarySerialization import io.github.pelmenstar1.digiDict.common.* import java.io.OutputStream import java.nio.* import kotlin.math.min /** * Provides means for writing primitive types (like [Int], [Long], [String]) to [OutputStream]. * The byte order can't be changed and is always little-endian. * * The class provides emit-like methods that write a value and move the cursor forward for the amount of bytes that was written. * Because of its stream nature, there's no going back and the cursor can't be moved forward or backward. * * The writer is already buffered, thus a reasonable buffer size should be specified in constructor. * There are several limitations imposed on buffer size: * - It should be greater than or equals to 8. * - It should be even. */ class PrimitiveValueWriter(private val output: OutputStream, bufferSize: Int) { private val byteBufferArray = ByteArray(bufferSize) private var byteBuffer: ByteBuffer? = null // A CharBuffer which can effectively write chars to byteBufferArray private var byteBufferAsCharHolder: CharBuffer? = null // A IntBuffer which can effectively write ints to byteBufferArray private var byteBufferAsIntHolder: IntBuffer? = null private var byteBufferAsIntOffset = 0 // A cached reference to the char array which is used in emit(String) to write a char data to it and write the array to the stream. // There's a temporary step with the char array because CharBuffer (when mapped from ByteBuffer) // provides optimized way for writing CharArray but not String. // // The size of the array is only extended when a string with bigger length than the array's one is requested. // Outside the emit(String) method, the array's content should be considered as garbage. private var charBuffer: CharArray? = null // Stores a current position in byteBufferArray from which writing the data should start. // It can't equal to byteBufferArray.size and should be even. private var bufferPos = 0 init { when { bufferSize < 8 -> throw IllegalArgumentException("bufferSize should be greater than or equals to 8") bufferSize % 2 != 0 -> throw IllegalArgumentException("bufferSize should be even") } } private fun getByteBuffer(): ByteBuffer { return getLazyValue( byteBuffer, { ByteBuffer.wrap(byteBufferArray).apply { order(ByteOrder.LITTLE_ENDIAN) } }, { byteBuffer = it } ) } // offset is not used and its only purpose is to match a lambda signature in emitArray() private fun getByteBufferAsChar(@Suppress("UNUSED_PARAMETER") offset: Int = 0): CharBuffer { return getLazyValue( byteBufferAsCharHolder, { getByteBuffer().asCharBuffer() }, { byteBufferAsCharHolder = it } ) } private fun getByteBufferAsInt(offset: Int): IntBuffer { var bbAsInt = byteBufferAsIntHolder if (bbAsInt == null || byteBufferAsIntOffset != offset) { val bb = getByteBuffer() bb.position(offset) bbAsInt = bb.asIntBuffer() } byteBufferAsIntHolder = bbAsInt byteBufferAsIntOffset = offset return bbAsInt!! } fun emit(value: Short) { // Short (2 bytes) emission is special because as bufferPos should be even and buffer size is greater than or equals to 8, // there can't be cross-buffer writing. The logic can be simpler comparing to general emitPrimitive. val bp = bufferPos value.writeTo(byteBufferArray, bp) setBufferPosAndSyncIfNecessary(bp + 2) } fun emit(value: Int) { emitNumberPrimitive(value.toLong(), byteCount = 4) } fun emit(value: Long) { emitNumberPrimitive(value, byteCount = 8) } private fun emitNumberPrimitive( value: Long, byteCount: Int ) { val buf = byteBufferArray var bp = bufferPos val remaining = buf.size - bp if (remaining >= byteCount) { writeLongPartToBuffer(buf, bp, value, 0, byteCount) bp += byteCount } else { writeLongPartToBuffer(buf, bp, value, 0, remaining) // If remaining < byteCount, it means that we can't write enough bits of value to the buffer and // it needs to be written to the stream first. output.write(buf, 0, buf.size) val remainingInValue = byteCount - remaining writeLongPartToBuffer(buf, 0, value, remaining, remainingInValue) bp = remainingInValue } setBufferPosAndSyncIfNecessary(bp) } fun emit(value: String) { var cb = charBuffer val valueLength = value.length checkStringLength(valueLength) emit(valueLength.toShort()) // It saves a few allocations if the string is empty. if (valueLength > 0) { if (cb == null || valueLength > cb.size) { cb = CharArray(valueLength) charBuffer = cb } value.toCharArray(cb) emit(cb, 0, valueLength) } } fun emit(chars: CharArray, start: Int, end: Int) { emitPrimitiveArray(chars, start, end, elementSize = 2, this::getByteBufferAsChar, CharBuffer::put) } fun emit(ints: IntArray, start: Int, end: Int) { emitPrimitiveArray(ints, start, end, elementSize = 4, this::getByteBufferAsInt, IntBuffer::put) } fun emitArrayAndLength(ints: IntArray, start: Int = 0, end: Int = ints.size) { val length = end - start emit(length) emit(ints, start, end) } private inline fun <TArray : Any, TBuffer : Buffer> emitPrimitiveArray( array: TArray, start: Int, end: Int, elementSize: Int, getElementBuffer: (offset: Int) -> TBuffer, putArray: TBuffer.(TArray, start: Int, length: Int) -> Unit ) { val out = output val bb = byteBufferArray var bp = bufferPos val bufSize = bb.size val elemPos = bp / elementSize val elemOffset = bp % elementSize val offsetElemBuffer = getElementBuffer(elemOffset) val elementLength = end - start offsetElemBuffer.position(elemPos) val remElementsInByteBuffer = (bufSize - bp) / elementSize val prefixElemLength = min(remElementsInByteBuffer, elementLength) offsetElemBuffer.putArray(array, start, prefixElemLength) bp += prefixElemLength * elementSize if (prefixElemLength != elementLength) { // We've written what we can to the buffer which means we need to write it down the stream and start to re-fill the buffer. out.write(bb, 0, bp) var elementPos = start + prefixElemLength val elemBuffer = getElementBuffer(0) val bufSizeAsElement = bufSize / elementSize val alignedBufSize = bufSizeAsElement * elementSize // Stores amount of elements that need to be written. var remElements: Int while (true) { remElements = end - elementPos // Exit the loop if we can't do full buffer write. if (remElements < bufSizeAsElement) { break } elemBuffer.position(0) elemBuffer.putArray(array, elementPos, bufSizeAsElement) elementPos += bufSizeAsElement out.write(bb, 0, alignedBufSize) } // Write suffix if it exists. if (remElements > 0) { elemBuffer.position(0) elemBuffer.putArray(array, elementPos, remElements) } bp = remElements * elementSize } setBufferPosAndSyncIfNecessary(bp) } fun <T : Any> emit( values: Array<out T>, serializer: BinarySerializer<in T>, progressReporter: ProgressReporter? = null ) { val size = values.size emit(size) trackLoopProgressWith(progressReporter, size) { i -> serializer.writeTo(this, values[i]) } } fun flush() { val bp = bufferPos if (bp > 0) { output.write(byteBufferArray, 0, bp) } } private fun setBufferPosAndSyncIfNecessary(newPos: Int) { val bb = byteBufferArray val bufSize = bb.size bufferPos = if (newPos == bufSize) { output.write(bb, 0, bufSize) 0 } else { newPos } } companion object { internal fun checkStringLength(length: Int) { if (length > 65535) { throw IllegalArgumentException("Length of the string to be written can't be greater than 65535") } } internal fun writeLongPartToBuffer( buffer: ByteArray, bufferStart: Int, value: Long, valueStart: Int, length: Int ) { var shift = valueStart shl 3 for (i in 0 until length) { val b = (value shr shift).toByte() shift += 8 buffer[bufferStart + i] = b } } } }
3
Kotlin
0
2
944988a5f0028f93229cc324a6cd3ad5816ab80a
9,442
DigiDictionary
MIT License
common/src/main/java/io/github/pelmenstar1/digiDict/common/binarySerialization/PrimitiveValueWriter.kt
pelmenstar1
512,710,767
false
null
package io.github.pelmenstar1.digiDict.common.binarySerialization import io.github.pelmenstar1.digiDict.common.* import java.io.OutputStream import java.nio.* import kotlin.math.min /** * Provides means for writing primitive types (like [Int], [Long], [String]) to [OutputStream]. * The byte order can't be changed and is always little-endian. * * The class provides emit-like methods that write a value and move the cursor forward for the amount of bytes that was written. * Because of its stream nature, there's no going back and the cursor can't be moved forward or backward. * * The writer is already buffered, thus a reasonable buffer size should be specified in constructor. * There are several limitations imposed on buffer size: * - It should be greater than or equals to 8. * - It should be even. */ class PrimitiveValueWriter(private val output: OutputStream, bufferSize: Int) { private val byteBufferArray = ByteArray(bufferSize) private var byteBuffer: ByteBuffer? = null // A CharBuffer which can effectively write chars to byteBufferArray private var byteBufferAsCharHolder: CharBuffer? = null // A IntBuffer which can effectively write ints to byteBufferArray private var byteBufferAsIntHolder: IntBuffer? = null private var byteBufferAsIntOffset = 0 // A cached reference to the char array which is used in emit(String) to write a char data to it and write the array to the stream. // There's a temporary step with the char array because CharBuffer (when mapped from ByteBuffer) // provides optimized way for writing CharArray but not String. // // The size of the array is only extended when a string with bigger length than the array's one is requested. // Outside the emit(String) method, the array's content should be considered as garbage. private var charBuffer: CharArray? = null // Stores a current position in byteBufferArray from which writing the data should start. // It can't equal to byteBufferArray.size and should be even. private var bufferPos = 0 init { when { bufferSize < 8 -> throw IllegalArgumentException("bufferSize should be greater than or equals to 8") bufferSize % 2 != 0 -> throw IllegalArgumentException("bufferSize should be even") } } private fun getByteBuffer(): ByteBuffer { return getLazyValue( byteBuffer, { ByteBuffer.wrap(byteBufferArray).apply { order(ByteOrder.LITTLE_ENDIAN) } }, { byteBuffer = it } ) } // offset is not used and its only purpose is to match a lambda signature in emitArray() private fun getByteBufferAsChar(@Suppress("UNUSED_PARAMETER") offset: Int = 0): CharBuffer { return getLazyValue( byteBufferAsCharHolder, { getByteBuffer().asCharBuffer() }, { byteBufferAsCharHolder = it } ) } private fun getByteBufferAsInt(offset: Int): IntBuffer { var bbAsInt = byteBufferAsIntHolder if (bbAsInt == null || byteBufferAsIntOffset != offset) { val bb = getByteBuffer() bb.position(offset) bbAsInt = bb.asIntBuffer() } byteBufferAsIntHolder = bbAsInt byteBufferAsIntOffset = offset return bbAsInt!! } fun emit(value: Short) { // Short (2 bytes) emission is special because as bufferPos should be even and buffer size is greater than or equals to 8, // there can't be cross-buffer writing. The logic can be simpler comparing to general emitPrimitive. val bp = bufferPos value.writeTo(byteBufferArray, bp) setBufferPosAndSyncIfNecessary(bp + 2) } fun emit(value: Int) { emitNumberPrimitive(value.toLong(), byteCount = 4) } fun emit(value: Long) { emitNumberPrimitive(value, byteCount = 8) } private fun emitNumberPrimitive( value: Long, byteCount: Int ) { val buf = byteBufferArray var bp = bufferPos val remaining = buf.size - bp if (remaining >= byteCount) { writeLongPartToBuffer(buf, bp, value, 0, byteCount) bp += byteCount } else { writeLongPartToBuffer(buf, bp, value, 0, remaining) // If remaining < byteCount, it means that we can't write enough bits of value to the buffer and // it needs to be written to the stream first. output.write(buf, 0, buf.size) val remainingInValue = byteCount - remaining writeLongPartToBuffer(buf, 0, value, remaining, remainingInValue) bp = remainingInValue } setBufferPosAndSyncIfNecessary(bp) } fun emit(value: String) { var cb = charBuffer val valueLength = value.length checkStringLength(valueLength) emit(valueLength.toShort()) // It saves a few allocations if the string is empty. if (valueLength > 0) { if (cb == null || valueLength > cb.size) { cb = CharArray(valueLength) charBuffer = cb } value.toCharArray(cb) emit(cb, 0, valueLength) } } fun emit(chars: CharArray, start: Int, end: Int) { emitPrimitiveArray(chars, start, end, elementSize = 2, this::getByteBufferAsChar, CharBuffer::put) } fun emit(ints: IntArray, start: Int, end: Int) { emitPrimitiveArray(ints, start, end, elementSize = 4, this::getByteBufferAsInt, IntBuffer::put) } fun emitArrayAndLength(ints: IntArray, start: Int = 0, end: Int = ints.size) { val length = end - start emit(length) emit(ints, start, end) } private inline fun <TArray : Any, TBuffer : Buffer> emitPrimitiveArray( array: TArray, start: Int, end: Int, elementSize: Int, getElementBuffer: (offset: Int) -> TBuffer, putArray: TBuffer.(TArray, start: Int, length: Int) -> Unit ) { val out = output val bb = byteBufferArray var bp = bufferPos val bufSize = bb.size val elemPos = bp / elementSize val elemOffset = bp % elementSize val offsetElemBuffer = getElementBuffer(elemOffset) val elementLength = end - start offsetElemBuffer.position(elemPos) val remElementsInByteBuffer = (bufSize - bp) / elementSize val prefixElemLength = min(remElementsInByteBuffer, elementLength) offsetElemBuffer.putArray(array, start, prefixElemLength) bp += prefixElemLength * elementSize if (prefixElemLength != elementLength) { // We've written what we can to the buffer which means we need to write it down the stream and start to re-fill the buffer. out.write(bb, 0, bp) var elementPos = start + prefixElemLength val elemBuffer = getElementBuffer(0) val bufSizeAsElement = bufSize / elementSize val alignedBufSize = bufSizeAsElement * elementSize // Stores amount of elements that need to be written. var remElements: Int while (true) { remElements = end - elementPos // Exit the loop if we can't do full buffer write. if (remElements < bufSizeAsElement) { break } elemBuffer.position(0) elemBuffer.putArray(array, elementPos, bufSizeAsElement) elementPos += bufSizeAsElement out.write(bb, 0, alignedBufSize) } // Write suffix if it exists. if (remElements > 0) { elemBuffer.position(0) elemBuffer.putArray(array, elementPos, remElements) } bp = remElements * elementSize } setBufferPosAndSyncIfNecessary(bp) } fun <T : Any> emit( values: Array<out T>, serializer: BinarySerializer<in T>, progressReporter: ProgressReporter? = null ) { val size = values.size emit(size) trackLoopProgressWith(progressReporter, size) { i -> serializer.writeTo(this, values[i]) } } fun flush() { val bp = bufferPos if (bp > 0) { output.write(byteBufferArray, 0, bp) } } private fun setBufferPosAndSyncIfNecessary(newPos: Int) { val bb = byteBufferArray val bufSize = bb.size bufferPos = if (newPos == bufSize) { output.write(bb, 0, bufSize) 0 } else { newPos } } companion object { internal fun checkStringLength(length: Int) { if (length > 65535) { throw IllegalArgumentException("Length of the string to be written can't be greater than 65535") } } internal fun writeLongPartToBuffer( buffer: ByteArray, bufferStart: Int, value: Long, valueStart: Int, length: Int ) { var shift = valueStart shl 3 for (i in 0 until length) { val b = (value shr shift).toByte() shift += 8 buffer[bufferStart + i] = b } } } }
3
Kotlin
0
2
944988a5f0028f93229cc324a6cd3ad5816ab80a
9,442
DigiDictionary
MIT License
app/src/main/kotlin/co/netguru/android/carrecognition/data/recognizer/Car.kt
netguru
135,276,208
false
null
package co.netguru.android.carrecognition.data.recognizer enum class Car( val id: String ) { OTHER_CAR("OtherCar"), NOT_A_CAR("NotCar"), FORD_FIESTA("FordFiesta"), HONDA_CIVIC("HondaCivic"), NISSAN_QASHQAI("NissanQashqai"), VOLKSWAGEN_PASSAT("VolkswagenPassat"); companion object { const val TOP_SPEED_MAX = 200 const val ZERO_TO_SIXTY_MIN = 2.9f const val ZERO_TO_SIXTY_MAX = 20f const val HORSEPOWER_MAX = 320 const val ENGINE_MAX = 2000 fun of(text: String) = valueOf(text.replace(" ", "_").toUpperCase()) } }
0
Kotlin
8
24
321fa52c5cc0a339b27737b626163f8f72348cd9
600
CarLens-Android
Apache License 2.0
app/src/main/java/com/asteriatech/mobile/di/WebSocketThermalDataChannelModule.kt
erdemserhat
829,683,635
false
{"Kotlin": 43502}
package com.asteriatech.mobile.di import com.asteriatech.mobile.data.remote.websocket.WebSocketThermalDataChannelClient import com.asteriatech.mobile.data.remote.websocket.listeners.WebSocketThermalDataListenerImpl import com.asteriatech.mobile.data.repository.WebSocketThermalDataChannelRepository import com.asteriatech.mobile.domain.WebSocketThermalDataChannelService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.Request @Module @InstallIn(SingletonComponent::class) object WebSocketThermalDataChannelModule { @Provides @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) fun provideThermalDataUrl(): String { val customURL = CustomURL.Builder() .communicationProtocolType(CommunicationProtocolType.WS) .serverIp(ServerInformation.SERVER_IP) .serverPort(ServerInformation.SERVER_PORT) .endPoint(ServerInformation.EndPoints.THERMAL_DATA_ENDPOINT) .build() return customURL } @Provides @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) fun provideWebSocketThermalDataRequest(@WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) url: String): Request { return Request.Builder().url(url).build() } @Provides @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) fun provideWebSocketThermalDataClient( @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) request: Request, client: OkHttpClient ): WebSocketThermalDataChannelClient { return WebSocketThermalDataChannelClient(request, client) } @Provides @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) fun provideWebSocketThermalDataService( @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) webSocketThermalDataChannelClient: WebSocketThermalDataChannelClient, webSocketThermalDataListener: WebSocketThermalDataListenerImpl ): WebSocketThermalDataChannelService { return WebSocketThermalDataChannelService( webSocketThermalDataChannelClient, webSocketThermalDataListener ) } @Provides @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) fun provideWebSocketThermalDataRepository( @WebSocketChannel(WebSocketChannels.THERMAL_DATA_CHANNEL) webSocketThermalDataChannelService: WebSocketThermalDataChannelService ): WebSocketThermalDataChannelRepository { return WebSocketThermalDataChannelRepository(webSocketThermalDataChannelService) } }
0
Kotlin
0
0
cfc2d8a0c75352acf00a8955cbd57e0ae60011cc
2,639
AsteriaMobile
MIT License
model/src/main/kotlin/dev/msfjarvis/claw/model/UIPost.kt
msfjarvis
289,347,156
false
null
/* * Copyright © 2021-2024 Harsh Shandilya. * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package dev.msfjarvis.claw.model import dev.msfjarvis.claw.database.local.SavedPost import io.mcarle.konvert.api.KonvertFrom import io.mcarle.konvert.api.KonvertTo import io.mcarle.konvert.api.Mapping import kotlinx.serialization.SerialName @KonvertTo( value = SavedPost::class, mappings = [ Mapping(target = "submitterName", expression = "it.submitter.username"), Mapping(target = "submitterAvatarUrl", expression = "it.submitter.avatarUrl"), ], ) data class UIPost( val shortId: String, val createdAt: String, val title: String, val url: String, val description: String, val commentCount: Int, val commentsUrl: String, @SerialName("submitter_user") val submitter: User, val tags: List<String>, val comments: List<Comment> = emptyList(), val isSaved: Boolean = false, val isRead: Boolean = false, ) { @KonvertFrom( value = SavedPost::class, mappings = [ Mapping( target = "submitter", expression = "User(it.submitterName, \"\", null, it.submitterAvatarUrl, \"\")", ), Mapping(target = "commentCount", expression = "it.commentCount ?: 0"), Mapping(target = "isSaved", expression = "true"), ], ) companion object }
5
null
8
99
8303530857c7a94eefae83e4853438d0e73435db
1,441
compose-lobsters
MIT License
WX/WX-Maven/WX-Plugin/Maven-Wgllss-Dynamic-Plugin-Sample/maven-wgllss-sample-ui-other-lib/src/main/java/com/wgllss/sample/features_ui/page/home/viewmodels/CollectViewModel.kt
wgllss
805,804,060
false
{"Kotlin": 891471, "Java": 50011, "JavaScript": 17530}
package com.wgllss.sample.features_ui.page.home.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.wgllss.core.units.AppGlobals import com.wgllss.core.viewmodel.BaseViewModel import com.wgllss.sample.datasource.repository.NewsRepository import com.wgllss.sample.feature_system.room.table.CollectTableBean import kotlinx.coroutines.flow.onEach class CollectViewModel : BaseViewModel() { private val newsRepositoryL by lazy { NewsRepository.getInstance(AppGlobals.sApplication) } lateinit var liveData: LiveData<MutableList<CollectTableBean>> val isInitSuccess by lazy { MutableLiveData<Boolean>() } override fun start() { flowAsyncWorkOnViewModelScopeLaunch { newsRepositoryL.getAllList().onEach { liveData = it isInitSuccess.postValue(true) } } } fun deleteFromId(id: Long) { flowAsyncWorkOnViewModelScopeLaunch { newsRepositoryL.deleteFromId(id) } } }
4
Kotlin
8
40
868c09711b3e67b22e3345261734db09df9f2162
1,032
WXDynamicPlugin
Apache License 2.0
main/src/main/java/xyz/laziness/fontsimulator/main/MyActivity.kt
hwshim0810
127,599,118
false
null
package xyz.laziness.fontsimulator.main import android.support.v7.app.AppCompatActivity import android.widget.Toast const val BACK_EVENT_GAP_TIME = 2000 open class MyActivity : AppCompatActivity() { var onPressTime : Long = 0L override fun onBackPressed() { val now = System.currentTimeMillis() if (now > onPressTime + BACK_EVENT_GAP_TIME) { onPressTime = now Toast.makeText(applicationContext, getString(R.string.app_finish_msg), Toast.LENGTH_SHORT).show() } else { super.onBackPressed() } } }
0
Kotlin
0
0
98d20badc4103454ac8a0f63672f1cebda7822c0
601
font-simulator-Android
Apache License 2.0