path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/kotlin/net/primal/android/note/reactions/ReactionsScreen.kt
PrimalHQ
639,579,258
false
{"Kotlin": 2548226}
package net.primal.android.note.reactions import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemKey import net.primal.android.R import net.primal.android.core.compose.AvatarThumbnail import net.primal.android.core.compose.NostrUserText import net.primal.android.core.compose.PrimalDivider import net.primal.android.core.compose.PrimalTopAppBar import net.primal.android.core.compose.foundation.rememberLazyListStatePagingWorkaround import net.primal.android.core.compose.icons.PrimalIcons import net.primal.android.core.compose.icons.primaliconpack.ArrowBack import net.primal.android.core.compose.icons.primaliconpack.FeedZaps import net.primal.android.core.utils.shortened import net.primal.android.note.ui.NoteZapUiModel import net.primal.android.theme.AppTheme @Composable fun ReactionsScreen( viewModel: ReactionsViewModel, onClose: () -> Unit, onProfileClick: (profileId: String) -> Unit, ) { val state = viewModel.state.collectAsState() ReactionsScreen( state = state.value, onClose = onClose, onProfileClick = onProfileClick, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ReactionsScreen( state: ReactionsContract.UiState, onClose: () -> Unit, onProfileClick: (profileId: String) -> Unit, ) { Scaffold( topBar = { PrimalTopAppBar( title = stringResource(id = R.string.note_reactions_title), navigationIcon = PrimalIcons.ArrowBack, onNavigationIconClick = onClose, navigationIconContentDescription = stringResource(id = R.string.accessibility_back_button), ) }, content = { paddingValues -> val pagingItems = state.zaps.collectAsLazyPagingItems() val listState = pagingItems.rememberLazyListStatePagingWorkaround() LazyColumn( modifier = Modifier .fillMaxSize() .padding(paddingValues), state = listState, ) { items( count = pagingItems.itemCount, key = pagingItems.itemKey { it.id }, ) { val item = pagingItems[it] when { item != null -> NoteZapListItem( data = item, onProfileClick = onProfileClick, ) else -> Unit } } } }, ) } @Composable private fun NoteZapListItem(data: NoteZapUiModel, onProfileClick: (profileId: String) -> Unit) { Column { ListItem( modifier = Modifier.clickable { onProfileClick(data.zapperId) }, colors = ListItemDefaults.colors( containerColor = AppTheme.colorScheme.surfaceVariant, ), leadingContent = { AvatarThumbnail( avatarCdnImage = data.zapperAvatarCdnImage, avatarSize = 42.dp, onClick = { onProfileClick(data.zapperId) }, ) }, headlineContent = { NostrUserText(displayName = data.zapperName, internetIdentifier = data.zapperInternetIdentifier) }, supportingContent = { if (!data.message.isNullOrEmpty()) { Text( text = data.message, color = AppTheme.extraColorScheme.onSurfaceVariantAlt2, ) } }, trailingContent = { Column( modifier = Modifier.width(38.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Image( modifier = Modifier .padding(bottom = 4.dp) .size(18.dp), imageVector = PrimalIcons.FeedZaps, contentDescription = null, colorFilter = ColorFilter.tint(color = AppTheme.extraColorScheme.onSurfaceVariantAlt2), ) Text( modifier = Modifier.padding(vertical = 4.dp), text = data.amountInSats.toLong().shortened(), style = AppTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = AppTheme.colorScheme.onSurface, ) } }, ) PrimalDivider() } }
56
Kotlin
12
98
438072af7f67762c71c5dceffa0c83dedd8e2e85
5,687
primal-android-app
MIT License
kotest-assertions/src/commonMain/kotlin/io/kotest/properties/gens.kt
niraj8
268,596,932
false
null
package io.kotest.properties import io.kotest.properties.shrinking.ChooseShrinker import io.kotest.properties.shrinking.DoubleShrinker import io.kotest.properties.shrinking.FloatShrinker import io.kotest.properties.shrinking.IntShrinker import io.kotest.properties.shrinking.ListShrinker import io.kotest.properties.shrinking.Shrinker import io.kotest.properties.shrinking.StringShrinker import kotlin.jvm.JvmOverloads import kotlin.math.abs import kotlin.random.Random import kotlin.random.nextInt import kotlin.random.nextLong /** * Returns a stream of values where each value is a random * printed string. * * The constant values are: * The empty string * A line separator * Multi-line string * a UTF8 string. */ @JvmOverloads @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.string(minSize: Int = 0, maxSize: Int = 100): Gen<String> = object : Gen<String> { val literals = listOf("", "\n", "\nabc\n123\n", "\u006c\u0069b/\u0062\u002f\u006d\u0069nd/m\u0061x\u002e\u0070h\u0070") override fun constants(): Iterable<String> = literals.filter { it.length in minSize..maxSize } override fun random(seed: Long?): Sequence<String> { val r = getRandomFor(seed) return generateSequence { r.nextPrintableString(minSize + r.nextInt(maxSize - minSize + 1)) } } override fun shrinker(): Shrinker<String>? = StringShrinker } /** * Returns a stream of values where each value is a randomly * chosen [Int]. The values always returned include * the following edge cases: [[Int.MIN_VALUE], [Int.MAX_VALUE], 0, 1, -1] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.int() = object : Gen<Int> { val literals = listOf(Int.MIN_VALUE, Int.MAX_VALUE, 0, 1, -1) override fun constants(): Iterable<Int> = literals override fun random(seed: Long?): Sequence<Int> { val r = getRandomFor(seed) return generateSequence { r.nextInt() } } override fun shrinker() = IntShrinker } /** * Returns a stream of values where each value is a randomly * chosen [UInt]. The values always returned include * the following edge cases: [[UInt.MIN_VALUE], [UInt.MAX_VALUE]] */ @ExperimentalUnsignedTypes fun Gen.Companion.uint() = object : Gen<UInt> { val literals = listOf(UInt.MIN_VALUE, UInt.MAX_VALUE) override fun constants(): Iterable<UInt> = literals override fun random(seed: Long?): Sequence<UInt> { val r = getRandomFor(seed) return generateSequence { r.nextInt().toUInt() } } } /** * Returns a stream of values where each value is a randomly * chosen [Short]. The values always returned include * the following edge cases: [[Short.MIN_VALUE], [Short.MAX_VALUE], 0] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.short() = int().map { it.ushr(Int.SIZE_BITS - Short.SIZE_BITS).toShort() } /** * Returns a stream of values where each value is a randomly * chosen [UShort]. The values always returned include * the following edge cases: [[UShort.MIN_VALUE], [UShort.MAX_VALUE]] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") @ExperimentalUnsignedTypes fun Gen.Companion.ushort() = uint().map { it.shr(UInt.SIZE_BITS - UShort.SIZE_BITS).toUShort() } /** * Returns a stream of values where each value is a randomly * chosen [Byte]. The values always returned include * the following edge cases: [[Byte.MIN_VALUE], [Byte.MAX_VALUE], 0] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.byte() = int().map { it.ushr(Int.SIZE_BITS - Byte.SIZE_BITS).toByte() } /** * Returns a stream of values where each value is a randomly * chosen [UByte]. The values always returned include * the following edge cases: [[UByte.MIN_VALUE], [UByte.MAX_VALUE]] */ @ExperimentalUnsignedTypes fun Gen.Companion.ubyte() = uint().map { it.shr(UInt.SIZE_BITS - UByte.SIZE_BITS).toByte() } /** * Returns a stream of values where each value is a randomly * chosen positive value. The values returned always include * the following edge cases: [Int.MAX_VALUE] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.positiveIntegers(): Gen<Int> = int().filter { it > 0 } /** * Returns a stream of values where each value is a randomly * chosen natural number. The values returned always include * the following edge cases: [Int.MAX_VALUE] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.nats(): Gen<Int> = int().filter { it >= 0 } /** * Returns a stream of values where each value is a randomly * chosen negative value. The values returned always include * the following edge cases: [Int.MIN_VALUE] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.negativeIntegers(): Gen<Int> = int().filter { it < 0 } /** * Returns a stream of values where each value is a randomly * chosen Double. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.double(): Gen<Double> = object : Gen<Double> { val literals = listOf(0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE, Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY) override fun constants(): Iterable<Double> = literals override fun random(seed: Long?): Sequence<Double> { val r = getRandomFor(seed) return generateSequence { r.nextDouble() } } override fun shrinker(): Shrinker<Double>? = DoubleShrinker } /** * Returns a [Gen] which is the same as [Gen.double] but does not include +INFINITY, -INFINITY or NaN. * * This will only generate numbers ranging from [from] (inclusive) to [to] (inclusive) */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.numericDoubles(from: Double = Double.MIN_VALUE, to: Double = Double.MAX_VALUE ): Gen<Double> = object : Gen<Double> { val literals = listOf(0.0, 1.0, -1.0, 1e300, Double.MIN_VALUE, Double.MAX_VALUE).filter { it in (from..to) } override fun constants(): Iterable<Double> = literals override fun random(seed: Long?): Sequence<Double> { val r = getRandomFor(seed) return generateSequence { r.nextDouble(from, to) } } override fun shrinker(): Shrinker<Double>? = DoubleShrinker } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.positiveDoubles(): Gen<Double> = double().filter { it > 0.0 } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.negativeDoubles(): Gen<Double> = double().filter { it < 0.0 } /** * Returns a stream of values where each value is a randomly * chosen Float. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.float(): Gen<Float> = object : Gen<Float> { val literals = listOf(0F, Float.MIN_VALUE, Float.MAX_VALUE, Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY) override fun constants(): Iterable<Float> = literals override fun random(seed: Long?): Sequence<Float> { val r = getRandomFor(seed) return generateSequence { r.nextFloat() } } override fun shrinker() = FloatShrinker } /** * Returns a [Gen] which is the same as [Gen.float] but does not include +INFINITY, -INFINITY or NaN. * * This will only generate numbers ranging from [from] (inclusive) to [to] (inclusive) */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.numericFloats( from: Float = Float.MIN_VALUE, to: Float = Float.MAX_VALUE ): Gen<Float> = object : Gen<Float> { val literals = listOf(0.0F, 1.0F, -1.0F, Float.MIN_VALUE, Float.MAX_VALUE).filter { it in (from..to) } override fun constants(): Iterable<Float> = literals // There's no nextFloat(from, to) method, so borrowing it from Double override fun random(seed: Long?): Sequence<Float> { val r = getRandomFor(seed) return generateSequence { r.nextDouble(from.toDouble(), to.toDouble()).toFloat() } } override fun shrinker(): Shrinker<Float>? = FloatShrinker } /** * Returns a stream of values where each value is a randomly * chosen long. The values returned always include * the following edge cases: [[Long.MIN_VALUE], [Long.MAX_VALUE], 0, 1, -1] */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.long(): Gen<Long> = object : Gen<Long> { val literals = listOf(Long.MIN_VALUE, Long.MAX_VALUE, 0L, 1L, -1L) override fun constants(): Iterable<Long> = literals override fun random(seed: Long?): Sequence<Long> { val r = getRandomFor(seed) return generateSequence { abs(r.nextLong()) } } } /** * Returns a stream of values where each value is a randomly * chosen [ULong]. The values returned always include * the following edge cases: [[ULong.MIN_VALUE], [ULong.MAX_VALUE]] */ @ExperimentalUnsignedTypes fun Gen.Companion.ulong(): Gen<ULong> = object : Gen<ULong> { val literals = listOf(ULong.MIN_VALUE, ULong.MAX_VALUE) override fun constants(): Iterable<ULong> = literals override fun random(seed: Long?): Sequence<ULong> { val r = getRandomFor(seed) return generateSequence { r.nextLong().toULong() } } } /** * Returns both boolean values */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.bool(): Gen<Boolean> = object : Gen<Boolean> { override fun constants(): Iterable<Boolean> = listOf(true, false) override fun random(seed: Long?): Sequence<Boolean> { val r = getRandomFor(seed) return generateSequence { r.nextBoolean() } } } private object CharSets { val CONTROL = listOf('\u0000'..'\u001F', '\u007F'..'\u007F') val WHITESPACE = listOf('\u0020'..'\u0020', '\u0009'..'\u0009', '\u000A'..'\u000A') val BASIC_LATIN = listOf('\u0021'..'\u007E') } /** * Returns a stream of randomly-chosen Chars. Custom characters can be generated by * providing CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.char(range: CharRange, vararg ranges: CharRange): Gen<Char> { return Gen.char(listOf(range) + ranges) } /** * Returns a stream of randomly-chosen Chars. Custom characters can be generated by * providing a list of CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char(listOf('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. * * If no parameter is given, ASCII characters will be generated. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.char(ranges: List<CharRange> = CharSets.BASIC_LATIN): Gen<Char> = object : Gen<Char> { init { require(ranges.all { !it.isEmpty() }) { "Ranges cannot be empty" } require(ranges.isNotEmpty()) { "List of ranges must have at least one range" } } override fun constants(): Iterable<Char> = emptyList() override fun random(seed: Long?): Sequence<Char> { val r = getRandomFor(seed) val genRange = if (ranges.size == 1) Gen.constant(ranges.first()) else makeRangeWeightedGen() return generateSequence { genRange.next(seed = seed).random(r) } } // Convert the list of CharRanges into a weighted Gen in which // the ranges are chosen from the list using the length of the // range as the weight. private fun makeRangeWeightedGen(): Gen<CharRange> { val weightPairs = ranges.map { range -> val weight = range.last.toInt() - range.first.toInt() + 1 Pair(weight, range) } return Gen.choose(weightPairs[0], weightPairs[1], *weightPairs.drop(2).toTypedArray()) } } /** * Returns a stream of values, where each value is * a set of values generated by the given generator. */ @JvmOverloads @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.set(gen: Gen<T>, maxSize: Int = 100): Gen<Set<T>> = object : Gen<Set<T>> { init { require(maxSize >= 0) { "maxSize must be positive" } } override fun constants(): Iterable<Set<T>> = listOf(gen.constants().take(maxSize).toSet()) override fun random(seed: Long?): Sequence<Set<T>> { val r = getRandomFor(seed) return generateSequence { val size = r.nextInt(maxSize) gen.random().take(size).toSet() } } } /** * Returns a stream of values, where each value is * a list of values generated by the underlying generator. */ @JvmOverloads @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.list(gen: Gen<T>, maxSize: Int = 100): Gen<List<T>> = object : Gen<List<T>> { init { require(maxSize >= 0) { "maxSize must be positive" } } override fun constants(): Iterable<List<T>> = listOf(gen.constants().take(maxSize).toList()) override fun random(seed: Long?): Sequence<List<T>> { val r = getRandomFor(seed) return generateSequence { val size = r.nextInt(maxSize) gen.random().take(size).toList() } } override fun shrinker() = ListShrinker<T>() } /** * Returns a [[Gen]] where each value is a [[Triple]] generated * by a value from each of three supplied generators. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C> Gen.Companion.triple(genA: Gen<A>, genB: Gen<B>, genC: Gen<C>): Gen<Triple<A, B, C>> = object : Gen<Triple<A, B, C>> { override fun constants(): Iterable<Triple<A, B, C>> { return genA.constants().zip(genB.constants()).zip(genC.constants()).map { Triple(it.first.first, it.first.second, it.second) } } override fun random(seed: Long?): Sequence<Triple<A, B, C>> = genA.random(seed).zip(genB.random(seed)).zip( genC.random( seed)).map { Triple(it.first.first, it.first.second, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, T> Gen.Companion.bind(gena: Gen<A>, createFn: (A) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random().map { createFn(it) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, createFn: (A, B) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random().zip(genb.random(seed)).map { createFn(it.first, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, createFn: (A, B, C) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random().zip(genb.random(seed)).zip(genc.random()).map { createFn(it.first.first, it.first.second, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, createFn: (A, B, C, D) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random() .zip(genb.random(seed)) .zip(genc.random(seed)) .zip(gend.random(seed)) .map { createFn(it.first.first.first, it.first.first.second, it.first.second, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, createFn: (A, B, C, D, E) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random() .zip(genb.random(seed)) .zip(genc.random(seed)) .zip(gend.random(seed)) .zip(gene.random(seed)) .map { createFn(it.first.first.first.first, it.first.first.first.second, it.first.first.second, it.first.second, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E, F, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, genf: Gen<F>, createFn: (A, B, C, D, E, F) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random() .zip(genb.random(seed)) .zip(genc.random(seed)) .zip(gend.random(seed)) .zip(gene.random(seed)) .zip(genf.random(seed)) .map { createFn( it.first.first.first.first.first, it.first.first.first.first.second, it.first.first.first.second, it.first.first.second, it.first.second, it.second) } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <A, B, C, D, E, F, G, T> Gen.Companion.bind(gena: Gen<A>, genb: Gen<B>, genc: Gen<C>, gend: Gen<D>, gene: Gen<E>, genf: Gen<F>, geng: Gen<G>, createFn: (A, B, C, D, E, F, G) -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = gena.random() .zip(genb.random(seed)) .zip(genc.random(seed)) .zip(gend.random(seed)) .zip(gene.random(seed)) .zip(genf.random(seed)) .zip(geng.random(seed)) .map { createFn( it.first.first.first.first.first.first, it.first.first.first.first.first.second, it.first.first.first.first.second, it.first.first.first.second, it.first.first.second, it.first.second, it.second) } } fun <A> Gen.Companion.oneOf(vararg gens: Gen<out A>): Gen<A> = object : Gen<A> { override fun constants(): Iterable<A> = gens.flatMap { it.constants() } override fun random(seed: Long?): Sequence<A> { require(gens.isNotEmpty()) { "List of generators cannot be empty" } val iterators = gens.map { it.random(seed).iterator() } val r = getRandomFor(seed) return generateInfiniteSequence { val iteratorLocation = r.nextInt(0, iterators.size) val iterator = iterators[iteratorLocation] iterator.next() } } } /** * Returns a stream of values, where each * value is generated from the given function */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") inline fun <T> Gen.Companion.create(crossinline fn: () -> T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> = generateInfiniteSequence { fn() } } /** * Adapts a list into a generator, where random * values will be picked. May not choose every * item in the list. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.from(values: List<T>): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> { val r = getRandomFor(seed) return generateInfiniteSequence { values[r.nextInt(0, values.size)] } } } /** * @return a new [Gen] created from the given [values] (see [from] List for more details) */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.from(values: Array<T>): Gen<T> = from(values.toList()) /** * Returns a stream of values, where each value is * a random Int between the given min and max. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0. Use Arb.ints(min, max)") fun Gen.Companion.choose(min: Int, max: Int): Gen<Int> { require(min < max) { "min must be < max" } return object : Gen<Int> { override fun constants(): Iterable<Int> = emptyList() override fun random(seed: Long?): Sequence<Int> { val r = getRandomFor(seed) return generateSequence { r.nextInt(min..max) } } override fun shrinker() = ChooseShrinker(min, max) } } /** * Returns a stream of values, where each value is a * Long between the given min and max. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0. Use Arb.longs(min, max)") fun Gen.Companion.choose(min: Long, max: Long): Gen<Long> { require(min < max) { "min must be < max" } return object : Gen<Long> { override fun constants(): Iterable<Long> = emptyList() override fun random(seed: Long?): Sequence<Long> { val r = getRandomFor(seed) return generateSequence { r.nextLong(min..max) } } } } /** * Returns a stream of values based on weights: * * Gen.choose(1 to 'A', 2 to 'B') will generate 'A' 33% of the time * and 'B' 66% of the time. * * @throws IllegalArgumentException If any negative weight is given or only * weights of zero are given. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0. Use Arb.choose(a, b, c, ...)") fun <T : Any> Gen.Companion.choose(a: Pair<Int, T>, b: Pair<Int, T>, vararg cs: Pair<Int, T>): Gen<T> { val allPairs = listOf(a, b) + cs val weights = allPairs.map { it.first } require(weights.all { it >=0 }) { "Negative weights not allowed" } require(weights.any { it > 0 }) { "At least one weight must be greater than zero"} return object : Gen<T> { // The algorithm for pick is a migration of // the algorithm from Haskell QuickCheck // http://hackage.haskell.org/package/QuickCheck // See function frequency in the package Test.QuickCheck private tailrec fun pick(n: Int, l: Sequence<Pair<Int, T>>): T { val (w, e) = l.first() return if (n <= w) e else pick(n - w, l.drop(1)) } override fun constants(): Iterable<T> = emptyList() override fun random(seed: Long?): Sequence<T> { val r = getRandomFor(seed) val total = weights.sum() return generateSequence { val n = r.nextInt(1, total + 1) pick(n, allPairs.asSequence()) } } } } /** * Returns a stream of values, where each value is * a pair generated by the underlying generators. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <K, V> Gen.Companion.pair(genK: Gen<K>, genV: Gen<V>): Gen<Pair<K, V>> = object : Gen<Pair<K, V>> { override fun constants(): Iterable<Pair<K, V>> { val keys = genK.constants().toList() return keys.zip(genV.random().take(keys.size).toList()) } override fun random(seed: Long?): Sequence<Pair<K, V>> = genK.random(seed).zip(genV.random(seed)) } /** * Returns a stream of values, where each value is * a Map, which contains keys and values generated * from the underlying generators. */ @JvmOverloads @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <K, V> Gen.Companion.map(genK: Gen<K>, genV: Gen<V>, maxSize: Int = 100): Gen<Map<K, V>> = object : Gen<Map<K, V>> { init { require(maxSize >= 0) { "maxSize must be positive" } } override fun constants(): Iterable<Map<K, V>> = emptyList() override fun random(seed: Long?): Sequence<Map<K, V>> { val r = getRandomFor(seed) return generateSequence { val size = r.nextInt(maxSize) genK.random().take(size).zip(genV.random().take(size)).toMap() } } } /** * @return a stream of values, where each value is a [Map] of [Pair]s from the given [gen] * the size of the [Map] is bounded between [0, [maxSize]) */ @JvmOverloads @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <K, V> Gen.Companion.map(gen: Gen<Pair<K, V>>, maxSize: Int = 100): Gen<Map<K, V>> = object : Gen<Map<K, V>> { init { require(maxSize >= 0) { "maxSize must be positive" } } override fun constants(): Iterable<Map<K, V>> = emptyList() override fun random(seed: Long?): Sequence<Map<K, V>> { val r = getRandomFor(seed) return generateSequence { val size = r.nextInt(maxSize) gen.random(seed).take(size).toMap() } } } /** * Returns the next pseudorandom, uniformly distributed value * from the ASCII range 32-126. */ fun Random.nextPrintableChar(): Char = nextInt(from = 32, until = 127).toChar() /** * Generates a [String] of [length] by calling [nextPrintableChar] * * ```kotlin * // Examples * val r = Random.Default * r.nextPrintableString(-10) // "" * r.nextPrintableString(0) // "" * r.nextPrintableString(1) // " ", "a", "Z", etc. * r.nextPrintableString(5) // "Ha Ha", "gens!", "[{-}]", etc. * ``` * * @param length of String * @return a given length String of random printable Chars */ fun Random.nextPrintableString(length: Int): String { return (0 until length).map { nextPrintableChar() }.joinToString("") } /** * Returns a [[Gen]] which always returns the same value. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.constant(value: T): Gen<T> = object : Gen<T> { override fun constants(): Iterable<T> = listOf(value) override fun random(seed: Long?): Sequence<T> = generateInfiniteSequence { value } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.multiples(k: Int, max: Int): Gen<Int> = object : Gen<Int> { // 0 is a multiple of everything override fun constants(): Iterable<Int> = listOf(0) override fun random(seed: Long?): Sequence<Int> { val r = getRandomFor(seed) return generateSequence { r.nextInt(max / k) * k }.filter { it >= 0 } } } @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun Gen.Companion.factors(k: Int): Gen<Int> = object : Gen<Int> { // 1 is a factor of all ints override fun constants(): Iterable<Int> = listOf(1) override fun random(seed: Long?): Sequence<Int> { val r = getRandomFor(seed) return generateSequence { r.nextInt(k) }.filter { it > 0 } .filter { k % it == 0 } } } /** * Returns a [Gen] which returns the sample values in the same order as they are passed in, once all sample values are used * it repeats elements from start. */ @Deprecated("Deprecated and will be removed in 5.0. Migrate to the new property test classes in 4.0") fun <T> Gen.Companion.samples(vararg sampleValues: T) = object : Gen<T> { private fun getNextSampleElementProvider(): () -> T { var currentIndex = 0; return { val nextIndex = currentIndex % sampleValues.size val nextValue = sampleValues[nextIndex] currentIndex += 1 nextValue } } override fun random(seed: Long?): Sequence<T> { return if(sampleValues.isEmpty()) { emptySequence() } else { generateInfiniteSequence(getNextSampleElementProvider()) } } override fun constants(): Iterable<T> = sampleValues.asIterable() }
1
null
1
1
e176cc3e14364d74ee593533b50eb9b08df1f5d1
29,447
kotlintest
Apache License 2.0
src/main/kotlin/gdx/liftoff/views/widgets/ScrollableTextArea.kt
libgdx
188,758,773
false
null
package com.github.czyzby.setup.views.widgets import com.github.czyzby.kiwi.util.common.Strings import com.github.czyzby.lml.parser.LmlParser import com.github.czyzby.lml.parser.impl.tag.builder.TextLmlActorBuilder import com.github.czyzby.lml.parser.tag.LmlTag import com.github.czyzby.lml.parser.tag.LmlTagProvider import com.github.czyzby.lml.vis.parser.impl.tag.VisTextAreaLmlTag import com.kotcrab.vis.ui.widget.VisTextArea import com.kotcrab.vis.ui.widget.VisTextField /** Custom [VisTextArea] used to display logs in the generation prompt. Supports embedding in scroll pane by calculating * required space needed for current text. * @author Kotcrab */ class ScrollableTextArea(text: String, styleName: String) : VisTextArea(text, styleName) { init { style.font.data.markupEnabled = true; } override fun getPrefWidth(): Float { return width } override fun getPrefHeight(): Float { return lines * style.font.lineHeight } override fun setText(str: String) { // TextArea seems to have problem when '\r\n' (Windows style) is used as line ending, as it treats it as two // lines. Although example templates files are using '\n', Git (when cloning the repository) may replace them // with '\r\n' on Windows. super.setText(Strings.stripCharacter(str, '\r')) } /** Provides [CodeTextArea] tags. * @author Kotcrab */ class ScrollableTextAreaLmlTagProvider : LmlTagProvider { override fun create(parser: LmlParser, parentTag: LmlTag, rawTagData: StringBuilder): LmlTag = ScrollableTextAreaLmlTag(parser, parentTag, rawTagData) } /** Handles [CodeTextArea] actor. * @author Kotcrab */ class ScrollableTextAreaLmlTag(parser: LmlParser, parentTag: LmlTag, rawTagData: StringBuilder) : VisTextAreaLmlTag(parser, parentTag, rawTagData) { override protected fun getNewInstanceOfTextField(textBuilder: TextLmlActorBuilder): VisTextField = ScrollableTextArea(textBuilder.text, textBuilder.styleName) } }
8
null
50
534
7f172c9953acd8e6bf967310e2c2121baa7e9a22
2,097
gdx-liftoff
Apache License 2.0
app/src/main/java/site/panda2134/thssforum/models/User.kt
panda2134-thss-android-team
488,254,653
false
null
/** * THSSForum * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package site.panda2134.thssforum.models import com.google.gson.annotations.SerializedName /** <<<<<<< HEAD * * @param uid * @param nickname ======= * * @param uid * @param nickname >>>>>>> b4b450e45b368d43885bb35d9952a220dcd4308f * @param email * @param avatar * @param intro */ data class User ( @SerializedName("uid") val uid: String, @SerializedName("nickname") val nickname: String, @SerializedName("email") val email: String, @SerializedName("avatar") val avatar: String, @SerializedName("intro") val intro: String, )
0
Kotlin
0
2
a5c527b0073158a38ee658842dc2a759bb499268
927
thss-forum-android
MIT License
app/src/main/java/com/example/yumyum/ui/secondactivity/mealdetailsscreen/ingredientsfragment/IngredientsAdapter.kt
RanaAnwar1
843,824,099
false
{"Kotlin": 106708}
package com.example.yumyum.ui.secondactivity.mealdetailsscreen.ingredientsfragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.yumyum.R import com.example.yumyum.databinding.IngredientItemViewBinding class IngredientsAdapter(private val ingredients: List<Ingredient>) : RecyclerView.Adapter<IngredientsAdapter.IngredientViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IngredientViewHolder { val binding = IngredientItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false) return IngredientViewHolder(binding) } override fun onBindViewHolder(holder: IngredientViewHolder, position: Int) { val ingredient = ingredients[position] Log.d("IngredientsFragment", "ingredients adapter $ingredient") holder.bind(ingredient) } override fun getItemCount(): Int = ingredients.size class IngredientViewHolder(private val binding: IngredientItemViewBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(ingredient: Ingredient) { binding.ingredientTitle.text = ingredient.title binding.ingredientMeasurement.text = ingredient.measurement } } } data class Ingredient(val title: String, val measurement: String)
0
Kotlin
0
0
02c22a19e2bf918cb0d4226dbaed5dd7fbc41285
1,443
YumYum
MIT License
verik-compiler/src/test/kotlin/io/verik/compiler/check/post/StatementCheckerStageTest.kt
frwang96
269,980,078
false
null
/* * Copyright (c) 2021 Francis Wang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.verik.compiler.check.post import io.verik.compiler.test.BaseTest import org.junit.jupiter.api.Test internal class StatementCheckerStageTest : BaseTest() { @Test fun `invalid statement`() { driveMessageTest( """ fun f() { 0 } """.trimIndent(), true, "Could not interpret expression as statement" ) } }
0
null
1
7
a40d6195f3b57bebac813b3e5be59d17183433c7
1,045
verik
Apache License 2.0
backend/src/main/kotlin/hotel/minimal/backend/dtos/DeleteDto.kt
IIPEKOLICT
521,438,023
false
null
package hotel.minimal.backend.dtos data class DeleteDto(val id: Int = -1)
0
Kotlin
0
0
a24df5667b13b3274ed9cbbb5c7d06f5494e41f1
74
hotel-minimal
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/unit/restapi/controller/ReferralsControllerTest.kt
ministryofjustice
615,402,552
false
{"Kotlin": 501733, "Shell": 9504, "Dockerfile": 1415}
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.restapi.controller import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.ninjasquad.springmockk.MockkBean import io.kotest.matchers.shouldBe import io.mockk.Runs import io.mockk.every import io.mockk.just import io.mockk.verify import jakarta.validation.ValidationException import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.Import import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.test.context.support.WithMockUser import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.post import org.springframework.test.web.servlet.put import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.config.JwtAuthHelper import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.util.REFERRAL_STARTED import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.util.REFERRAL_SUBMITTED import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.util.REFERRER_USERNAME import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.util.randomPrisonNumber import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.domain.entity.create.AuditAction import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.restapi.model.ReferralStatusUpdate import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.service.AuditService import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.service.ReferralService import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.service.SecurityService import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.CourseEntityFactory import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.OfferingEntityFactory import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.ReferralEntityFactory import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.unit.domain.entity.factory.ReferrerUserEntityFactory import java.util.UUID private const val MY_REFERRALS_ENDPOINT = "/referrals/me/dashboard" @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc @ActiveProfiles("test") @Import(JwtAuthHelper::class) class ReferralControllerTest @Autowired constructor( val mockMvc: MockMvc, val jwtAuthHelper: JwtAuthHelper, ) { @MockkBean private lateinit var referralService: ReferralService @MockkBean private lateinit var securityService: SecurityService @MockkBean private lateinit var auditService: AuditService @Test fun `createReferral with JWT, existing user, and valid payload returns 201 with correct body`() { val referral = ReferralEntityFactory() .withOffering( OfferingEntityFactory() .withId(UUID.randomUUID()) .produce(), ) .withPrisonNumber(randomPrisonNumber()) .withReferrer( ReferrerUserEntityFactory() .withUsername(REFERRER_USERNAME) .produce(), ) .produce() val payload = mapOf( "offeringId" to referral.offering.id, "prisonNumber" to referral.prisonNumber, ) every { referralService.createReferral(any(), any()) } returns referral.id mockMvc.post("/referrals") { contentType = MediaType.APPLICATION_JSON headers { set(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) } content = jacksonObjectMapper().writeValueAsString(payload) }.andExpect { status { isCreated() } content { contentType(MediaType.APPLICATION_JSON) jsonPath("$.referralId") { value(referral.id.toString()) } } } verify { referralService.createReferral(referral.prisonNumber, referral.offering.id!!) } } @Test @WithMockUser(username = "NONEXISTENT_USER") fun `createReferral with JWT, nonexistent user, and valid payload returns 201 with correct body`() { val referral = ReferralEntityFactory() .withOffering( OfferingEntityFactory() .withId(UUID.randomUUID()) .produce(), ) .withPrisonNumber(randomPrisonNumber()) .withReferrer( ReferrerUserEntityFactory() .withUsername(SecurityContextHolder.getContext().authentication?.name.toString()) .produce(), ) .produce() SecurityContextHolder.getContext().authentication?.name shouldBe "NONEXISTENT_USER" val payload = mapOf( "offeringId" to referral.offering.id, "prisonNumber" to referral.prisonNumber, ) every { referralService.createReferral(any(), any()) } returns referral.id mockMvc.post("/referrals") { contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) content = jacksonObjectMapper().writeValueAsString(payload) }.andExpect { status { isCreated() } content { contentType(MediaType.APPLICATION_JSON) jsonPath("$.referralId") { value(referral.id.toString()) } } } verify { referralService.createReferral(referral.prisonNumber, referral.offering.id!!) } } @Test fun `getReferralById with JWT returns 200 with correct body`() { val offeringEntity = OfferingEntityFactory() .withId(UUID.randomUUID()) .produce() offeringEntity.course = CourseEntityFactory().produce() val referral = ReferralEntityFactory() .withId(UUID.randomUUID()) .withOffering(offeringEntity) .withReferrer( ReferrerUserEntityFactory() .withUsername(REFERRER_USERNAME) .produce(), ) .withOasysConfirmed(true) .withHasReviewedProgrammeHistory(true) .produce() every { referralService.getReferralById(any()) } returns referral every { auditService.audit(any(), any(), org.mockito.kotlin.eq(AuditAction.VIEW_REFERRAL.name)) } returns Unit mockMvc.get("/referrals/${referral.id}?updatePerson=false") { accept = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isOk() } content { contentType(MediaType.APPLICATION_JSON) jsonPath("$.offeringId") { value(referral.offering.id.toString()) } jsonPath("$.prisonNumber") { value(referral.prisonNumber) } jsonPath("$.referrerUsername") { value(referral.referrer.username) } jsonPath("$.status") { REFERRAL_STARTED } jsonPath("$.oasysConfirmed") { value(true) } jsonPath("$.hasReviewedProgrammeHistory") { value(true) } jsonPath("$.additionalInformation") { doesNotExist() } } } verify { referralService.getReferralById(any()) } verify { auditService.audit(any(), any(), org.mockito.kotlin.eq(AuditAction.VIEW_REFERRAL.name)) } } @Test fun `getReferralById without JWT returns 401`() { mockMvc.get("/referrals/${UUID.randomUUID()}") { accept = MediaType.APPLICATION_JSON }.andExpect { status { isUnauthorized() } } } @Test fun `getReferralById with random UUID returns 404 with error body`() { val referralId = UUID.randomUUID() every { referralService.getReferralById(any()) } returns null mockMvc.get("/referrals/$referralId?updatePerson=false") { accept = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isNotFound() } content { contentType(MediaType.APPLICATION_JSON) jsonPath("$.status") { value(404) } jsonPath("$.errorCode") { isEmpty() } jsonPath("$.userMessage") { prefix("Not Found: No Referral found at /referrals/$referralId") } jsonPath("$.developerMessage") { prefix("No referral found at /courses/$referralId") } jsonPath("$.moreInfo") { isEmpty() } } } verify { referralService.getReferralById(referralId) } } @Test fun `getReferralById with invalid UUID returns 400 with error body`() { val referralId = "bad-id" mockMvc.get("/referrals/$referralId") { accept = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isBadRequest() } content { contentType(MediaType.APPLICATION_JSON) jsonPath("$.status") { value(400) } jsonPath("$.errorCode") { isEmpty() } jsonPath("$.userMessage") { prefix("Request not readable: Failed to convert value of type 'java.lang.String' to required type 'UUID'; Invalid UUID string: bad-id") } jsonPath("$.developerMessage") { prefix("Failed to convert value of type 'java.lang.String' to required type 'UUID'; Invalid UUID string: bad-id") } jsonPath("$.moreInfo") { isEmpty() } } } } @Test fun `updateReferralStatusById with valid transition returns 204 with no body`() { val referral = ReferralEntityFactory().produce() val payload = mapOf( "status" to "REFERRAL_SUBMITTED", ) every { referralService.updateReferralStatusById(any(), any()) } just Runs mockMvc.put("/referrals/${referral.id}/status") { contentType = MediaType.APPLICATION_JSON header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) content = jacksonObjectMapper().writeValueAsString(payload) }.andExpect { status { isNoContent() } } verify { referralService.updateReferralStatusById(referral.id!!, ReferralStatusUpdate(status = REFERRAL_SUBMITTED)) } } @Test fun `submitReferralById with valid ID returns 204 with no body`() { val referral = ReferralEntityFactory() .withOffering( OfferingEntityFactory() .withId(UUID.randomUUID()) .produce(), ) .withPrisonNumber(randomPrisonNumber()) .withReferrer( ReferrerUserEntityFactory() .withUsername(REFERRER_USERNAME) .produce(), ) .withAdditionalInformation("Additional Info") .withOasysConfirmed(true) .withHasReviewedProgrammeHistory(true) .produce() every { referralService.getReferralById(referral.id!!) } returns referral every { referralService.submitReferralById(referral.id!!) } just Runs mockMvc.post("/referrals/${referral.id}/submit") { header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isNoContent() } } verify { referralService.getReferralById(referral.id!!) } verify { referralService.submitReferralById(referral.id!!) } } @Test fun `submitReferralById with invalid ID returns 404 with error body`() { val invalidReferralId = UUID.randomUUID() every { referralService.getReferralById(invalidReferralId) } returns null mockMvc.post("/referrals/$invalidReferralId/submit") { header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isNotFound() } } verify { referralService.getReferralById(invalidReferralId) } } @Test fun `submitReferralById with incomplete referral returns 400 with error body`() { val referral = ReferralEntityFactory() .withOffering( OfferingEntityFactory() .withId(UUID.randomUUID()) .produce(), ) .withPrisonNumber(randomPrisonNumber()) .withReferrer( ReferrerUserEntityFactory() .withUsername(REFERRER_USERNAME) .produce(), ) .produce() every { referralService.getReferralById(referral.id!!) } returns referral every { referralService.submitReferralById(referral.id!!) } throws ValidationException("additionalInformation is not valid: null") mockMvc.post("/referrals/${referral.id}/submit") { header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken()) }.andExpect { status { isBadRequest() } } verify { referralService.getReferralById(referral.id!!) } verify { referralService.submitReferralById(referral.id!!) } } }
3
Kotlin
0
0
eef3131ddcb2d222af9974cb0b93ddc4f4ce3a64
12,471
hmpps-accredited-programmes-api
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnDashboardRadarChartFieldWellsPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.quicksight import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.quicksight.CfnDashboard /** * The field wells of a radar chart visual. * * Example: * ``` * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dashboard-radarchartfieldwells.html) */ @CdkDslMarker public class CfnDashboardRadarChartFieldWellsPropertyDsl { private val cdkBuilder: CfnDashboard.RadarChartFieldWellsProperty.Builder = CfnDashboard.RadarChartFieldWellsProperty.builder() /** @param radarChartAggregatedFieldWells The aggregated field wells of a radar chart visual. */ public fun radarChartAggregatedFieldWells(radarChartAggregatedFieldWells: IResolvable) { cdkBuilder.radarChartAggregatedFieldWells(radarChartAggregatedFieldWells) } /** @param radarChartAggregatedFieldWells The aggregated field wells of a radar chart visual. */ public fun radarChartAggregatedFieldWells( radarChartAggregatedFieldWells: CfnDashboard.RadarChartAggregatedFieldWellsProperty ) { cdkBuilder.radarChartAggregatedFieldWells(radarChartAggregatedFieldWells) } public fun build(): CfnDashboard.RadarChartFieldWellsProperty = cdkBuilder.build() }
0
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,585
awscdk-dsl-kotlin
Apache License 2.0
sdk/backend/src/main/kotlin/com/supertokens/sdk/recipes/emailpassword/requests/CreateResetPasswordTokenRequest.kt
Appstractive
656,572,792
false
null
package com.supertokens.sdk.recipes.emailpassword.requests import kotlinx.serialization.Serializable @Serializable data class CreateResetPasswordTokenRequest( val userId: String, val email: String, )
5
null
1
3
e4d0ff3664034d1c4981a0a2cdf58c3a053da2a7
210
supertokens-kt
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/source/online/AnimeSource.kt
az4521
176,152,541
true
{"Kotlin": 2483150}
package eu.kanade.tachiyomi.source.online /** * A source that will return anime instead of manga. * Chapters are episodes, pages are videos, page numbers are video quality * The rest works the same as a standard HttpSource */ interface AnimeSource
22
Kotlin
18
471
a72df3df5073300e02054ee75dc990d196cd6db8
253
TachiyomiAZ
Apache License 2.0
subprojects/library/src/commonMain/kotlin/kotools/types/text/NotBlankString.kt
kotools
581,475,148
false
null
package kotools.types.text import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotools.types.experimental.ExperimentalKotoolsTypesApi import kotools.types.internal.ErrorMessage import kotools.types.internal.InternalKotoolsTypesApi import kotools.types.internal.KotoolsTypesPackage import kotools.types.internal.serializationError import kotools.types.internal.simpleNameOf import kotools.types.internal.stringSerializer import kotools.types.number.StrictlyPositiveInt import kotools.types.number.toStrictlyPositiveInt import org.kotools.types.internal.ExperimentalSince import org.kotools.types.internal.KotoolsTypesVersion import org.kotools.types.internal.Since import kotlin.jvm.JvmInline import kotlin.jvm.JvmSynthetic /** * Returns this string as an encapsulated [NotBlankString], or returns an * encapsulated [IllegalArgumentException] if this string is * [blank][String.isBlank]. */ @OptIn(InternalKotoolsTypesApi::class) @Since(KotoolsTypesVersion.V4_0_0) public fun String.toNotBlankString(): Result<NotBlankString> = runCatching { requireNotNull(NotBlankString of this) { ErrorMessage.blankString } } /** * Represents a string that has at least one character excluding whitespaces. * * You can use the [toNotBlankString] function for creating an instance of this * type. * * <br> * <details> * <summary> * <b>Serialization and deserialization</b> * </summary> * * The [serialization and deserialization processes](https://kotlinlang.org/docs/serialization.html) * of this type behave like for the [String] type. * * Here's an example of Kotlin code that encodes and decodes this type using the * [JavaScript Object Notation (JSON) format from kotlinx.serialization](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json): * * ```kotlin * val string: NotBlankString = "hello world".toNotBlankString() * .getOrThrow() * val encoded: String = Json.encodeToString(string) * println(encoded) // "hello world" * val decoded: NotBlankString = Json.decodeFromString(encoded) * println(decoded == string) // true * ``` * </details> */ @JvmInline @OptIn(InternalKotoolsTypesApi::class) @Serializable(NotBlankStringSerializer::class) @Since(KotoolsTypesVersion.V4_0_0) public value class NotBlankString private constructor( private val value: String ) : Comparable<NotBlankString> { /** Contains static declarations for the [NotBlankString] type. */ public companion object { /** * Creates a [NotBlankString] from the string representation of the * specified [value], or throws an [IllegalArgumentException] if its * string representation is [blank][String.isBlank]. * * Here's an example of calling this function from Kotlin code: * * ```kotlin * val text: NotBlankString = NotBlankString.create("Kotools Types") * println(text) // Kotools Types * ``` * * The [NotBlankString] type being an * [inline value class](https://kotlinlang.org/docs/inline-classes.html), * this function is not available yet for Java users. * * You can use the [NotBlankString.Companion.createOrNull] function for * returning `null` instead of throwing an exception in case of invalid * [value]. */ @ExperimentalKotoolsTypesApi @ExperimentalSince(KotoolsTypesVersion.V4_5_0) @JvmSynthetic public fun create(value: Any): NotBlankString { val text: String = value.toString() val isValid: Boolean = text.isNotBlank() require(isValid) { ErrorMessage.blankString } return NotBlankString(text) } /** * Creates a [NotBlankString] from the string representation of the * specified [value], or returns `null` if its string representation is * [blank][String.isBlank]. * * Here's an example of calling this function from Kotlin code: * * ```kotlin * val text: NotBlankString? = * NotBlankString.createOrNull("Kotools Types") * println(text) // Kotools Types * ``` * * The [NotBlankString] type being an * [inline value class](https://kotlinlang.org/docs/inline-classes.html), * this function is not available yet for Java users. * * You can use the [NotBlankString.Companion.create] function for * throwing an exception instead of returning `null` in case of invalid * [value]. */ @ExperimentalKotoolsTypesApi @ExperimentalSince(KotoolsTypesVersion.V4_5_0) @JvmSynthetic public fun createOrNull(value: Any): NotBlankString? { val text: String = value.toString() val isValid: Boolean = text.isNotBlank() return if (isValid) NotBlankString(text) else null } @JvmSynthetic internal infix fun of(value: String): NotBlankString? = if (value.isBlank()) null else NotBlankString(value) } /** Returns the length of this string. */ public val length: StrictlyPositiveInt get() = value.length.toStrictlyPositiveInt() .getOrThrow() /** * Compares this string alphabetically with the [other] one for order. * Returns zero if this string equals the [other] one, a negative number if * it's less than the [other] one, or a positive number if it's greater than * the [other] one. */ @Since(KotoolsTypesVersion.V4_1_0) override infix fun compareTo(other: NotBlankString): Int = "$this".compareTo("$other") /** * Concatenates this string with the string representation of the [other] * object. * * Here's an example of calling this function from Kotlin code: * * ```kotlin * val text: NotBlankString = "hello".toNotBlankString() * .getOrThrow() * val message: NotBlankString = text + " world" * println(message) // hello world * ``` * * The [NotBlankString] type being an * [inline value class](https://kotlinlang.org/docs/inline-classes.html), * this function is not available yet for Java users. */ @ExperimentalKotoolsTypesApi @ExperimentalSince(KotoolsTypesVersion.V4_5_0) @JvmSynthetic public operator fun plus(other: Any): NotBlankString = value.plus("$other") .toNotBlankString() .getOrThrow() /** Returns this string as a [String]. */ override fun toString(): String = value } @InternalKotoolsTypesApi internal object NotBlankStringSerializer : KSerializer<NotBlankString> by stringSerializer( NotBlankStringDeserializationStrategy ) @InternalKotoolsTypesApi private object NotBlankStringDeserializationStrategy : DeserializationStrategy<NotBlankString> { override val descriptor: SerialDescriptor by lazy { val simpleName: String = simpleNameOf<NotBlankString>() val serialName = "${KotoolsTypesPackage.Text}.$simpleName" PrimitiveSerialDescriptor(serialName, PrimitiveKind.STRING) } override fun deserialize(decoder: Decoder): NotBlankString = decoder .decodeString() .toNotBlankString() .getOrNull() ?: serializationError(ErrorMessage.blankString) }
51
null
6
90
80422a2af60d0aa24f9d86e859f985678bad52b8
7,729
types
MIT License
zoe-cli/src/commands/schemas.kt
adevinta
243,047,314
false
null
// Copyright (c) 2020 Adevinta. // // 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 com.adevinta.oss.zoe.cli.commands import com.adevinta.oss.zoe.cli.commands.DeploySchema.SubjectNameStrategyEnum.* import com.adevinta.oss.zoe.cli.utils.fetch import com.adevinta.oss.zoe.cli.utils.globalTermColors import com.adevinta.oss.zoe.core.functions.SchemaContent import com.adevinta.oss.zoe.core.functions.SchemaContent.AvdlSchema import com.adevinta.oss.zoe.core.functions.SchemaContent.AvscSchema import com.adevinta.oss.zoe.core.functions.SubjectNameStrategy import com.adevinta.oss.zoe.core.functions.TopicNameStrategySuffix import com.adevinta.oss.zoe.core.utils.toJsonNode import com.adevinta.oss.zoe.service.ZoeService import com.adevinta.oss.zoe.service.utils.userError import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.optional import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.choice import com.github.ajalt.clikt.parameters.types.file import com.github.ajalt.clikt.parameters.types.int import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.koin.core.KoinComponent import org.koin.core.inject import java.io.InputStream class SchemasCommand : CliktCommand( name = "schemas", help = "List, describe or deploy schemas", printHelpOnEmptyArgs = true ) { override fun run() {} } class ListSchemas : CliktCommand(name = "list"), KoinComponent { private val ctx by inject<CliContext>() private val service by inject<ZoeService>() private val filter: Regex? by option("-m", "--matching", help = "Filter only subject names matching the given pattern") .convert { it.toRegex() } private val limit: Int? by option("-n", "--limit", help = "Limit the number of returned results").int() override fun run() = runBlocking { val subjects = service.listSchemas(ctx.cluster, filter, limit).subjects ctx.term.output.format(mapOf("subjects" to subjects).toJsonNode()) { echo(it) } } } class DescribeSchema : CliktCommand(name = "describe"), KoinComponent { private val subject: String by argument("subject", help = "Subject name to describe") private val ctx by inject<CliContext>() private val service by inject<ZoeService>() override fun run() = runBlocking { val response = service.describeSchema(ctx.cluster, subject) ctx.term.output.format(response.toJsonNode()) { echo(it) } } } class DeploySchema : CliktCommand( name = "deploy", help = """Deploy a schema to the registry""", printHelpOnEmptyArgs = true, epilog = with(globalTermColors) { """``` |Examples: | | Deploy a schema named 'SerenityResult' from an .avdl file: | > ${bold("""zoe -c local schemas deploy --avdl --from-file schema.avdl --name SerenityResult""")} | | Use the dry-run mode to check the compiled schema : | > ${bold("""zoe -c local schemas deploy --avdl --from-file schema.avdl --name SerenityResult""")} | |```""".trimMargin() } ), KoinComponent { enum class SubjectNameStrategyEnum { Topic, Record, TopicRecord } enum class SchemaType { Avsc, Avdl } private val strategy by option("--strategy", help = "Subject naming strategy") .choice("topic" to Topic, "record" to Record, "topicRecord" to TopicRecord) .default(Record) private val fromStdin by option("--from-stdin", help = "Consume data from stdin").flag(default = false) private val fromFile by option("--from-file", help = "Consume data from a json file") .file(mustExist = true, canBeFile = true, mustBeReadable = true) private val topic by option("--topic", help = "Target topic") private val suffix by option("--suffix", help = "Suffix for subject name") .choice(TopicNameStrategySuffix.values().map { it.code to it }.toMap()) private val content by argument("schema", help = "Schema json content").optional() private val type by option().switch(SchemaType.values().map { "--${it.name.toLowerCase()}" to it }.toMap()) .default(SchemaType.Avsc) private val name by option("--name", help = "Name of the schema in the avdl file (required when using --avdl)") private val dryRun by option("--dry-run", help = "Do not actually create the schema").flag(default = false) private val ctx by inject<CliContext>() private val service by inject<ZoeService>() override fun run() = runBlocking { val strategy: SubjectNameStrategy = strategy.let { when (it) { Topic -> { requireNotNull(topic) { "--topic needs to be supplied when using strategy : $it" } requireNotNull(suffix) { "--suffix needs to be supplied when using strategy : $it" } SubjectNameStrategy.TopicNameStrategy(topic!!, suffix!!) } Record -> SubjectNameStrategy.RecordNameStrategy TopicRecord -> { requireNotNull(topic) { "--topic needs to be supplied when using strategy : $it" } SubjectNameStrategy.TopicRecordNameStrategy(topic!!) } } } val schema: SchemaContent = kotlin.run { val input: InputStream = when { fromStdin -> System.`in` fromFile != null -> fromFile!!.inputStream() content != null -> content!!.byteInputStream(Charsets.UTF_8) else -> userError("supply the schema as an argument or use one of : '--from-stdin', '--from-file'") } val content = fetch(input, streaming = false).first() when (type) { SchemaType.Avsc -> AvscSchema(content) SchemaType.Avdl -> AvdlSchema( content, name ?: userError("--name is required when using '$type'") ) } } val subject = service.deploySchema(ctx.cluster, schema, strategy, dryRun) ctx.term.output.format(subject.toJsonNode()) { echo(it) } } } fun schemasCommand() = SchemasCommand().subcommands( ListSchemas(), DescribeSchema(), DeploySchema() )
9
Kotlin
21
273
d8ade76e2a74d96b97a8a08d82d27407539f1ff4
7,462
zoe
MIT License
feature/home/src/main/kotlin/com/stepmate/home/screen/homeSetting/HomeSettingScreen.kt
step-Mate
738,437,093
false
{"Kotlin": 738811}
package com.stepmate.home.screen.homeSetting import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.stepmate.core.SnackBarMessage import com.stepmate.design.R import com.stepmate.design.component.DescriptionLargeText import com.stepmate.design.component.HorizontalDivider import com.stepmate.design.component.HorizontalWeightSpacer import com.stepmate.design.component.StepMateNumberPicker import com.stepmate.design.component.StepMateTopBar import com.stepmate.design.component.VerticalSpacer import com.stepmate.design.component.clickableAvoidingDuplication import com.stepmate.design.component.layout.DefaultLayout import com.stepmate.design.theme.StepMateTheme import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @Composable internal fun HomeSettingScreen( homeSettingViewModel: HomeSettingViewModel = hiltViewModel(), popBackStack: () -> Unit, showSnackBar: (SnackBarMessage) -> Unit, ) { HomeSettingScreen( setStepGoal = homeSettingViewModel::setStepGoal, popBackStack = popBackStack, showSnackBar = showSnackBar, ) } @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable private fun HomeSettingScreen( coroutineScope: CoroutineScope = rememberCoroutineScope(), setStepGoal: (Int) -> Unit, popBackStack: () -> Unit, showSnackBar: (SnackBarMessage) -> Unit, ) { val sheetState = rememberModalBottomSheetState() val pagerItems = remember { (0..50000 step 100).toList() } val pagerState = rememberPagerState(50) { 50000 / 100 + 1 } var isSheetVisible by remember { mutableStateOf(false) } StepMateNumberPicker( isSheetVisible = isSheetVisible, items = pagerItems, pagerState = pagerState, sheetState = sheetState, updateIsSheetVisibility = { bool -> isSheetVisible = bool } ) { val goal = pagerItems[pagerState.currentPage] setStepGoal(goal) showSnackBar( SnackBarMessage( headerMessage = "걸음수 목표치가 설정되었어요.", contentMessage = "목표치: [$goal]" ) ) } DefaultLayout( topBar = { StepMateTopBar( icon = R.drawable.ic_arrow_left_small, onClick = popBackStack, ) } ) { Column( modifier = Modifier .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(20.dp)) .padding(vertical = 12.dp, horizontal = 8.dp), ) { DescriptionLargeText( text = "목표치 설정", color = MaterialTheme.colorScheme.onSurfaceVariant ) VerticalSpacer(height = 4.dp) VerticalSpacer(height = 32.dp) Row( modifier = Modifier .fillMaxWidth() .height(32.dp) .clickableAvoidingDuplication { coroutineScope.launch { isSheetVisible = true sheetState.expand() } }, verticalAlignment = Alignment.CenterVertically, ) { DescriptionLargeText( text = "걸음수 목표치 설정", modifier = Modifier, ) HorizontalWeightSpacer(float = 1f) Icon( painter = painterResource(id = R.drawable.ic_arrow_right_small), contentDescription = "RightArrowIcon", tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } VerticalSpacer(height = 8.dp) HorizontalDivider() } } } @Composable @Preview private fun PreviewHomeSettingScreen() = StepMateTheme { HomeSettingScreen( setStepGoal = {}, popBackStack = {}, showSnackBar = {}, ) }
3
Kotlin
0
0
f5e6f25014466d6a884ac3316ee7c556ca58c8f1
5,165
Android
Apache License 2.0
navigation/src/main/java/com/parimatch/navigation/screen/Screen.kt
parimatch-tech
509,548,833
false
null
package com.parimatch.navigation.screen import com.parimatch.navigation.receiver.Target import com.parimatch.navigation.reflection.Form import com.parimatch.navigation.reflection.StateBundler import kotlinx.coroutines.flow.StateFlow import java.util.UUID /** * Reflection constructor in [StateBundler]. */ internal data class Screen<A : Any>( val uid: String, val context: ScreenContext, val description: ScreenDescription<A, *, *>, val arg: A, val afterCloseTarget: Target<*, *, *>? = null // todo relocate to separate part ) { val form: Form get() = description.produceForm(arg) val limitation: StateFlow<Boolean> get() = description.produceLimitation(arg) companion object { fun <A : Any, I : Any, C : ScreenContract<A, I>> from( screenDescription: ScreenDescription<A, I, C>, target: Target<A, I, C>, afterCloseTarget: Target<*, *, *>? = null ): Screen<A> { return Screen( uid = UUID.randomUUID().toString(), context = target.context ?: screenDescription.defaultContext, description = screenDescription, arg = target.arg, afterCloseTarget = afterCloseTarget ) } } }
0
Kotlin
0
0
a074b34e86a18884982b515d228faa26d04e2f21
1,278
priroda
Apache License 2.0
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package01/Foo00145.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.singlemoduleapp.package01 class Foo00145 { fun method0() { Foo00144().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
app/src/main/java/com/peteralexbizjak/europaopen/models/statistics/Domain.kt
sunderee
375,731,952
false
null
package com.peteralexbizjak.europaopen.models.statistics import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Domain( val id: Int, val title: String, val indicators: List<Indicator> ) : Parcelable
0
Kotlin
0
2
968705e28f1a5ae012338452d8100f364e886a20
243
EuropaOpen
MIT License
libraries/architecture/src/main/kotlin/io/element/android/libraries/architecture/AsyncAction.kt
element-hq
546,522,002
false
{"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
/* * Copyright (c) 2023 New Vector Ltd * * 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 io.element.android.libraries.architecture import androidx.compose.runtime.MutableState import androidx.compose.runtime.Stable import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Sealed type that allows to model an asynchronous operation triggered by the user. */ @Stable sealed interface AsyncAction<out T> { /** * Represents an uninitialized operation (i.e. yet to be run by the user). */ data object Uninitialized : AsyncAction<Nothing> /** * Represents an operation that is currently waiting for user confirmation. */ data object Confirming : AsyncAction<Nothing> /** * Represents an operation that is currently ongoing. */ data object Loading : AsyncAction<Nothing> /** * Represents a failed operation. * * @property error the error that caused the operation to fail. */ data class Failure( val error: Throwable, ) : AsyncAction<Nothing> /** * Represents a successful operation. * * @param T the type of data returned by the operation. * @property data the data returned by the operation. */ data class Success<out T>( val data: T, ) : AsyncAction<T> /** * Returns the data returned by the operation, or null otherwise. */ fun dataOrNull(): T? = when (this) { is Success -> data else -> null } /** * Returns the error that caused the operation to fail, or null otherwise. */ fun errorOrNull(): Throwable? = when (this) { is Failure -> error else -> null } fun isUninitialized(): Boolean = this == Uninitialized fun isConfirming(): Boolean = this == Confirming fun isLoading(): Boolean = this == Loading fun isFailure(): Boolean = this is Failure fun isSuccess(): Boolean = this is Success } suspend inline fun <T> MutableState<AsyncAction<T>>.runCatchingUpdatingState( errorTransform: (Throwable) -> Throwable = { it }, block: () -> T, ): Result<T> = runUpdatingState( state = this, errorTransform = errorTransform, resultBlock = { runCatching { block() } }, ) suspend inline fun <T> (suspend () -> T).runCatchingUpdatingState( state: MutableState<AsyncAction<T>>, errorTransform: (Throwable) -> Throwable = { it }, ): Result<T> = runUpdatingState( state = state, errorTransform = errorTransform, resultBlock = { runCatching { this() } }, ) suspend inline fun <T> MutableState<AsyncAction<T>>.runUpdatingState( errorTransform: (Throwable) -> Throwable = { it }, resultBlock: () -> Result<T>, ): Result<T> = runUpdatingState( state = this, errorTransform = errorTransform, resultBlock = resultBlock, ) /** * Calls the specified [Result]-returning function [resultBlock] * encapsulating its progress and return value into an [AsyncAction] while * posting its updates to the MutableState [state]. * * @param T the type of data returned by the operation. * @param state the [MutableState] to post updates to. * @param errorTransform a function to transform the error before posting it. * @param resultBlock a suspending function that returns a [Result]. * @return the [Result] returned by [resultBlock]. */ @OptIn(ExperimentalContracts::class) @Suppress("REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE") suspend inline fun <T> runUpdatingState( state: MutableState<AsyncAction<T>>, errorTransform: (Throwable) -> Throwable = { it }, resultBlock: suspend () -> Result<T>, ): Result<T> { contract { callsInPlace(resultBlock, InvocationKind.EXACTLY_ONCE) } state.value = AsyncAction.Loading return resultBlock().fold( onSuccess = { state.value = AsyncAction.Success(it) Result.success(it) }, onFailure = { val error = errorTransform(it) state.value = AsyncAction.Failure( error = error, ) Result.failure(error) } ) }
263
Kotlin
86
955
31d0621fa15fe153bfd36104e560c9703eabe917
4,737
element-x-android
Apache License 2.0
Barlom-Foundation-JVM/src/main/kotlin/i/barlom/infrastructure/codegen/blocks/NewLineSeparatedCodeBlock.kt
martin-nordberg
82,682,055
false
null
// // (C) Copyright 2019 <NAME> // Apache 2.0 License // package i.barlom.infrastructure.codegen.blocks import i.barlom.infrastructure.codegen.chunks.ICodeChunk //--------------------------------------------------------------------------------------------------------------------- internal class NewLineSeparatedCodeBlock(chunks: List<ICodeChunk>) : AbstractCodeBlock() { init { for (chunk in chunks) { add(chunk) } } override val debugNodeName = "NewLineSeparatedBlock" override fun getSeparator(density: ECodeDensity): String = "\n" } //---------------------------------------------------------------------------------------------------------------------
0
Kotlin
0
0
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
723
ZZ-Barlom
Apache License 2.0
resource-kotlin-mpp/src/main/java/ru/pocketbyte/locolaser/kotlinmpp/KotlinMultiplatformResourcesConfigBuilder.kt
PocketByte
79,646,282
false
null
package ru.pocketbyte.locolaser.kotlinmpp import ru.pocketbyte.locolaser.config.resources.BaseResourcesConfig import ru.pocketbyte.locolaser.config.resources.ResourcesConfig import ru.pocketbyte.locolaser.config.resources.ResourcesSetConfig import java.io.File class KotlinMultiplatformResourcesConfigBuilder { open class BaseKmpBuilder { /** * Path to directory with source code. */ var sourcesDir: File? = null /** * Filter function. * If defined, only strings that suits the filter will be added as Repository fields. */ var filter: ((key: String) -> Boolean)? = null /** * If defined, only strings with keys that matches RegExp will be added as Repository fields. * @param regExp RegExp String. Only strings with keys that matches RegExp will be added as Repository fields. */ fun filter(regExp: String) { filter = BaseResourcesConfig.regExFilter(regExp) } } class KmpInterfaceBuilder: BaseKmpBuilder() { /** * Canonical name of the Repository interface that should be generated. */ var interfaceName: String? = null } class KmpClassBuilder: BaseKmpBuilder() { /** * Canonical name of the Repository class that should be generated. */ var className: String? = null } /** * Canonical name of the Repository interface that should be implemented by generated classes. * If empty there will no interfaces implemented by generated Repository classes. */ var repositoryInterface: String? = null /** * Canonical name of the Repository class that should be generated for each platform. */ var repositoryClass: String? = null /** * Path to src directory. */ var srcDir: File? = null /** * Path to src directory. */ fun srcDir(path: String) { srcDir = File(path) } /** * Filter function. * If defined, only strings that suits the filter will be added as Repository fields. */ var filter: ((key: String) -> Boolean)? = null /** * If defined, only strings with keys that matches RegExp will be added as Repository fields. * @param regExp RegExp String. Only strings with keys that matches RegExp will be added as Repository fields. */ fun filter(regExp: String) { filter = BaseResourcesConfig.regExFilter(regExp) } private var commonPlatform: KmpInterfaceBuilder? = null private var androidPlatform: KmpClassBuilder? = null private var iosPlatform: KmpClassBuilder? = null private var jsPlatform: KmpClassBuilder? = null /** * Configure Repository interface in common module. */ fun common(action: KmpInterfaceBuilder.() -> Unit = {}) { commonPlatform = KmpInterfaceBuilder().apply { action(this) } } /** * Configure Repository implementation for Android platform. * There is no Android implementation will be generated if Android platform wasn't be configured. */ fun android(action: KmpClassBuilder.() -> Unit = {}) { androidPlatform = KmpClassBuilder().apply { action(this) } } /** * Configure Repository implementation for iOS platform. * There is no iOS implementation will be generated if iOS platform wasn't be configured. */ fun ios(action: KmpClassBuilder.() -> Unit = {}) { iosPlatform = KmpClassBuilder().apply { action(this) } } /** * Configure Repository implementation for JS platform. * There is no JS implementation will be generated if JS platform wasn't be configured. */ fun js(action: KmpClassBuilder.() -> Unit = {}) { jsPlatform = KmpClassBuilder().apply { action(this) } } internal fun build(): ResourcesConfig { val commonConfig = KotlinCommonResourcesConfig() val androidConfig = if (androidPlatform != null) KotlinAndroidResourcesConfig() else null val iosConfig = if (iosPlatform != null) KotlinIosResourcesConfig() else null val jsConfig = if (jsPlatform != null) KotlinJsResourcesConfig() else null repositoryInterface?.also { commonConfig.resourceName = it } repositoryClass?.also { className -> val applyAction: (it: KotlinBaseImplResourcesConfig) -> Unit = { it.resourceName = className } androidConfig?.also { applyAction(it) } iosConfig?.also { applyAction(it) } jsConfig?.also { applyAction(it) } } srcDir?.also { commonConfig.resourcesDir = File(it, "./commonMain/kotlin/") androidConfig?.resourcesDir = File(it, "./androidMain/kotlin/") iosConfig?.resourcesDir = File(it, "./iosMain/kotlin/") jsConfig?.resourcesDir = File(it, "./jsMain/kotlin/") } filter?.also { commonConfig.filter = it androidConfig?.filter = it iosConfig?.filter = it jsConfig?.filter = it } commonPlatform?.also { commonConfig.fillFrom(it) } androidPlatform?.also { androidConfig?.fillFrom(it) androidConfig?.implements = commonConfig.resourceName } iosPlatform?.also { iosConfig?.fillFrom(it) iosConfig?.implements = commonConfig.resourceName } jsPlatform?.also { jsConfig?.fillFrom(it) jsConfig?.implements = commonConfig.resourceName } return ResourcesSetConfig( LinkedHashSet<ResourcesConfig>().apply { add(commonConfig) androidConfig?.also { add(it) } iosConfig?.also { add(it) } jsConfig?.also { add(it) } } ) } private fun BaseResourcesConfig.fillFrom(platformBuilder: BaseKmpBuilder) { if (platformBuilder is KmpInterfaceBuilder) { platformBuilder.interfaceName?.let { resourceName = it } } else if (platformBuilder is KmpClassBuilder) { platformBuilder.className?.let { resourceName = it } } platformBuilder.sourcesDir?.let { resourcesDir = it } platformBuilder.filter?.let { val parentFiler = filter filter = if (parentFiler == null) { it } else { { key: String -> parentFiler(key) && it(key) } } } } }
5
Kotlin
1
27
502dc5c55430cc057b58dae542669169ef3ee100
6,683
LocoLaser
Apache License 2.0
resource-kotlin-mpp/src/main/java/ru/pocketbyte/locolaser/kotlinmpp/KotlinMultiplatformResourcesConfigBuilder.kt
PocketByte
79,646,282
false
null
package ru.pocketbyte.locolaser.kotlinmpp import ru.pocketbyte.locolaser.config.resources.BaseResourcesConfig import ru.pocketbyte.locolaser.config.resources.ResourcesConfig import ru.pocketbyte.locolaser.config.resources.ResourcesSetConfig import java.io.File class KotlinMultiplatformResourcesConfigBuilder { open class BaseKmpBuilder { /** * Path to directory with source code. */ var sourcesDir: File? = null /** * Filter function. * If defined, only strings that suits the filter will be added as Repository fields. */ var filter: ((key: String) -> Boolean)? = null /** * If defined, only strings with keys that matches RegExp will be added as Repository fields. * @param regExp RegExp String. Only strings with keys that matches RegExp will be added as Repository fields. */ fun filter(regExp: String) { filter = BaseResourcesConfig.regExFilter(regExp) } } class KmpInterfaceBuilder: BaseKmpBuilder() { /** * Canonical name of the Repository interface that should be generated. */ var interfaceName: String? = null } class KmpClassBuilder: BaseKmpBuilder() { /** * Canonical name of the Repository class that should be generated. */ var className: String? = null } /** * Canonical name of the Repository interface that should be implemented by generated classes. * If empty there will no interfaces implemented by generated Repository classes. */ var repositoryInterface: String? = null /** * Canonical name of the Repository class that should be generated for each platform. */ var repositoryClass: String? = null /** * Path to src directory. */ var srcDir: File? = null /** * Path to src directory. */ fun srcDir(path: String) { srcDir = File(path) } /** * Filter function. * If defined, only strings that suits the filter will be added as Repository fields. */ var filter: ((key: String) -> Boolean)? = null /** * If defined, only strings with keys that matches RegExp will be added as Repository fields. * @param regExp RegExp String. Only strings with keys that matches RegExp will be added as Repository fields. */ fun filter(regExp: String) { filter = BaseResourcesConfig.regExFilter(regExp) } private var commonPlatform: KmpInterfaceBuilder? = null private var androidPlatform: KmpClassBuilder? = null private var iosPlatform: KmpClassBuilder? = null private var jsPlatform: KmpClassBuilder? = null /** * Configure Repository interface in common module. */ fun common(action: KmpInterfaceBuilder.() -> Unit = {}) { commonPlatform = KmpInterfaceBuilder().apply { action(this) } } /** * Configure Repository implementation for Android platform. * There is no Android implementation will be generated if Android platform wasn't be configured. */ fun android(action: KmpClassBuilder.() -> Unit = {}) { androidPlatform = KmpClassBuilder().apply { action(this) } } /** * Configure Repository implementation for iOS platform. * There is no iOS implementation will be generated if iOS platform wasn't be configured. */ fun ios(action: KmpClassBuilder.() -> Unit = {}) { iosPlatform = KmpClassBuilder().apply { action(this) } } /** * Configure Repository implementation for JS platform. * There is no JS implementation will be generated if JS platform wasn't be configured. */ fun js(action: KmpClassBuilder.() -> Unit = {}) { jsPlatform = KmpClassBuilder().apply { action(this) } } internal fun build(): ResourcesConfig { val commonConfig = KotlinCommonResourcesConfig() val androidConfig = if (androidPlatform != null) KotlinAndroidResourcesConfig() else null val iosConfig = if (iosPlatform != null) KotlinIosResourcesConfig() else null val jsConfig = if (jsPlatform != null) KotlinJsResourcesConfig() else null repositoryInterface?.also { commonConfig.resourceName = it } repositoryClass?.also { className -> val applyAction: (it: KotlinBaseImplResourcesConfig) -> Unit = { it.resourceName = className } androidConfig?.also { applyAction(it) } iosConfig?.also { applyAction(it) } jsConfig?.also { applyAction(it) } } srcDir?.also { commonConfig.resourcesDir = File(it, "./commonMain/kotlin/") androidConfig?.resourcesDir = File(it, "./androidMain/kotlin/") iosConfig?.resourcesDir = File(it, "./iosMain/kotlin/") jsConfig?.resourcesDir = File(it, "./jsMain/kotlin/") } filter?.also { commonConfig.filter = it androidConfig?.filter = it iosConfig?.filter = it jsConfig?.filter = it } commonPlatform?.also { commonConfig.fillFrom(it) } androidPlatform?.also { androidConfig?.fillFrom(it) androidConfig?.implements = commonConfig.resourceName } iosPlatform?.also { iosConfig?.fillFrom(it) iosConfig?.implements = commonConfig.resourceName } jsPlatform?.also { jsConfig?.fillFrom(it) jsConfig?.implements = commonConfig.resourceName } return ResourcesSetConfig( LinkedHashSet<ResourcesConfig>().apply { add(commonConfig) androidConfig?.also { add(it) } iosConfig?.also { add(it) } jsConfig?.also { add(it) } } ) } private fun BaseResourcesConfig.fillFrom(platformBuilder: BaseKmpBuilder) { if (platformBuilder is KmpInterfaceBuilder) { platformBuilder.interfaceName?.let { resourceName = it } } else if (platformBuilder is KmpClassBuilder) { platformBuilder.className?.let { resourceName = it } } platformBuilder.sourcesDir?.let { resourcesDir = it } platformBuilder.filter?.let { val parentFiler = filter filter = if (parentFiler == null) { it } else { { key: String -> parentFiler(key) && it(key) } } } } }
5
Kotlin
1
27
502dc5c55430cc057b58dae542669169ef3ee100
6,683
LocoLaser
Apache License 2.0
app/src/main/java/com/atarious/map_location/Data/viewModels/CityViewModel.kt
AbdullahRamees
479,697,389
false
{"Kotlin": 28359}
package com.atarious.map_location.Data.viewModels import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.viewModelScope import com.atarious.map_location.Data.Repositories.CityRepository import com.atarious.map_location.Data.database.LocalDatabase import com.atarious.map_location.Data.tables.City import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class cityViewModel(application: Application):AndroidViewModel(application) { val allCity : LiveData<List<City>> val maxid : Int private val repository:CityRepository init{ val citydao = LocalDatabase.getDatabase(application).cityDao() repository = CityRepository(citydao) allCity = repository.AllCity maxid = repository.maxId } fun addCity(city: City){ viewModelScope.launch(Dispatchers.IO){ repository.AddCity(city) } } fun updatecity(city: City){ viewModelScope.launch (Dispatchers.IO){ repository.updateCity(city) } } fun deleteAll(){ viewModelScope.launch(Dispatchers.IO){ repository.deleteAll() } } fun deleteCity(ID:Int){ viewModelScope.launch(Dispatchers.IO){ repository.deleteCity(ID) } } fun Clear(){ viewModelScope.launch(Dispatchers.IO){ repository.Clear() } } }
0
Kotlin
0
0
1b773946c93e36cc08dc9b74045fb5481ca1a059
1,460
Map_Location
MIT License
domain/src/main/java/com/oguzdogdu/domain/usecase/home/GetPopularAndLatestUseCase.kt
oguzsout
616,912,430
false
{"Kotlin": 469164}
package com.oguzdogdu.domain.usecase.home import com.oguzdogdu.domain.model.home.HomeListItems import com.oguzdogdu.domain.wrapper.Resource import kotlinx.coroutines.flow.Flow interface GetPopularAndLatestUseCase { suspend operator fun invoke(type:String?): Flow<Resource<List<HomeListItems>?>> }
0
Kotlin
0
8
12d75ef6f5e4c0a8121b6ad9c880723f14c93b1e
301
Wallies
MIT License
platform/platform-impl/src/com/intellij/ui/list/targetPopup.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("TargetPopup") package com.intellij.ui.list import com.intellij.ide.ui.UISettings import com.intellij.navigation.TargetPresentation import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.ui.popup.IPopupChooserBuilder import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts.PopupTitle import com.intellij.util.concurrency.annotations.RequiresEdt import java.util.function.Consumer import java.util.function.Function import javax.swing.ListCellRenderer @RequiresEdt fun <T> createTargetPopup( @PopupTitle title: String, items: List<T>, presentations: List<TargetPresentation>, processor: Consumer<in T> ): JBPopup { return createTargetPopup( title = title, items = items.zip(presentations), presentationProvider = { it.second }, processor = { processor.accept(it.first) } ) } @RequiresEdt fun <T> createTargetPopup( @PopupTitle title: String, items: List<T>, presentationProvider: Function<in T, out TargetPresentation>, processor: Consumer<in T> ): JBPopup { return buildTargetPopup(items, presentationProvider, processor) .setTitle(title) .createPopup() } @RequiresEdt fun <T> buildTargetPopup( items: List<T>, presentationProvider: Function<in T, out TargetPresentation>, processor: Consumer<in T> ): IPopupChooserBuilder<T> { require(items.size > 1) { "Attempted to build a target popup with ${items.size} elements" } return JBPopupFactory.getInstance() .createPopupChooserBuilder(items) .setRenderer(createTargetPresentationRenderer(presentationProvider)) .setFont(EditorUtil.getEditorFont()) .withHintUpdateSupply() .setNamerForFiltering { item: T -> presentationProvider.apply(item).speedSearchText() }.setItemChosenCallback(processor::accept) } fun <T> createTargetPresentationRenderer(presentationProvider: Function<in T, out TargetPresentation>): ListCellRenderer<T> { return if (UISettings.instance.showIconInQuickNavigation) { TargetPresentationRenderer(presentationProvider) } else { TargetPresentationMainRenderer(presentationProvider) } } private fun TargetPresentation.speedSearchText(): String { val presentableText = presentableText val containerText = containerText return if (containerText == null) presentableText else "$presentableText $containerText" }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,581
intellij-community
Apache License 2.0
strikt-core/src/main/kotlin/strikt/assertions/Arrays.kt
robfletcher
131,475,396
false
null
package strikt.assertions import strikt.api.Assertion /** * Asserts that the subject's content is equal to that of [other] according to * [Array.contentEquals]. */ infix fun <T> Assertion.Builder<Array<out T>>.contentEquals(other: Array<out T>): Assertion.Builder<Array<out T>> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isObjectArrayEmpty") fun <T> Assertion.Builder<Array<T>>.isEmpty(): Assertion.Builder<Array<T>> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [BooleanArray.contentEquals]. */ infix fun Assertion.Builder<BooleanArray>.contentEquals(other: BooleanArray): Assertion.Builder<BooleanArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isBooleanArrayEmpty") fun Assertion.Builder<BooleanArray>.isEmpty(): Assertion.Builder<BooleanArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [ByteArray.contentEquals]. */ infix fun Assertion.Builder<ByteArray>.contentEquals(other: ByteArray): Assertion.Builder<ByteArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isByteArrayEmpty") fun Assertion.Builder<ByteArray>.isEmpty(): Assertion.Builder<ByteArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [ShortArray.contentEquals]. */ infix fun Assertion.Builder<ShortArray>.contentEquals(other: ShortArray): Assertion.Builder<ShortArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isShortArrayEmpty") fun Assertion.Builder<ShortArray>.isEmpty(): Assertion.Builder<ShortArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [IntArray.contentEquals]. */ infix fun Assertion.Builder<IntArray>.contentEquals(other: IntArray): Assertion.Builder<IntArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isIntArrayEmpty") fun Assertion.Builder<IntArray>.isEmpty(): Assertion.Builder<IntArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [LongArray.contentEquals]. */ infix fun Assertion.Builder<LongArray>.contentEquals(other: LongArray): Assertion.Builder<LongArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isLongArrayEmpty") fun Assertion.Builder<LongArray>.isEmpty(): Assertion.Builder<LongArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [FloatArray.contentEquals]. */ infix fun Assertion.Builder<FloatArray>.contentEquals(other: FloatArray): Assertion.Builder<FloatArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isFloatArrayEmpty") fun Assertion.Builder<FloatArray>.isEmpty(): Assertion.Builder<FloatArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [DoubleArray.contentEquals]. */ infix fun Assertion.Builder<DoubleArray>.contentEquals(other: DoubleArray): Assertion.Builder<DoubleArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("isDoubleArrayEmpty") fun Assertion.Builder<DoubleArray>.isEmpty(): Assertion.Builder<DoubleArray> = assertThat("array is empty") { it.isEmpty() } /** * Asserts that the subject's content is equal to that of [other] according to * [CharArray.contentEquals]. */ infix fun Assertion.Builder<CharArray>.contentEquals(other: CharArray): Assertion.Builder<CharArray> = assertThat("array content equals %s", other) { it.contentEquals(other) } /** * Asserts that the subject's content is empty. * @see Array.isEmpty */ @JvmName("is_ArrayEmpty") fun Assertion.Builder<CharArray>.isEmpty(): Assertion.Builder<CharArray> = assertThat("array is empty") { it.isEmpty() } /** * Maps an array to a list to make it possible to use the iterable matchers */ fun <T> Assertion.Builder<Array<T>>.toList(): Assertion.Builder<List<T>> = get("as list") { toList() }
30
Kotlin
45
408
0489303377a4bb0b2c3e21f9f0d1fbe7a9655e8e
5,094
strikt
Apache License 2.0
app/src/main/java/io/github/droidkaigi/confsched2018/di/RecycledViewPoolModule.kt
DroidKaigi
115,203,383
false
null
package io.github.droidkaigi.confsched2018.di import android.support.v7.widget.RecyclerView import dagger.Module import dagger.Provides // Share RecycledViewPool between content fragments of ViewPager. @Module class RecycledViewPoolModule { private val recycledViewPool = RecyclerView.RecycledViewPool() @Provides fun providesRecycledViewPool(): RecyclerView.RecycledViewPool = recycledViewPool }
30
null
337
1,340
f19dd63f8b691d44ba7f758d92c2ca615cdad08d
413
conference-app-2018
Apache License 2.0
mulighetsrommet-api/src/test/kotlin/no/nav/mulighetsrommet/api/repositories/TiltakstypeRepositoryTest.kt
navikt
435,813,834
false
null
package no.nav.mulighetsrommet.api.repositories import io.kotest.core.spec.style.FunSpec import io.kotest.core.test.TestCaseOrder import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import no.nav.mulighetsrommet.api.utils.* import no.nav.mulighetsrommet.database.kotest.extensions.FlywayDatabaseTestListener import no.nav.mulighetsrommet.database.kotest.extensions.createApiDatabaseTestSchema import no.nav.mulighetsrommet.domain.dbo.TiltakstypeDbo import java.time.LocalDate import java.time.LocalDateTime import java.util.* class TiltakstypeRepositoryTest : FunSpec({ testOrder = TestCaseOrder.Sequential val database = extension(FlywayDatabaseTestListener(createApiDatabaseTestSchema())) test("CRUD") { val tiltakstyper = TiltakstypeRepository(database.db) tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "Arbeidstrening", tiltakskode = "ARBTREN", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 15, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "Oppfølging", tiltakskode = "INDOPPFOLG", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) tiltakstyper.getAll().second shouldHaveSize 2 tiltakstyper.getAll( TiltakstypeFilter( search = "Førerhund", status = Status.AKTIV, kategori = null ) ).second shouldHaveSize 0 val arbeidstrening = tiltakstyper.getAll(TiltakstypeFilter(search = "Arbeidstrening", status = Status.AVSLUTTET, kategori = null)) arbeidstrening.second shouldHaveSize 1 arbeidstrening.second[0].navn shouldBe "Arbeidstrening" arbeidstrening.second[0].arenaKode shouldBe "ARBTREN" arbeidstrening.second[0].rettPaaTiltakspenger shouldBe true arbeidstrening.second[0].registrertIArenaDato shouldBe LocalDateTime.of(2022, 1, 11, 0, 0, 0) arbeidstrening.second[0].sistEndretIArenaDato shouldBe LocalDateTime.of(2022, 1, 15, 0, 0, 0) arbeidstrening.second[0].fraDato shouldBe LocalDate.of(2023, 1, 11) arbeidstrening.second[0].tilDato shouldBe LocalDate.of(2023, 1, 12) } context("filter") { database.db.clean() database.db.migrate() val tiltakstyper = TiltakstypeRepository(database.db) tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "Arbeidsforberedende trening", tiltakskode = "ARBFORB", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 15, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "Jobbklubb", tiltakskode = "JOBBK", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 15, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "Oppfølging", tiltakskode = "INDOPPFOLG", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) test("Filter for kun gruppetiltak returnerer bare gruppetiltak") { tiltakstyper.getAll( TiltakstypeFilter( search = null, status = Status.AVSLUTTET, kategori = Tiltakstypekategori.GRUPPE ) ).second shouldHaveSize 2 } test("Filter for kun individuelle tiltak returnerer bare individuelle tiltak") { tiltakstyper.getAll( TiltakstypeFilter( search = null, status = Status.AVSLUTTET, kategori = Tiltakstypekategori.INDIVIDUELL ) ).second shouldHaveSize 1 } test("Ingen filter for kategori returnerer både individuelle- og gruppetiltak") { tiltakstyper.getAll(TiltakstypeFilter(search = null, status = Status.AVSLUTTET, kategori = null)).second shouldHaveSize 3 } } context("pagination") { database.db.clean() database.db.migrate() val tiltakstyper = TiltakstypeRepository(database.db) (1..105).forEach { tiltakstyper.upsert( TiltakstypeDbo( id = UUID.randomUUID(), navn = "$it", tiltakskode = "$it", rettPaaTiltakspenger = true, registrertDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), sistEndretDatoIArena = LocalDateTime.of(2022, 1, 11, 0, 0, 0), fraDato = LocalDate.of(2023, 1, 11), tilDato = LocalDate.of(2023, 1, 12) ) ) } test("default pagination gets first 50 tiltak") { val (totalCount, items) = tiltakstyper.getAll() items.size shouldBe DEFAULT_PAGINATION_LIMIT items.first().navn shouldBe "1" items.last().navn shouldBe "49" totalCount shouldBe 105 } test("pagination with page 4 and size 20 should give tiltak with id 59-76") { val (totalCount, items) = tiltakstyper.getAll( paginationParams = PaginationParams( 4, 20 ) ) items.size shouldBe 20 items.first().navn shouldBe "59" items.last().navn shouldBe "76" totalCount shouldBe 105 } test("pagination with page 3 default size should give tiltak with id 95-99") { val (totalCount, items) = tiltakstyper.getAll( paginationParams = PaginationParams( 3 ) ) items.size shouldBe 5 items.first().navn shouldBe "95" items.last().navn shouldBe "99" totalCount shouldBe 105 } test("pagination with default page and size 200 should give tiltak with id 1-99") { val (totalCount, items) = tiltakstyper.getAll( paginationParams = PaginationParams( nullableLimit = 200 ) ) items.size shouldBe 105 items.first().navn shouldBe "1" items.last().navn shouldBe "99" totalCount shouldBe 105 } } })
1
Kotlin
1
3
4a9e295dcd541c61b6e31e92757a2f958c9b351b
7,890
mulighetsrommet
MIT License
openrndr-core/src/main/kotlin/org/openrndr/internal/Driver.kt
xabbu137
221,031,198
true
{"Kotlin": 780792, "Java": 570908, "GLSL": 38491, "ANTLR": 9333, "CSS": 4374, "Shell": 1474}
package org.openrndr.internal import org.openrndr.color.ColorRGBa import org.openrndr.draw.* import java.nio.Buffer /** * built-in shader generators */ interface ShaderGenerators { fun vertexBufferFragmentShader(shadeStructure: ShadeStructure): String fun vertexBufferVertexShader(shadeStructure: ShadeStructure): String fun imageFragmentShader(shadeStructure: ShadeStructure): String fun imageVertexShader(shadeStructure: ShadeStructure): String fun circleFragmentShader(shadeStructure: ShadeStructure): String fun circleVertexShader(shadeStructure: ShadeStructure): String fun fontImageMapFragmentShader(shadeStructure: ShadeStructure): String fun fontImageMapVertexShader(shadeStructure: ShadeStructure): String fun rectangleFragmentShader(shadeStructure: ShadeStructure): String fun rectangleVertexShader(shadeStructure: ShadeStructure): String fun expansionFragmentShader(shadeStructure: ShadeStructure): String fun expansionVertexShader(shadeStructure: ShadeStructure): String fun fastLineFragmentShader(shadeStructure: ShadeStructure): String fun fastLineVertexShader(shadeStructure: ShadeStructure): String fun meshLineFragmentShader(shadeStructure: ShadeStructure): String fun meshLineVertexShader(shadeStructure: ShadeStructure): String } /** * Driver interface. This is the internal interface */ interface Driver { val contextID: Long fun createShader(vsCode: String, fsCode: String): Shader fun createShadeStyleManager(vertexShaderGenerator: (ShadeStructure) -> String, fragmentShaderGenerator: (ShadeStructure) -> String): ShadeStyleManager fun createRenderTarget(width: Int, height: Int, contentScale: Double = 1.0, multisample: BufferMultisample = BufferMultisample.Disabled): RenderTarget fun createColorBuffer(width: Int, height: Int, contentScale: Double, format: ColorFormat, type: ColorType, multisample: BufferMultisample = BufferMultisample.Disabled): ColorBuffer fun createColorBufferFromUrl(url: String): ColorBuffer fun createColorBufferFromFile(filename: String): ColorBuffer fun createDepthBuffer(width: Int, height: Int, format: DepthFormat, multisample: BufferMultisample = BufferMultisample.Disabled): DepthBuffer fun createBufferTexture(elementCount: Int, format: ColorFormat, type: ColorType): BufferTexture fun createCubemap(width: Int, format: ColorFormat, type: ColorType): Cubemap fun createCubemapFromUrls(urls: List<String>): Cubemap fun createResourceThread(f: () -> Unit): ResourceThread fun createDrawThread() : DrawThread fun clear(r: Double, g: Double, b: Double, a: Double) fun clear(color: ColorRGBa) { clear(color.r, color.g, color.b, color.a) } fun createDynamicVertexBuffer(format: VertexFormat, vertexCount: Int): VertexBuffer fun createStaticVertexBuffer(format: VertexFormat, buffer: Buffer): VertexBuffer fun createDynamicIndexBuffer(elementCount: Int, type: IndexType): IndexBuffer fun drawVertexBuffer(shader: Shader, vertexBuffers: List<VertexBuffer>, drawPrimitive: DrawPrimitive, vertexOffset: Int, vertexCount: Int) fun drawIndexedVertexBuffer(shader: Shader, indexBuffer: IndexBuffer, vertexBuffers: List<VertexBuffer>, drawPrimitive: DrawPrimitive, indexOffset: Int, indexCount: Int) fun drawInstances(shader: Shader, vertexBuffers: List<VertexBuffer>, instanceAttributes: List<VertexBuffer>, drawPrimitive: DrawPrimitive, vertexOffset: Int, vertexCount: Int, instanceCount: Int) fun drawIndexedInstances(shader: Shader, indexBuffer: IndexBuffer, vertexBuffers: List<VertexBuffer>, instanceAttributes: List<VertexBuffer>, drawPrimitive: DrawPrimitive, indexOffset: Int, indexCount: Int, instanceCount: Int) fun setState(drawStyle: DrawStyle) val fontImageMapManager: FontMapManager val fontVectorMapManager: FontMapManager val shaderGenerators: ShaderGenerators val activeRenderTarget: RenderTarget /** * waits for all drawing to complete */ fun finish() fun internalShaderResource(resourceId: String): String companion object { lateinit var driver: Driver val instance: Driver get() = driver } } /** * Wait for the [Driver] to finish drawing */ fun finish() { Driver.instance.finish() }
0
Kotlin
0
0
fa9dbb6aae158da69acd1f1dcd79271184aa0973
4,556
openrndr
BSD 2-Clause FreeBSD License
app/src/main/java/cn/nekocode/murmur/ui/MainActivity.kt
achillh
76,178,569
true
{"Kotlin": 45109, "Java": 11465, "GLSL": 1040}
package cn.nekocode.murmur.ui import android.content.Context import android.os.Bundle import android.os.PersistableBundle import cn.nekocode.kotgo.component.ui.FragmentActivity import cn.nekocode.murmur.ui.main.MainFragment import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper /** * @author nekocode (<EMAIL>) */ class MainActivity: FragmentActivity() { override fun onCreatePresenter(presenterFactory: PresenterFactory) { } override fun attachBaseContext(newBase: Context) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setBackgroundDrawable(null) if (savedInstanceState == null) MainFragment.push(this) } }
0
Kotlin
0
0
b1267dcdc0853261efbd2c0e1cf63ac914d3e3f2
808
murmur
Apache License 2.0
Halachic Times/app/src/androidTest/java/com/github/times/ZmanimTests.kt
pnemonic78
121,489,129
false
{"Kotlin": 916005, "Java": 140420, "HTML": 5998, "Shell": 73}
package com.github.times import android.content.Context import androidx.test.core.app.ApplicationProvider import com.github.times.preference.SimpleZmanimPreferences import com.github.times.preference.ZmanimPreferences import java.util.Calendar import java.util.TimeZone import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Test class ZmanimTests { @Test fun molad2019() { val context = ApplicationProvider.getApplicationContext<Context>() assertNotNull(context) val preferences: ZmanimPreferences = SimpleZmanimPreferences(context) assertNotNull(preferences) val populater = ZmanimPopulater<ZmanimAdapter<ZmanViewHolder>>(context, preferences) assertNotNull(populater) populater.isInIsrael = true assertMolad(populater, 2018, Calendar.DECEMBER, 7, 22, 29) assertMolad(populater, 2019, Calendar.JANUARY, 6, 11, 13) assertMolad(populater, 2019, Calendar.FEBRUARY, 4, 23, 57) assertMolad(populater, 2019, Calendar.MARCH, 6, 12, 41) assertMolad(populater, 2019, Calendar.APRIL, 5, 1, 25) assertMolad(populater, 2019, Calendar.MAY, 4, 14, 10) assertMolad(populater, 2019, Calendar.JUNE, 3, 2, 54) assertMolad(populater, 2019, Calendar.JULY, 2, 15, 38) assertMolad(populater, 2019, Calendar.AUGUST, 1, 4, 22) assertMolad(populater, 2019, Calendar.AUGUST, 30, 17, 6) assertMolad(populater, 2019, Calendar.SEPTEMBER, 29, 5, 50) assertMolad(populater, 2019, Calendar.OCTOBER, 28, 18, 34) assertMolad(populater, 2019, Calendar.NOVEMBER, 27, 7, 18) assertMolad(populater, 2019, Calendar.DECEMBER, 26, 20, 2) } private fun assertMolad( populater: ZmanimPopulater<ZmanimAdapter<ZmanViewHolder>>, year: Int, month: Int, day: Int, hour: Int, minute: Int ) { val context = ApplicationProvider.getApplicationContext<Context>() assertNotNull(context) val settings: ZmanimPreferences = SimpleZmanimPreferences(context) assertNotNull(settings) val adapter = ZmanimAdapter<ZmanViewHolder>(context, settings) assertNotNull(adapter) assertEquals(0, adapter.itemCount) val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")) assertNotNull(cal) cal[year, month] = day populater.setCalendar(cal) populater.populate(adapter, false) assertNotEquals(0, adapter.itemCount) val item = adapter.getItemById(R.string.molad) assertNotNull(item) val molad = Calendar.getInstance(cal.timeZone) assertNotNull(molad) molad.timeInMillis = item!!.time assertEquals(year, molad[Calendar.YEAR]) assertEquals(month, molad[Calendar.MONTH]) assertEquals(day, molad[Calendar.DAY_OF_MONTH]) assertEquals(hour, molad[Calendar.HOUR_OF_DAY]) assertEquals(minute, molad[Calendar.MINUTE]) } @Test fun kosherCalendar() { val context = ApplicationProvider.getApplicationContext<Context>() assertNotNull(context) val preferences: ZmanimPreferences = SimpleZmanimPreferences(context) assertNotNull(preferences) val populater: ZmanimPopulater<*> = ZmanimPopulater<ZmanimAdapter<ZmanViewHolder>>(context, preferences) assertNotNull(populater) val complexZmanimCalendar = populater.calendar assertNotNull(complexZmanimCalendar) assertNotNull(complexZmanimCalendar.geoLocation) assertNotNull(complexZmanimCalendar.calendar) assertNotNull(complexZmanimCalendar.seaLevelSunrise) assertNotNull(complexZmanimCalendar.seaLevelSunset) } }
43
Kotlin
2
9
7fdabe5aea2a2002b9aff8ba6e89ba7223278f7f
3,790
HalachicTimes
Apache License 2.0
mocker-core/src/commonMain/kotlin/fr/speekha/httpmocker/scenario/DynamicMockProvider.kt
speekha
190,229,886
false
{"Gradle": 20, "YAML": 2, "Shell": 5, "Batchfile": 4, "Java Properties": 13, "Ignore List": 1, "EditorConfig": 1, "Text": 6, "Markdown": 3, "Kotlin": 176, "Proguard": 1, "JSON": 30, "XML": 36, "Java": 1}
/* * Copyright 2019-2020 David Blanc * * 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 fr.speekha.httpmocker.scenario import fr.speekha.httpmocker.io.HttpRequest import fr.speekha.httpmocker.model.ResponseDescriptor internal class DynamicMockProvider( private val callbacks: List<RequestCallback> ) : ScenarioProvider { override fun loadResponse(request: HttpRequest): ResponseDescriptor? = callbacks .asSequence() .mapNotNull { it.processRequest(request)?.copy(bodyFile = null) } .firstOrNull() override fun toString(): String = "dynamic mock configuration" }
1
null
1
1
bb4f8ea57f40fd149171632e86b63e2304d60402
1,124
httpmocker
Apache License 2.0
src/nl/hannahsten/texifyidea/run/sumatra/SumatraForwardSearchListener.kt
Hannah-Sten
62,398,769
false
{"Kotlin": 2697096, "TeX": 71181, "Lex": 31225, "HTML": 23552, "Python": 967, "Perl": 39}
package nl.hannahsten.texifyidea.run.sumatra import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.application.invokeLater import com.intellij.openapi.util.Key import nl.hannahsten.texifyidea.TeXception import nl.hannahsten.texifyidea.psi.LatexEnvironment import nl.hannahsten.texifyidea.run.latex.LatexRunConfiguration import nl.hannahsten.texifyidea.util.caretOffset import nl.hannahsten.texifyidea.util.files.document import nl.hannahsten.texifyidea.util.files.isRoot import nl.hannahsten.texifyidea.util.files.openedEditor import nl.hannahsten.texifyidea.util.files.psiFile import nl.hannahsten.texifyidea.util.name import nl.hannahsten.texifyidea.util.parentOfType import org.jetbrains.concurrency.runAsync /** * @author Sten Wessel */ class SumatraForwardSearchListener(val runConfig: LatexRunConfiguration, private val executionEnvironment: ExecutionEnvironment ) : ProcessListener { override fun processTerminated(event: ProcessEvent) { // First check if the user provided a custom path to SumatraPDF, if not, check if it is installed if (event.exitCode == 0 && (runConfig.sumatraPath != null || isSumatraAvailable)) { try { SumatraConversation.openFile(runConfig.outputFilePath, sumatraPath = runConfig.sumatraPath) } catch (ignored: TeXception) { } } // Forward search. invokeLater { val psiFile = runConfig.mainFile?.psiFile(executionEnvironment.project) ?: return@invokeLater val document = psiFile.document() ?: return@invokeLater val editor = psiFile.openedEditor() ?: return@invokeLater if (document != editor.document) { return@invokeLater } // Do not do forward search when editing the preamble. if (psiFile.isRoot()) { val element = psiFile.findElementAt(editor.caretOffset()) ?: return@invokeLater val latexEnvironment = element.parentOfType(LatexEnvironment::class) ?: return@invokeLater if (latexEnvironment.name()?.text != "document") { return@invokeLater } } val line = document.getLineNumber(editor.caretOffset()) + 1 runAsync { try { // Wait for sumatra pdf to start. 1250ms should be plenty. // Otherwise the person is out of luck ¯\_(ツ)_/¯ Thread.sleep(1250) // Never focus, because forward search will work fine without focus, and the user might want to continue typing after doing forward search/compiling SumatraConversation.forwardSearch(sourceFilePath = psiFile.virtualFile.path, line = line, focus = false) } catch (ignored: TeXception) { } } } // Reset to default runConfig.allowFocusChange = true } override fun onTextAvailable(p0: ProcessEvent, p1: Key<*>) { // Do nothing. } override fun processWillTerminate(p0: ProcessEvent, p1: Boolean) { // Do nothing. } override fun startNotified(p0: ProcessEvent) { // Do nothing. } }
99
Kotlin
87
891
986550410e2fea91d1e93abfc683db1c8527c9d9
3,430
TeXiFy-IDEA
MIT License
compiler/testData/diagnostics/tests/multiplatform/arrayLimitationsInJvm.ll.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}
// LANGUAGE: +NullableNothingInReifiedPosition // MODULE: m1-common // FILE: common.kt fun foo(): Array<Nothing?> = arrayOf(null, null) fun <T : Array<*>> bar(arg: T) {} // MODULE: m2-jvm()()(m1-common) fun test() { val res = <!UNSUPPORTED!>foo<!>() <!UNSUPPORTED!>bar<!>(<!UNSUPPORTED!>res<!>) }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
309
kotlin
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/evmnetwork/addrpc/AddRpcModule.kt
horizontalsystems
142,825,178
false
null
package com.wikicious.app.modules.evmnetwork import android.os.Bundle import androidx.core.os.bundleOf import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.wikicious.app.core.App import io.horizontalsystems.core.parcelable import io.horizontalsystems.marketkit.models.Blockchain object EvmNetworkModule { fun args(blockchain: Blockchain): Bundle { return bundleOf("blockchain" to blockchain) } class Factory(arguments: Bundle) : ViewModelProvider.Factory { private val blockchain = arguments.parcelable<Blockchain>("blockchain")!! @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return EvmNetworkViewModel(blockchain, App.evmSyncSourceManager) as T } } }
57
null
340
778
454cb88a3f4687d77ffc3d2d878462f23b4b9dab
810
unstoppable-wallet-android
MIT License
mobile/src/main/java/com/siliconlabs/bledemo/home_screen/base/BaseServiceDependentMainMenuFragment.kt
SiliconLabs
85,345,875
false
null
package com.siliconlabs.bledemo.home_screen.base import android.os.Build import android.os.Bundle import android.view.View import android.widget.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.siliconlabs.bledemo.home_screen.viewmodels.MainActivityViewModel import com.siliconlabs.bledemo.home_screen.views.BluetoothEnableBar import com.siliconlabs.bledemo.home_screen.views.LocationEnableBar import com.siliconlabs.bledemo.home_screen.views.LocationPermissionBar import com.siliconlabs.bledemo.home_screen.views.BluetoothPermissionsBar abstract class BaseServiceDependentMainMenuFragment : BaseMainMenuFragment() { protected open val bluetoothDependent: BluetoothDependent? = null protected open val locationDependent: LocationDependent? = null protected var activityViewModel: MainActivityViewModel? = null protected fun toggleBluetoothBar(isOn: Boolean, bar: BluetoothEnableBar) { bar.visibility = if (isOn) View.GONE else View.VISIBLE if (!isOn) bar.resetState() } protected fun toggleBluetoothPermissionsBar(arePermissionsGranted: Boolean, bar: BluetoothPermissionsBar) { bar.visibility = if (arePermissionsGranted) View.GONE else View.VISIBLE } protected fun toggleLocationBar(isOn: Boolean, bar: LocationEnableBar) { bar.visibility = if (isOn) View.GONE else View.VISIBLE } protected fun toggleLocationPermissionBar(isPermissionGranted: Boolean, bar: LocationPermissionBar) { bar.visibility = if (isPermissionGranted) View.GONE else View.VISIBLE } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.let { activityViewModel = ViewModelProvider(it).get(MainActivityViewModel::class.java) } observeChanges() setupWarningBarsButtons() } override fun onResume() { super.onResume() bluetoothDependent?.refreshBluetoothDependentUi(isBluetoothOperationPossible()) } private fun observeChanges() { activity?.let { activityViewModel?.isBluetoothOn?.observe(viewLifecycleOwner, Observer { isOn -> bluetoothDependent?.onBluetoothStateChanged(isOn) }) activityViewModel?.areBluetoothPermissionGranted?.observe(viewLifecycleOwner, Observer { areGranted -> bluetoothDependent?.onBluetoothPermissionsStateChanged(areGranted) }) activityViewModel?.isLocationOn?.observe(viewLifecycleOwner, Observer { isOn -> locationDependent?.onLocationStateChanged(isOn) }) activityViewModel?.isLocationPermissionGranted?.observe(viewLifecycleOwner, Observer { isGranted -> locationDependent?.onLocationPermissionStateChanged(isGranted) }) } } private fun setupWarningBarsButtons() { locationDependent?.let { it.setupLocationBarButtons() it.setupLocationPermissionBarButtons() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { bluetoothDependent?.setupBluetoothPermissionsBarButtons() } } fun showToastLengthShort(message: String) { activity?.runOnUiThread { Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() } } fun showToastLengthLong(message: String) { activity?.runOnUiThread { Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() } } protected fun isBluetoothOperationPossible() : Boolean { return activityViewModel?.let { it.getIsBluetoothOn() && it.getAreBluetoothPermissionsGranted() } ?: false } }
7
Kotlin
70
96
2d3bc7b9fe358bc2f8b988479acfd8fc40794101
3,756
EFRConnect-android
Apache License 2.0
data/src/main/kotlin/io/petros/github/data/network/rest/response/repository/RepoDetails.kt
ParaskP7
140,927,471
false
{"Kotlin": 118109}
package io.petros.github.data.network.rest.response.repository data class RepoDetails( val id: Int, val subscribers_count: Int )
0
Kotlin
1
9
ad9c53165db32af9ca08e4ae3ca4ea9b30e24d2e
138
sample-code-github
Apache License 2.0
thisboot/src/main/kotlin/com/brageast/blog/thisboot/service/ArticleService.kt
chenmoand
208,778,754
false
{"TypeScript": 45692, "Kotlin": 35290, "JavaScript": 15070, "Less": 11069, "HTML": 8617, "Java": 149}
package com.brageast.blog.thisboot.service import com.brageast.blog.thisboot.entity.Article import org.bson.types.ObjectId import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.core.publisher.Mono interface ArticleService { fun insert(article: Article): Mono<Article> fun findAll(): Flux<Article> fun findWithPagination(page: Int, size: Int): Flux<Article> fun updateOrInsert(article: Article): Mono<Article> fun findById(id: String): Mono<Article> fun findById(id: ObjectId): Mono<Article> fun deleteById(id: ObjectId): Mono<Void> fun getSize(): Mono<Long> }
9
TypeScript
1
2
0819b24e15843546d0b2d338ad5673b3901dfd4d
636
thisme
MIT License
src/main/kotlin/io/github/sergkhram/idbClient/requests/settings/RevokeRequest.kt
SergKhram
524,131,579
false
null
package io.github.sergkhram.idbClient.requests.settings import idb.RevokeResponse import io.github.sergkhram.idbClient.entities.GrpcClient import io.github.sergkhram.idbClient.entities.requestsBody.settings.Permission import io.github.sergkhram.idbClient.requests.IdbRequest class RevokeRequest( private val bundleId: String = "", private val permissions: List<Permission> = emptyList(), private val scheme: String = "" ): IdbRequest<RevokeResponse>() { override suspend fun execute(client: GrpcClient): RevokeResponse { return client.stub.revoke( idb.RevokeRequest.newBuilder().setBundleId(bundleId).addAllPermissionsValue(permissions.map { it.value }).setScheme(scheme).build() ) } }
0
Kotlin
0
5
355102d6c7220f484210938772b2e84daa58ab36
727
IdbClient
Apache License 2.0
software-design/assertions/src/test/kotlin/com/github/nothingelsematters/lrucache/LinkedHashMapLruCache.kt
nothingelsematters
135,926,684
false
null
package com.github.nothingelsematters.lrucache import java.util.LinkedHashMap private const val loadFactor = 0.75f private const val accessOrder = true class LinkedHashMapLruCache<K, V>(val capacity: Int = 256) : LinkedHashMap<K, V>(capacity, loadFactor, accessOrder), Cache<K, V> { override fun set(key: K, value: V) { put(key, value) } override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, V>?) = size > capacity }
1
null
3
5
d442a3d25b579b96c6abda13ed3f7e60d1747b53
458
university
Do What The F*ck You Want To Public License
solid-material-api/src/main/kotlin/io/github/solid/resourcepack/material/SolidEntityMaterialTexture.kt
solid-resourcepack
838,892,385
false
{"Kotlin": 722691}
package io.github.solid.resourcepack.material import kotlin.Lazy import net.kyori.adventure.key.Key public enum class SolidEntityMaterialTexture( public val key: Lazy<Key>, ) { WIND(lazy { Key.key("minecraft:entity/conduit/wind") }), WIND_VERTICAL(lazy { Key.key("minecraft:entity/conduit/wind_vertical") }), BUTCHER(lazy { Key.key("minecraft:entity/zombie_villager/profession/butcher") }), FARMER(lazy { Key.key("minecraft:entity/zombie_villager/profession/farmer") }), FISHERMAN(lazy { Key.key("minecraft:entity/zombie_villager/profession/fisherman") }), FLETCHER(lazy { Key.key("minecraft:entity/zombie_villager/profession/fletcher") }), LIBRARIAN(lazy { Key.key("minecraft:entity/zombie_villager/profession/librarian") }), SHEPHERD(lazy { Key.key("minecraft:entity/zombie_villager/profession/shepherd") }), DESERT(lazy { Key.key("minecraft:entity/zombie_villager/type/desert") }), SNOW(lazy { Key.key("minecraft:entity/zombie_villager/type/snow") }), ARMADILLO(lazy { Key.key("minecraft:entity/armadillo") }), BANNER_BASE(lazy { Key.key("minecraft:entity/banner_base") }), BAT(lazy { Key.key("minecraft:entity/bat") }), BEACON_BEAM(lazy { Key.key("minecraft:entity/beacon_beam") }), BLAZE(lazy { Key.key("minecraft:entity/blaze") }), CHICKEN(lazy { Key.key("minecraft:entity/chicken") }), DOLPHIN(lazy { Key.key("minecraft:entity/dolphin") }), ELYTRA(lazy { Key.key("minecraft:entity/elytra") }), ENCHANTING_TABLE_BOOK(lazy { Key.key("minecraft:entity/enchanting_table_book") }), ENDERMITE(lazy { Key.key("minecraft:entity/endermite") }), END_GATEWAY_BEAM(lazy { Key.key("minecraft:entity/end_gateway_beam") }), END_PORTAL(lazy { Key.key("minecraft:entity/end_portal") }), EXPERIENCE_ORB(lazy { Key.key("minecraft:entity/experience_orb") }), FISHING_HOOK(lazy { Key.key("minecraft:entity/fishing_hook") }), GUARDIAN(lazy { Key.key("minecraft:entity/guardian") }), GUARDIAN_BEAM(lazy { Key.key("minecraft:entity/guardian_beam") }), GUARDIAN_ELDER(lazy { Key.key("minecraft:entity/guardian_elder") }), LEAD_KNOT(lazy { Key.key("minecraft:entity/lead_knot") }), MINECART(lazy { Key.key("minecraft:entity/minecart") }), PHANTOM(lazy { Key.key("minecraft:entity/phantom") }), PHANTOM_EYES(lazy { Key.key("minecraft:entity/phantom_eyes") }), SHIELD_BASE(lazy { Key.key("minecraft:entity/shield_base") }), SHIELD_BASE_NOPATTERN(lazy { Key.key("minecraft:entity/shield_base_nopattern") }), SILVERFISH(lazy { Key.key("minecraft:entity/silverfish") }), SNOW_GOLEM(lazy { Key.key("minecraft:entity/snow_golem") }), SPIDER_EYES(lazy { Key.key("minecraft:entity/spider_eyes") }), TRIDENT(lazy { Key.key("minecraft:entity/trident") }), TRIDENT_RIPTIDE(lazy { Key.key("minecraft:entity/trident_riptide") }), WANDERING_TRADER(lazy { Key.key("minecraft:entity/wandering_trader") }), WITCH(lazy { Key.key("minecraft:entity/witch") }), ALLAY(lazy { Key.key("minecraft:entity/allay/allay") }), WOOD(lazy { Key.key("minecraft:entity/armorstand/wood") }), AXOLOTL_BLUE(lazy { Key.key("minecraft:entity/axolotl/axolotl_blue") }), AXOLOTL_CYAN(lazy { Key.key("minecraft:entity/axolotl/axolotl_cyan") }), AXOLOTL_GOLD(lazy { Key.key("minecraft:entity/axolotl/axolotl_gold") }), AXOLOTL_LUCY(lazy { Key.key("minecraft:entity/axolotl/axolotl_lucy") }), AXOLOTL_WILD(lazy { Key.key("minecraft:entity/axolotl/axolotl_wild") }), BASE(lazy { Key.key("minecraft:entity/shield/base") }), BORDER(lazy { Key.key("minecraft:entity/shield/border") }), BRICKS(lazy { Key.key("minecraft:entity/shield/bricks") }), CIRCLE(lazy { Key.key("minecraft:entity/shield/circle") }), CREEPER(lazy { Key.key("minecraft:entity/shield/creeper") }), CROSS(lazy { Key.key("minecraft:entity/shield/cross") }), CURLY_BORDER(lazy { Key.key("minecraft:entity/shield/curly_border") }), DIAGONAL_LEFT(lazy { Key.key("minecraft:entity/shield/diagonal_left") }), DIAGONAL_RIGHT(lazy { Key.key("minecraft:entity/shield/diagonal_right") }), DIAGONAL_UP_LEFT(lazy { Key.key("minecraft:entity/shield/diagonal_up_left") }), DIAGONAL_UP_RIGHT(lazy { Key.key("minecraft:entity/shield/diagonal_up_right") }), FLOW(lazy { Key.key("minecraft:entity/shield/flow") }), FLOWER(lazy { Key.key("minecraft:entity/shield/flower") }), GLOBE(lazy { Key.key("minecraft:entity/shield/globe") }), GRADIENT(lazy { Key.key("minecraft:entity/shield/gradient") }), GRADIENT_UP(lazy { Key.key("minecraft:entity/shield/gradient_up") }), GUSTER(lazy { Key.key("minecraft:entity/shield/guster") }), HALF_HORIZONTAL(lazy { Key.key("minecraft:entity/shield/half_horizontal") }), HALF_HORIZONTAL_BOTTOM(lazy { Key.key("minecraft:entity/shield/half_horizontal_bottom") }), HALF_VERTICAL(lazy { Key.key("minecraft:entity/shield/half_vertical") }), HALF_VERTICAL_RIGHT(lazy { Key.key("minecraft:entity/shield/half_vertical_right") }), MOJANG(lazy { Key.key("minecraft:entity/shield/mojang") }), PIGLIN(lazy { Key.key("minecraft:entity/shield/piglin") }), RHOMBUS(lazy { Key.key("minecraft:entity/shield/rhombus") }), SKULL(lazy { Key.key("minecraft:entity/shield/skull") }), SMALL_STRIPES(lazy { Key.key("minecraft:entity/shield/small_stripes") }), SQUARE_BOTTOM_LEFT(lazy { Key.key("minecraft:entity/shield/square_bottom_left") }), SQUARE_BOTTOM_RIGHT(lazy { Key.key("minecraft:entity/shield/square_bottom_right") }), SQUARE_TOP_LEFT(lazy { Key.key("minecraft:entity/shield/square_top_left") }), SQUARE_TOP_RIGHT(lazy { Key.key("minecraft:entity/shield/square_top_right") }), STRAIGHT_CROSS(lazy { Key.key("minecraft:entity/shield/straight_cross") }), STRIPE_BOTTOM(lazy { Key.key("minecraft:entity/shield/stripe_bottom") }), STRIPE_CENTER(lazy { Key.key("minecraft:entity/shield/stripe_center") }), STRIPE_DOWNLEFT(lazy { Key.key("minecraft:entity/shield/stripe_downleft") }), STRIPE_DOWNRIGHT(lazy { Key.key("minecraft:entity/shield/stripe_downright") }), STRIPE_LEFT(lazy { Key.key("minecraft:entity/shield/stripe_left") }), STRIPE_MIDDLE(lazy { Key.key("minecraft:entity/shield/stripe_middle") }), STRIPE_RIGHT(lazy { Key.key("minecraft:entity/shield/stripe_right") }), STRIPE_TOP(lazy { Key.key("minecraft:entity/shield/stripe_top") }), TRIANGLES_BOTTOM(lazy { Key.key("minecraft:entity/shield/triangles_bottom") }), TRIANGLES_TOP(lazy { Key.key("minecraft:entity/shield/triangles_top") }), TRIANGLE_BOTTOM(lazy { Key.key("minecraft:entity/shield/triangle_bottom") }), TRIANGLE_TOP(lazy { Key.key("minecraft:entity/shield/triangle_top") }), POLARBEAR(lazy { Key.key("minecraft:entity/bear/polarbear") }), BLACK(lazy { Key.key("minecraft:entity/llama/decor/black") }), BLUE(lazy { Key.key("minecraft:entity/llama/decor/blue") }), BROWN(lazy { Key.key("minecraft:entity/llama/decor/brown") }), CYAN(lazy { Key.key("minecraft:entity/llama/decor/cyan") }), GRAY(lazy { Key.key("minecraft:entity/llama/decor/gray") }), GREEN(lazy { Key.key("minecraft:entity/llama/decor/green") }), LIGHT_BLUE(lazy { Key.key("minecraft:entity/llama/decor/light_blue") }), LIGHT_GRAY(lazy { Key.key("minecraft:entity/llama/decor/light_gray") }), LIME(lazy { Key.key("minecraft:entity/llama/decor/lime") }), MAGENTA(lazy { Key.key("minecraft:entity/llama/decor/magenta") }), ORANGE(lazy { Key.key("minecraft:entity/llama/decor/orange") }), PINK(lazy { Key.key("minecraft:entity/llama/decor/pink") }), PURPLE(lazy { Key.key("minecraft:entity/llama/decor/purple") }), RED(lazy { Key.key("minecraft:entity/llama/decor/red") }), WHITE(lazy { Key.key("minecraft:entity/llama/decor/white") }), YELLOW(lazy { Key.key("minecraft:entity/llama/decor/yellow") }), BEE(lazy { Key.key("minecraft:entity/bee/bee") }), BEE_ANGRY(lazy { Key.key("minecraft:entity/bee/bee_angry") }), BEE_ANGRY_NECTAR(lazy { Key.key("minecraft:entity/bee/bee_angry_nectar") }), BEE_NECTAR(lazy { Key.key("minecraft:entity/bee/bee_nectar") }), BEE_STINGER(lazy { Key.key("minecraft:entity/bee/bee_stinger") }), BELL_BODY(lazy { Key.key("minecraft:entity/bell/bell_body") }), ACACIA(lazy { Key.key("minecraft:entity/signs/hanging/acacia") }), BAMBOO(lazy { Key.key("minecraft:entity/signs/hanging/bamboo") }), BIRCH(lazy { Key.key("minecraft:entity/signs/hanging/birch") }), CHERRY(lazy { Key.key("minecraft:entity/signs/hanging/cherry") }), DARK_OAK(lazy { Key.key("minecraft:entity/signs/hanging/dark_oak") }), JUNGLE(lazy { Key.key("minecraft:entity/zombie_villager/type/jungle") }), MANGROVE(lazy { Key.key("minecraft:entity/signs/hanging/mangrove") }), OAK(lazy { Key.key("minecraft:entity/signs/hanging/oak") }), SPRUCE(lazy { Key.key("minecraft:entity/signs/hanging/spruce") }), BREEZE(lazy { Key.key("minecraft:entity/breeze/breeze") }), BREEZE_EYES(lazy { Key.key("minecraft:entity/breeze/breeze_eyes") }), BREEZE_WIND(lazy { Key.key("minecraft:entity/breeze/breeze_wind") }), CAMEL(lazy { Key.key("minecraft:entity/camel/camel") }), ALL_BLACK(lazy { Key.key("minecraft:entity/cat/all_black") }), BRITISH_SHORTHAIR(lazy { Key.key("minecraft:entity/cat/british_shorthair") }), CALICO(lazy { Key.key("minecraft:entity/cat/calico") }), CAT_COLLAR(lazy { Key.key("minecraft:entity/cat/cat_collar") }), JELLIE(lazy { Key.key("minecraft:entity/cat/jellie") }), OCELOT(lazy { Key.key("minecraft:entity/cat/ocelot") }), PERSIAN(lazy { Key.key("minecraft:entity/cat/persian") }), RAGDOLL(lazy { Key.key("minecraft:entity/cat/ragdoll") }), SIAMESE(lazy { Key.key("minecraft:entity/cat/siamese") }), TABBY(lazy { Key.key("minecraft:entity/cat/tabby") }), CHRISTMAS(lazy { Key.key("minecraft:entity/chest/christmas") }), CHRISTMAS_LEFT(lazy { Key.key("minecraft:entity/chest/christmas_left") }), CHRISTMAS_RIGHT(lazy { Key.key("minecraft:entity/chest/christmas_right") }), ENDER(lazy { Key.key("minecraft:entity/chest/ender") }), NORMAL(lazy { Key.key("minecraft:entity/chest/normal") }), NORMAL_LEFT(lazy { Key.key("minecraft:entity/chest/normal_left") }), NORMAL_RIGHT(lazy { Key.key("minecraft:entity/chest/normal_right") }), TRAPPED(lazy { Key.key("minecraft:entity/chest/trapped") }), TRAPPED_LEFT(lazy { Key.key("minecraft:entity/chest/trapped_left") }), TRAPPED_RIGHT(lazy { Key.key("minecraft:entity/chest/trapped_right") }), BREAK_PARTICLE(lazy { Key.key("minecraft:entity/conduit/break_particle") }), CAGE(lazy { Key.key("minecraft:entity/conduit/cage") }), CLOSED_EYE(lazy { Key.key("minecraft:entity/conduit/closed_eye") }), OPEN_EYE(lazy { Key.key("minecraft:entity/conduit/open_eye") }), BROWN_MOOSHROOM(lazy { Key.key("minecraft:entity/cow/brown_mooshroom") }), COW(lazy { Key.key("minecraft:entity/cow/cow") }), RED_MOOSHROOM(lazy { Key.key("minecraft:entity/cow/red_mooshroom") }), CREEPER_ARMOR(lazy { Key.key("minecraft:entity/creeper/creeper_armor") }), ANGLER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/angler_pottery_pattern") }), ARCHER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/archer_pottery_pattern") }), ARMS_UP_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/arms_up_pottery_pattern") }), BLADE_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/blade_pottery_pattern") }), BREWER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/brewer_pottery_pattern") }), BURN_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/burn_pottery_pattern") }), DANGER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/danger_pottery_pattern") }), DECORATED_POT_BASE(lazy { Key.key("minecraft:entity/decorated_pot/decorated_pot_base") }), DECORATED_POT_SIDE(lazy { Key.key("minecraft:entity/decorated_pot/decorated_pot_side") }), EXPLORER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/explorer_pottery_pattern") }), FLOW_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/flow_pottery_pattern") }), FRIEND_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/friend_pottery_pattern") }), GUSTER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/guster_pottery_pattern") }), HEARTBREAK_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/heartbreak_pottery_pattern") }), HEART_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/heart_pottery_pattern") }), HOWL_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/howl_pottery_pattern") }), MINER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/miner_pottery_pattern") }), MOURNER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/mourner_pottery_pattern") }), PLENTY_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/plenty_pottery_pattern") }), PRIZE_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/prize_pottery_pattern") }), SCRAPE_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/scrape_pottery_pattern") }), SHEAF_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/sheaf_pottery_pattern") }), SHELTER_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/shelter_pottery_pattern") }), SKULL_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/skull_pottery_pattern") }), SNORT_POTTERY_PATTERN(lazy { Key.key("minecraft:entity/decorated_pot/snort_pottery_pattern") }), DRAGON(lazy { Key.key("minecraft:entity/enderdragon/dragon") }), DRAGON_EXPLODING(lazy { Key.key("minecraft:entity/enderdragon/dragon_exploding") }), DRAGON_EYES(lazy { Key.key("minecraft:entity/enderdragon/dragon_eyes") }), DRAGON_FIREBALL(lazy { Key.key("minecraft:entity/enderdragon/dragon_fireball") }), ENDERMAN(lazy { Key.key("minecraft:entity/enderman/enderman") }), ENDERMAN_EYES(lazy { Key.key("minecraft:entity/enderman/enderman_eyes") }), END_CRYSTAL(lazy { Key.key("minecraft:entity/end_crystal/end_crystal") }), END_CRYSTAL_BEAM(lazy { Key.key("minecraft:entity/end_crystal/end_crystal_beam") }), COD(lazy { Key.key("minecraft:entity/fish/cod") }), PUFFERFISH(lazy { Key.key("minecraft:entity/fish/pufferfish") }), SALMON(lazy { Key.key("minecraft:entity/fish/salmon") }), TROPICAL_A(lazy { Key.key("minecraft:entity/fish/tropical_a") }), TROPICAL_A_PATTERN_1(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_1") }), TROPICAL_A_PATTERN_2(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_2") }), TROPICAL_A_PATTERN_3(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_3") }), TROPICAL_A_PATTERN_4(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_4") }), TROPICAL_A_PATTERN_5(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_5") }), TROPICAL_A_PATTERN_6(lazy { Key.key("minecraft:entity/fish/tropical_a_pattern_6") }), TROPICAL_B(lazy { Key.key("minecraft:entity/fish/tropical_b") }), TROPICAL_B_PATTERN_1(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_1") }), TROPICAL_B_PATTERN_2(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_2") }), TROPICAL_B_PATTERN_3(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_3") }), TROPICAL_B_PATTERN_4(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_4") }), TROPICAL_B_PATTERN_5(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_5") }), TROPICAL_B_PATTERN_6(lazy { Key.key("minecraft:entity/fish/tropical_b_pattern_6") }), FOX(lazy { Key.key("minecraft:entity/fox/fox") }), FOX_SLEEP(lazy { Key.key("minecraft:entity/fox/fox_sleep") }), SNOW_FOX(lazy { Key.key("minecraft:entity/fox/snow_fox") }), SNOW_FOX_SLEEP(lazy { Key.key("minecraft:entity/fox/snow_fox_sleep") }), COLD_FROG(lazy { Key.key("minecraft:entity/frog/cold_frog") }), TEMPERATE_FROG(lazy { Key.key("minecraft:entity/frog/temperate_frog") }), WARM_FROG(lazy { Key.key("minecraft:entity/frog/warm_frog") }), GHAST(lazy { Key.key("minecraft:entity/ghast/ghast") }), GHAST_SHOOTING(lazy { Key.key("minecraft:entity/ghast/ghast_shooting") }), GOAT(lazy { Key.key("minecraft:entity/goat/goat") }), HOGLIN(lazy { Key.key("minecraft:entity/hoglin/hoglin") }), ZOGLIN(lazy { Key.key("minecraft:entity/hoglin/zoglin") }), DONKEY(lazy { Key.key("minecraft:entity/horse/donkey") }), HORSE_BLACK(lazy { Key.key("minecraft:entity/horse/horse_black") }), HORSE_BROWN(lazy { Key.key("minecraft:entity/horse/horse_brown") }), HORSE_CHESTNUT(lazy { Key.key("minecraft:entity/horse/horse_chestnut") }), HORSE_CREAMY(lazy { Key.key("minecraft:entity/horse/horse_creamy") }), HORSE_DARKBROWN(lazy { Key.key("minecraft:entity/horse/horse_darkbrown") }), HORSE_GRAY(lazy { Key.key("minecraft:entity/horse/horse_gray") }), HORSE_MARKINGS_BLACKDOTS(lazy { Key.key("minecraft:entity/horse/horse_markings_blackdots") }), HORSE_MARKINGS_WHITE(lazy { Key.key("minecraft:entity/horse/horse_markings_white") }), HORSE_MARKINGS_WHITEDOTS(lazy { Key.key("minecraft:entity/horse/horse_markings_whitedots") }), HORSE_MARKINGS_WHITEFIELD(lazy { Key.key("minecraft:entity/horse/horse_markings_whitefield") }), HORSE_SKELETON(lazy { Key.key("minecraft:entity/horse/horse_skeleton") }), HORSE_WHITE(lazy { Key.key("minecraft:entity/horse/horse_white") }), HORSE_ZOMBIE(lazy { Key.key("minecraft:entity/horse/horse_zombie") }), MULE(lazy { Key.key("minecraft:entity/horse/mule") }), EVOKER(lazy { Key.key("minecraft:entity/illager/evoker") }), EVOKER_FANGS(lazy { Key.key("minecraft:entity/illager/evoker_fangs") }), ILLUSIONER(lazy { Key.key("minecraft:entity/illager/illusioner") }), PILLAGER(lazy { Key.key("minecraft:entity/illager/pillager") }), RAVAGER(lazy { Key.key("minecraft:entity/illager/ravager") }), VEX(lazy { Key.key("minecraft:entity/illager/vex") }), VEX_CHARGING(lazy { Key.key("minecraft:entity/illager/vex_charging") }), VINDICATOR(lazy { Key.key("minecraft:entity/illager/vindicator") }), IRON_GOLEM(lazy { Key.key("minecraft:entity/iron_golem/iron_golem") }), IRON_GOLEM_CRACKINESS_HIGH(lazy { Key.key("minecraft:entity/iron_golem/iron_golem_crackiness_high") }), IRON_GOLEM_CRACKINESS_LOW(lazy { Key.key("minecraft:entity/iron_golem/iron_golem_crackiness_low") }), IRON_GOLEM_CRACKINESS_MEDIUM(lazy { Key.key("minecraft:entity/iron_golem/iron_golem_crackiness_medium") }), CREAMY(lazy { Key.key("minecraft:entity/llama/creamy") }), SPIT(lazy { Key.key("minecraft:entity/llama/spit") }), AGGRESSIVE_PANDA(lazy { Key.key("minecraft:entity/panda/aggressive_panda") }), BROWN_PANDA(lazy { Key.key("minecraft:entity/panda/brown_panda") }), LAZY_PANDA(lazy { Key.key("minecraft:entity/panda/lazy_panda") }), PANDA(lazy { Key.key("minecraft:entity/panda/panda") }), PLAYFUL_PANDA(lazy { Key.key("minecraft:entity/panda/playful_panda") }), WEAK_PANDA(lazy { Key.key("minecraft:entity/panda/weak_panda") }), WORRIED_PANDA(lazy { Key.key("minecraft:entity/panda/worried_panda") }), PARROT_BLUE(lazy { Key.key("minecraft:entity/parrot/parrot_blue") }), PARROT_GREEN(lazy { Key.key("minecraft:entity/parrot/parrot_green") }), PARROT_GREY(lazy { Key.key("minecraft:entity/parrot/parrot_grey") }), PARROT_RED_BLUE(lazy { Key.key("minecraft:entity/parrot/parrot_red_blue") }), PARROT_YELLOW_BLUE(lazy { Key.key("minecraft:entity/parrot/parrot_yellow_blue") }), PIG(lazy { Key.key("minecraft:entity/pig/pig") }), PIG_SADDLE(lazy { Key.key("minecraft:entity/pig/pig_saddle") }), PIGLIN_BRUTE(lazy { Key.key("minecraft:entity/piglin/piglin_brute") }), ZOMBIFIED_PIGLIN(lazy { Key.key("minecraft:entity/piglin/zombified_piglin") }), ARROW(lazy { Key.key("minecraft:entity/projectiles/arrow") }), SPECTRAL_ARROW(lazy { Key.key("minecraft:entity/projectiles/spectral_arrow") }), TIPPED_ARROW(lazy { Key.key("minecraft:entity/projectiles/tipped_arrow") }), WIND_CHARGE(lazy { Key.key("minecraft:entity/projectiles/wind_charge") }), CAERBANNOG(lazy { Key.key("minecraft:entity/rabbit/caerbannog") }), GOLD(lazy { Key.key("minecraft:entity/zombie_villager/profession_level/gold") }), SALT(lazy { Key.key("minecraft:entity/rabbit/salt") }), TOAST(lazy { Key.key("minecraft:entity/rabbit/toast") }), WHITE_SPLOTCHED(lazy { Key.key("minecraft:entity/rabbit/white_splotched") }), SHEEP(lazy { Key.key("minecraft:entity/sheep/sheep") }), SHEEP_FUR(lazy { Key.key("minecraft:entity/sheep/sheep_fur") }), SHULKER(lazy { Key.key("minecraft:entity/shulker/shulker") }), SHULKER_BLACK(lazy { Key.key("minecraft:entity/shulker/shulker_black") }), SHULKER_BLUE(lazy { Key.key("minecraft:entity/shulker/shulker_blue") }), SHULKER_BROWN(lazy { Key.key("minecraft:entity/shulker/shulker_brown") }), SHULKER_CYAN(lazy { Key.key("minecraft:entity/shulker/shulker_cyan") }), SHULKER_GRAY(lazy { Key.key("minecraft:entity/shulker/shulker_gray") }), SHULKER_GREEN(lazy { Key.key("minecraft:entity/shulker/shulker_green") }), SHULKER_LIGHT_BLUE(lazy { Key.key("minecraft:entity/shulker/shulker_light_blue") }), SHULKER_LIGHT_GRAY(lazy { Key.key("minecraft:entity/shulker/shulker_light_gray") }), SHULKER_LIME(lazy { Key.key("minecraft:entity/shulker/shulker_lime") }), SHULKER_MAGENTA(lazy { Key.key("minecraft:entity/shulker/shulker_magenta") }), SHULKER_ORANGE(lazy { Key.key("minecraft:entity/shulker/shulker_orange") }), SHULKER_PINK(lazy { Key.key("minecraft:entity/shulker/shulker_pink") }), SHULKER_PURPLE(lazy { Key.key("minecraft:entity/shulker/shulker_purple") }), SHULKER_RED(lazy { Key.key("minecraft:entity/shulker/shulker_red") }), SHULKER_WHITE(lazy { Key.key("minecraft:entity/shulker/shulker_white") }), SHULKER_YELLOW(lazy { Key.key("minecraft:entity/shulker/shulker_yellow") }), SPARK(lazy { Key.key("minecraft:entity/shulker/spark") }), CRIMSON(lazy { Key.key("minecraft:entity/signs/hanging/crimson") }), WARPED(lazy { Key.key("minecraft:entity/signs/hanging/warped") }), BOGGED(lazy { Key.key("minecraft:entity/skeleton/bogged") }), BOGGED_OVERLAY(lazy { Key.key("minecraft:entity/skeleton/bogged_overlay") }), SKELETON(lazy { Key.key("minecraft:entity/skeleton/skeleton") }), STRAY(lazy { Key.key("minecraft:entity/skeleton/stray") }), STRAY_OVERLAY(lazy { Key.key("minecraft:entity/skeleton/stray_overlay") }), WITHER_SKELETON(lazy { Key.key("minecraft:entity/skeleton/wither_skeleton") }), MAGMACUBE(lazy { Key.key("minecraft:entity/slime/magmacube") }), SLIME(lazy { Key.key("minecraft:entity/slime/slime") }), SNIFFER(lazy { Key.key("minecraft:entity/sniffer/sniffer") }), CAVE_SPIDER(lazy { Key.key("minecraft:entity/spider/cave_spider") }), SPIDER(lazy { Key.key("minecraft:entity/spider/spider") }), GLOW_SQUID(lazy { Key.key("minecraft:entity/squid/glow_squid") }), SQUID(lazy { Key.key("minecraft:entity/squid/squid") }), STRIDER(lazy { Key.key("minecraft:entity/strider/strider") }), STRIDER_COLD(lazy { Key.key("minecraft:entity/strider/strider_cold") }), STRIDER_SADDLE(lazy { Key.key("minecraft:entity/strider/strider_saddle") }), TADPOLE(lazy { Key.key("minecraft:entity/tadpole/tadpole") }), BIG_SEA_TURTLE(lazy { Key.key("minecraft:entity/turtle/big_sea_turtle") }), VILLAGER(lazy { Key.key("minecraft:entity/villager/villager") }), WARDEN(lazy { Key.key("minecraft:entity/warden/warden") }), WARDEN_BIOLUMINESCENT_LAYER(lazy { Key.key("minecraft:entity/warden/warden_bioluminescent_layer") }), WARDEN_HEART(lazy { Key.key("minecraft:entity/warden/warden_heart") }), WARDEN_PULSATING_SPOTS_1(lazy { Key.key("minecraft:entity/warden/warden_pulsating_spots_1") }), WARDEN_PULSATING_SPOTS_2(lazy { Key.key("minecraft:entity/warden/warden_pulsating_spots_2") }), WITHER(lazy { Key.key("minecraft:entity/wither/wither") }), WITHER_ARMOR(lazy { Key.key("minecraft:entity/wither/wither_armor") }), WITHER_INVULNERABLE(lazy { Key.key("minecraft:entity/wither/wither_invulnerable") }), WOLF(lazy { Key.key("minecraft:entity/wolf/wolf") }), WOLF_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_angry") }), WOLF_ARMOR(lazy { Key.key("minecraft:entity/wolf/wolf_armor") }), WOLF_ARMOR_CRACKINESS_HIGH(lazy { Key.key("minecraft:entity/wolf/wolf_armor_crackiness_high") }), WOLF_ARMOR_CRACKINESS_LOW(lazy { Key.key("minecraft:entity/wolf/wolf_armor_crackiness_low") }), WOLF_ARMOR_CRACKINESS_MEDIUM(lazy { Key.key("minecraft:entity/wolf/wolf_armor_crackiness_medium") }), WOLF_ARMOR_OVERLAY(lazy { Key.key("minecraft:entity/wolf/wolf_armor_overlay") }), WOLF_ASHEN(lazy { Key.key("minecraft:entity/wolf/wolf_ashen") }), WOLF_ASHEN_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_ashen_angry") }), WOLF_ASHEN_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_ashen_tame") }), WOLF_BLACK(lazy { Key.key("minecraft:entity/wolf/wolf_black") }), WOLF_BLACK_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_black_angry") }), WOLF_BLACK_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_black_tame") }), WOLF_CHESTNUT(lazy { Key.key("minecraft:entity/wolf/wolf_chestnut") }), WOLF_CHESTNUT_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_chestnut_angry") }), WOLF_CHESTNUT_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_chestnut_tame") }), WOLF_COLLAR(lazy { Key.key("minecraft:entity/wolf/wolf_collar") }), WOLF_RUSTY(lazy { Key.key("minecraft:entity/wolf/wolf_rusty") }), WOLF_RUSTY_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_rusty_angry") }), WOLF_RUSTY_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_rusty_tame") }), WOLF_SNOWY(lazy { Key.key("minecraft:entity/wolf/wolf_snowy") }), WOLF_SNOWY_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_snowy_angry") }), WOLF_SNOWY_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_snowy_tame") }), WOLF_SPOTTED(lazy { Key.key("minecraft:entity/wolf/wolf_spotted") }), WOLF_SPOTTED_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_spotted_angry") }), WOLF_SPOTTED_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_spotted_tame") }), WOLF_STRIPED(lazy { Key.key("minecraft:entity/wolf/wolf_striped") }), WOLF_STRIPED_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_striped_angry") }), WOLF_STRIPED_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_striped_tame") }), WOLF_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_tame") }), WOLF_WOODS(lazy { Key.key("minecraft:entity/wolf/wolf_woods") }), WOLF_WOODS_ANGRY(lazy { Key.key("minecraft:entity/wolf/wolf_woods_angry") }), WOLF_WOODS_TAME(lazy { Key.key("minecraft:entity/wolf/wolf_woods_tame") }), DROWNED(lazy { Key.key("minecraft:entity/zombie/drowned") }), DROWNED_OUTER_LAYER(lazy { Key.key("minecraft:entity/zombie/drowned_outer_layer") }), HUSK(lazy { Key.key("minecraft:entity/zombie/husk") }), ZOMBIE(lazy { Key.key("minecraft:entity/zombie/zombie") }), ZOMBIE_VILLAGER(lazy { Key.key("minecraft:entity/zombie_villager/zombie_villager") }), HORSE_ARMOR_DIAMOND(lazy { Key.key("minecraft:entity/horse/armor/horse_armor_diamond") }), HORSE_ARMOR_GOLD(lazy { Key.key("minecraft:entity/horse/armor/horse_armor_gold") }), HORSE_ARMOR_IRON(lazy { Key.key("minecraft:entity/horse/armor/horse_armor_iron") }), HORSE_ARMOR_LEATHER(lazy { Key.key("minecraft:entity/horse/armor/horse_armor_leather") }), TRADER_LLAMA(lazy { Key.key("minecraft:entity/llama/decor/trader_llama") }), ALEX(lazy { Key.key("minecraft:entity/player/wide/alex") }), ARI(lazy { Key.key("minecraft:entity/player/wide/ari") }), EFE(lazy { Key.key("minecraft:entity/player/wide/efe") }), KAI(lazy { Key.key("minecraft:entity/player/wide/kai") }), MAKENA(lazy { Key.key("minecraft:entity/player/wide/makena") }), NOOR(lazy { Key.key("minecraft:entity/player/wide/noor") }), STEVE(lazy { Key.key("minecraft:entity/player/wide/steve") }), SUNNY(lazy { Key.key("minecraft:entity/player/wide/sunny") }), ZURI(lazy { Key.key("minecraft:entity/player/wide/zuri") }), ARMORER(lazy { Key.key("minecraft:entity/zombie_villager/profession/armorer") }), CARTOGRAPHER(lazy { Key.key("minecraft:entity/zombie_villager/profession/cartographer") }), CLERIC(lazy { Key.key("minecraft:entity/zombie_villager/profession/cleric") }), LEATHERWORKER(lazy { Key.key("minecraft:entity/zombie_villager/profession/leatherworker") }), MASON(lazy { Key.key("minecraft:entity/zombie_villager/profession/mason") }), NITWIT(lazy { Key.key("minecraft:entity/zombie_villager/profession/nitwit") }), TOOLSMITH(lazy { Key.key("minecraft:entity/zombie_villager/profession/toolsmith") }), WEAPONSMITH(lazy { Key.key("minecraft:entity/zombie_villager/profession/weaponsmith") }), DIAMOND(lazy { Key.key("minecraft:entity/zombie_villager/profession_level/diamond") }), EMERALD(lazy { Key.key("minecraft:entity/zombie_villager/profession_level/emerald") }), IRON(lazy { Key.key("minecraft:entity/zombie_villager/profession_level/iron") }), STONE(lazy { Key.key("minecraft:entity/zombie_villager/profession_level/stone") }), PLAINS(lazy { Key.key("minecraft:entity/zombie_villager/type/plains") }), SAVANNA(lazy { Key.key("minecraft:entity/zombie_villager/type/savanna") }), SWAMP(lazy { Key.key("minecraft:entity/zombie_villager/type/swamp") }), TAIGA(lazy { Key.key("minecraft:entity/zombie_villager/type/taiga") }), ; public fun toGeneric(): SolidMaterialTexture = SolidMaterialTexture(key.value) }
0
Kotlin
0
1
cd816d69c12c7aff75064dc380e07005d7fd8ad0
29,196
solid-material
Apache License 2.0
plugins/kotlin/idea/tests/testData/quickfix/when/addRemainingBranchesEnumBackTicks.kt
ingokegel
72,937,917
false
null
// "Add remaining branches" "true" // WITH_STDLIB enum class FooEnum { A, B, `C`, `true`, `false`, `null` } fun test(foo: FooEnum?) = <caret>when (foo) { FooEnum.A -> "A" } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.AddWhenRemainingBranchesFix // FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.k2.codeinsight.fixes.AddWhenRemainingBranchFixFactories$AddRemainingWhenBranchesQuickFix
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
408
intellij-community
Apache License 2.0
plugin-animation/src/test/java/com/mapbox/maps/plugin/animation/CameraAnimatorsFactoryTest.kt
mapbox
330,365,289
false
null
package com.mapbox.maps.plugin.animation import android.view.animation.DecelerateInterpolator import com.mapbox.geojson.Point import com.mapbox.maps.* import com.mapbox.maps.plugin.animation.animator.CameraAnimator import com.mapbox.maps.plugin.delegates.MapCameraManagerDelegate import com.mapbox.maps.plugin.delegates.MapDelegateProvider import com.mapbox.maps.plugin.delegates.MapProjectionDelegate import com.mapbox.maps.plugin.delegates.MapTransformDelegate import io.mockk.every import io.mockk.mockk import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.shadows.ShadowLog @RunWith(RobolectricTestRunner::class) class CameraAnimatorsFactoryTest { private lateinit var mapTransformDelegate: MapTransformDelegate private lateinit var mapCameraManagerDelegate: MapCameraManagerDelegate private lateinit var mapProjectionDelegate: MapProjectionDelegate private lateinit var cameraAnimatorsFactory: CameraAnimatorsFactory private val initialCenter = Point.fromLngLat(-0.11968, 51.50325) private val initialCameraPosition = CameraState( initialCenter, EdgeInsets(0.0, 0.0, 0.0, 0.0), 0.0, -0.0, 15.0 ) private val decelerateInterpolatorNew = DecelerateInterpolator() private val delayNew = 20L private val durationNew = 50L @Before fun setUp() { ShadowLog.stream = System.out val delegateProvider = mockk<MapDelegateProvider>(relaxed = true) mapCameraManagerDelegate = mockk(relaxed = true) mapTransformDelegate = mockk(relaxed = true) mapProjectionDelegate = mockk(relaxed = true) every { delegateProvider.mapCameraManagerDelegate } returns mapCameraManagerDelegate every { delegateProvider.mapTransformDelegate } returns mapTransformDelegate every { delegateProvider.mapProjectionDelegate } returns mapProjectionDelegate every { mapCameraManagerDelegate.cameraState } returns initialCameraPosition cameraAnimatorsFactory = CameraAnimatorsFactory(delegateProvider) CameraAnimatorsFactory.setDefaultAnimatorOptions { this.interpolator = decelerateInterpolatorNew this.startDelay = delayNew this.duration = durationNew } } @Test fun testEaseToAnimators() { val targetEaseToPosition = CameraOptions.Builder() .center(Point.fromLngLat(-0.07520, 51.50550)) .zoom(17.0) .bearing(-180.0) .pitch(30.0) .build() val animators = cameraAnimatorsFactory.getEaseTo(targetEaseToPosition) testAnimators(animators, targetEaseToPosition) } @Test fun testMoveByAnimators() { every { mapCameraManagerDelegate.cameraState } returns initialCameraPosition val targetCenter = Point.fromLngLat(-0.12376717562057138, 51.50579407417868) every { mapCameraManagerDelegate.coordinateForPixel(any()) } returns targetCenter val offset = ScreenCoordinate(500.0, 500.0) val target = CameraOptions.Builder().center(targetCenter).build() val animators = cameraAnimatorsFactory.getMoveBy(offset) testAnimators(animators, target) } @Test fun testRotateByAnimators() { every { mapCameraManagerDelegate.cameraState } returns initialCameraPosition every { mapTransformDelegate.getMapOptions() } returns MapOptions.Builder().size(Size(1078.875f, 1698.375f)).build() val target = CameraOptions.Builder().bearing(-25.981604850040434).build() val animators = cameraAnimatorsFactory.getRotateBy(ScreenCoordinate(0.0, 0.0), ScreenCoordinate(500.0, 500.0)) testAnimators(animators, target) } @Test fun testScaleByAnimators() { every { mapCameraManagerDelegate.cameraState } returns initialCameraPosition val scaleBy = 15.0 val zoomTarget = CameraTransform.calculateScaleBy(scaleBy, initialCameraPosition.zoom) val target = CameraOptions.Builder().zoom(zoomTarget).anchor(ScreenCoordinate(10.0, 10.0)).build() val animators = cameraAnimatorsFactory.getScaleBy(scaleBy, target.anchor) testAnimators(animators, target) } @Test fun testPitchByAnimators() { every { mapCameraManagerDelegate.cameraState } returns initialCameraPosition val pitchBy = 20.0 val target = CameraOptions.Builder().pitch(initialCameraPosition.pitch + pitchBy).build() val animators = cameraAnimatorsFactory.getPitchBy(pitchBy) testAnimators(animators, target) } private fun testAnimators(animators: Array<CameraAnimator<*>>, targetCameraPosition: CameraOptions) { animators.forEach { val startValue = it.startValue val targetValue = it.targets.first() Assert.assertEquals(it.interpolator, decelerateInterpolatorNew) Assert.assertEquals(it.startDelay, delayNew) Assert.assertEquals(it.duration, durationNew) when (it.type) { CameraAnimatorType.BEARING -> { Assert.assertEquals(initialCameraPosition.bearing, startValue) Assert.assertEquals(targetCameraPosition.bearing!!, targetValue) } CameraAnimatorType.CENTER -> { Assert.assertEquals(initialCameraPosition.center, startValue) Assert.assertEquals(targetCameraPosition.center, targetValue) } CameraAnimatorType.PITCH -> { Assert.assertEquals(initialCameraPosition.pitch, startValue) Assert.assertEquals(targetCameraPosition.pitch, targetValue) } CameraAnimatorType.ZOOM -> { Assert.assertEquals(initialCameraPosition.zoom, startValue) Assert.assertEquals(targetCameraPosition.zoom, targetValue) } CameraAnimatorType.ANCHOR -> { Assert.assertEquals(targetCameraPosition.anchor, targetValue) Assert.assertEquals(targetCameraPosition.anchor, targetValue) } CameraAnimatorType.PADDING -> { Assert.assertEquals(initialCameraPosition.padding, startValue) Assert.assertEquals(targetCameraPosition.padding, targetValue) } } } } }
216
null
126
434
7faf620b4694bd50f4b4399abcf6eca29e3173ba
5,973
mapbox-maps-android
Apache License 2.0
flowable-xml-parser/src/test/kotlin/com/valb3r/bpmn/intellij/plugin/flowable/parser/customservicetasks/FlowableShellTaskTest.kt
valb3r
261,109,342
false
null
package com.valb3r.bpmn.intellij.plugin.flowable.parser.customservicetasks import com.valb3r.bpmn.intellij.plugin.bpmn.api.BpmnProcessObject import com.valb3r.bpmn.intellij.plugin.bpmn.api.bpmn.BpmnElementId import com.valb3r.bpmn.intellij.plugin.bpmn.api.bpmn.elements.tasks.BpmnShellTask import com.valb3r.bpmn.intellij.plugin.bpmn.api.info.PropertyType import com.valb3r.bpmn.intellij.plugin.flowable.parser.FlowableObjectFactory import com.valb3r.bpmn.intellij.plugin.flowable.parser.FlowableParser import com.valb3r.bpmn.intellij.plugin.flowable.parser.asResource import com.valb3r.bpmn.intellij.plugin.flowable.parser.readAndUpdateProcess import com.valb3r.bpmn.intellij.plugin.flowable.parser.testevents.BooleanValueUpdatedEvent import com.valb3r.bpmn.intellij.plugin.flowable.parser.testevents.StringValueUpdatedEvent import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNullOrEmpty import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldHaveSingleItem import org.junit.jupiter.api.Test private const val FILE = "custom-service-tasks/shell-task.bpmn20.xml" internal class FlowableShellTaskTest { private val parser = FlowableParser() private val elementId = BpmnElementId("shellTaskId") @Test fun `Shell task is parseable`() { val processObject = parser.parse(FILE.asResource()!!) val task = readShellTask(processObject) task.id.shouldBeEqualTo(elementId) task.name.shouldBeEqualTo("Shell task name") task.documentation.shouldBeEqualTo("Docs for shell task") task.async!!.shouldBeTrue() // TODO 'exclusive' ? task.isForCompensation!!.shouldBeTrue() task.command.shouldBeEqualTo("echo \"Hello\" > /tmp/foo.txt") task.arg1.shouldBeEqualTo("Arg1") task.arg2.shouldBeEqualTo("Arg2") task.arg3.shouldBeEqualTo("Arg3") task.arg4.shouldBeEqualTo("Arg4") task.arg5.shouldBeEqualTo("Arg5") task.wait.shouldBeEqualTo("WAIT") task.cleanEnv.shouldBeEqualTo("clear") task.errorCodeVariable.shouldBeEqualTo("ERR_CODE") task.outputVariable.shouldBeEqualTo("OUTPUT_VAR") task.directory.shouldBeEqualTo("/tmp") val props = BpmnProcessObject(processObject.process, processObject.diagram).toView(FlowableObjectFactory()).elemPropertiesByElementId[task.id]!! props[PropertyType.ID]!!.value.shouldBeEqualTo(task.id.id) props[PropertyType.NAME]!!.value.shouldBeEqualTo(task.name) props[PropertyType.DOCUMENTATION]!!.value.shouldBeEqualTo(task.documentation) props[PropertyType.ASYNC]!!.value.shouldBeEqualTo(task.async) props[PropertyType.IS_FOR_COMPENSATION]!!.value.shouldBeEqualTo(task.isForCompensation) props[PropertyType.COMMAND]!!.value.shouldBeEqualTo(task.command) props[PropertyType.ARG_1]!!.value.shouldBeEqualTo(task.arg1) props[PropertyType.ARG_2]!!.value.shouldBeEqualTo(task.arg2) props[PropertyType.ARG_3]!!.value.shouldBeEqualTo(task.arg3) props[PropertyType.ARG_4]!!.value.shouldBeEqualTo(task.arg4) props[PropertyType.ARG_5]!!.value.shouldBeEqualTo(task.arg5) props[PropertyType.WAIT]!!.value.shouldBeEqualTo(task.wait) props[PropertyType.CLEAN_ENV]!!.value.shouldBeEqualTo(task.cleanEnv) props[PropertyType.ERROR_CODE_VARIABLE]!!.value.shouldBeEqualTo(task.errorCodeVariable) props[PropertyType.OUTPUT_VARIABLE]!!.value.shouldBeEqualTo(task.outputVariable) props[PropertyType.DIRECTORY]!!.value.shouldBeEqualTo(task.directory) } @Test fun `Shell task is updatable`() { {value: String -> readAndUpdate(PropertyType.ID, value).id.id.shouldBeEqualTo(value)} ("new Id"); {value: String -> readAndUpdate(PropertyType.NAME, value).name.shouldBeEqualTo(value)} ("new Name"); {value: String -> readAndUpdate(PropertyType.DOCUMENTATION, value).documentation.shouldBeEqualTo(value)} ("new docs"); {value: Boolean -> readAndUpdate(PropertyType.ASYNC, value).async.shouldBeEqualTo(value)} (false); {value: Boolean -> readAndUpdate(PropertyType.IS_FOR_COMPENSATION, value).isForCompensation.shouldBeEqualTo(value)} (false); {value: String -> readAndUpdate(PropertyType.COMMAND, value).command.shouldBeEqualTo(value)} ("echo '123' > /data/temp"); {value: String -> readAndUpdate(PropertyType.ARG_1, value).arg1.shouldBeEqualTo(value)} ("'test1'"); {value: String -> readAndUpdate(PropertyType.ARG_2, value).arg2.shouldBeEqualTo(value)} ("'test2'"); {value: String -> readAndUpdate(PropertyType.ARG_3, value).arg3.shouldBeEqualTo(value)} ("'test3'"); {value: String -> readAndUpdate(PropertyType.ARG_4, value).arg4.shouldBeEqualTo(value)} ("'test4'"); {value: String -> readAndUpdate(PropertyType.ARG_5, value).arg5.shouldBeEqualTo(value)} ("'test5'"); {value: String -> readAndUpdate(PropertyType.WAIT, value).wait.shouldBeEqualTo(value)} ("sleep 1000;"); {value: String -> readAndUpdate(PropertyType.CLEAN_ENV, value).cleanEnv.shouldBeEqualTo(value)} ("rm -rf *"); {value: String -> readAndUpdate(PropertyType.ERROR_CODE_VARIABLE, value).errorCodeVariable.shouldBeEqualTo(value)} ("ERR_CODE_1"); {value: String -> readAndUpdate(PropertyType.OUTPUT_VARIABLE, value).outputVariable.shouldBeEqualTo(value)} ("OUTPUT_1"); {value: String -> readAndUpdate(PropertyType.DIRECTORY, value).directory.shouldBeEqualTo(value)} ("/tmp/work/result") } @Test fun `Shell task is fields are emptyable`() { readAndSetNullString(PropertyType.NAME).name.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.DOCUMENTATION).documentation.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.COMMAND).command.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ARG_1).arg1.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ARG_2).arg2.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ARG_3).arg3.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ARG_4).arg4.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ARG_5).arg5.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.WAIT).wait.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.CLEAN_ENV).cleanEnv.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.ERROR_CODE_VARIABLE).errorCodeVariable.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.OUTPUT_VARIABLE).outputVariable.shouldBeNullOrEmpty() readAndSetNullString(PropertyType.DIRECTORY).directory.shouldBeNullOrEmpty() } private fun readAndSetNullString(property: PropertyType): BpmnShellTask { return readShellTask(readAndUpdateProcess(parser, FILE, StringValueUpdatedEvent(elementId, property, ""))) } private fun readAndUpdate(property: PropertyType, newValue: String): BpmnShellTask { return readShellTask(readAndUpdateProcess(parser, FILE, StringValueUpdatedEvent(elementId, property, newValue))) } private fun readAndUpdate(property: PropertyType, newValue: Boolean): BpmnShellTask { return readShellTask(readAndUpdateProcess(parser, FILE, BooleanValueUpdatedEvent(elementId, property, newValue))) } private fun readShellTask(processObject: BpmnProcessObject): BpmnShellTask { return processObject.process.body!!.shellTask!!.shouldHaveSingleItem() } }
76
Kotlin
20
81
760efb3d7e48970545d0d7622687d67c2b9b9693
7,468
flowable-bpmn-intellij-plugin
MIT License
src/test/kotlin/kotlinx/io/tests/BytePacketBuildTestPooled.kt
icerockdev
152,649,269
true
{"Kotlin": 724251}
package kotlinx.io.tests import kotlinx.io.core.* class BytePacketBuildTestPooled : BytePacketBuildTest() { override val pool = VerifyingObjectPool(IoBuffer.Pool) }
0
Kotlin
0
0
1e877d31bfc51f16485de00df8fc166b39ca7ef9
171
kotlinx-io
Apache License 2.0
app/src/main/java/com/smart4apps/supportArTask/data/room/ArticlesDatabase.kt
alimahmoud0096
787,050,719
false
{"Kotlin": 34928}
package com.smart4apps.supportArTask.data.room import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.smart4apps.supportArTask.data.model.Article import com.smart4apps.supportArTask.utils.Converters @Database(entities = [Article::class], version = 1) @TypeConverters(Converters::class) abstract class ArticlesDatabase : RoomDatabase() { abstract fun articlesDao(): ArticlesDao }
0
Kotlin
0
0
8102a042b0dde26c367e21d382ce51e3a270ca34
442
supportArTask
Apache License 2.0
src/main/kotlin/felis/transformer/LazyTransformation.kt
Felis-Project
774,006,760
false
{"Kotlin": 104118}
package felis.transformer import felis.language.LanguageAdapter import felis.meta.TransformationMetadata class LazyTransformation(val source: TransformationMetadata, private val languageAdapter: LanguageAdapter) : Transformation { val t by lazy { this.languageAdapter.createInstance(this.source.specifier, Transformation::class.java).getOrThrow() } override fun transform(container: ClassContainer): ClassContainer? = this.t.transform(container) override fun toString(): String = this.source.toString() override fun hashCode(): Int = source.hashCode() override fun equals(other: Any?): Boolean = other is LazyTransformation && other.source == this.source }
1
Kotlin
1
2
ea2520653dabeaf4a847b98af7e62bee7e845609
696
felis
MIT License
src/main/java/osgi2gradle/projectsgradle/SourceSetsDeclarator.kt
aBothe
245,868,074
false
null
package osgi2gradle.projectsgradle import osgi2gradle.EclipseBundleGradleProject import java.io.FileInputStream import java.io.OutputStreamWriter import java.util.* import java.util.stream.Collectors fun EclipseBundleGradleProject.declareProjectSourceSets(projectsGradleWriter: OutputStreamWriter) { if (bundleProperties.sourceDirectories.isNotEmpty()) { projectsGradleWriter .append("\tsourceSets.main.java.srcDirs = [") .append(bundleProperties.sourceDirectories.joinToString("','", "'", "'")) .append("]\r\n") } projectsGradleWriter .append("\tsourceSets.main.resources.srcDirs = sourceSets.main.java.srcDirs\r\n") if (bundleProperties.jarsToInclude.isNotEmpty()) { projectsGradleWriter .append("\tjar.from files(").append(bundleProperties.jarsToInclude.joinToString("','", "'", "'")) .append(").collect { zipTree(it) }\r\n") } if (bundleProperties.nonJarsToInclude.isNotEmpty()) { projectsGradleWriter .append("\tjar.from fileTree(projectDir) { includes = [") .append(bundleProperties.nonJarsToInclude.joinToString("','", "'", "'")) .append("] }\r\n") } }
0
Kotlin
0
0
89dcb27468ee3893edfb3d33d10cce2f5490549b
1,256
osgi2gradle
MIT License
braintrust-java-core/src/main/kotlin/com/braintrustdata/api/services/blocking/project/LogServiceImpl.kt
braintrustdata
752,086,100
false
{"Kotlin": 3335628, "Shell": 3637, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.braintrustdata.api.services.async.project import com.braintrustdata.api.core.ClientOptions import com.braintrustdata.api.core.RequestOptions import com.braintrustdata.api.core.http.HttpMethod import com.braintrustdata.api.core.http.HttpRequest import com.braintrustdata.api.core.http.HttpResponse.Handler import com.braintrustdata.api.errors.BraintrustError import com.braintrustdata.api.models.ProjectLogFeedbackParams import com.braintrustdata.api.models.ProjectLogFetchParams import com.braintrustdata.api.models.ProjectLogFetchPostParams import com.braintrustdata.api.models.ProjectLogFetchPostResponse import com.braintrustdata.api.models.ProjectLogFetchResponse import com.braintrustdata.api.models.ProjectLogInsertParams import com.braintrustdata.api.models.ProjectLogInsertResponse import com.braintrustdata.api.services.emptyHandler import com.braintrustdata.api.services.errorHandler import com.braintrustdata.api.services.json import com.braintrustdata.api.services.jsonHandler import com.braintrustdata.api.services.withErrorHandler class LogServiceAsyncImpl constructor( private val clientOptions: ClientOptions, ) : LogServiceAsync { private val errorHandler: Handler<BraintrustError> = errorHandler(clientOptions.jsonMapper) private val feedbackHandler: Handler<Void?> = emptyHandler().withErrorHandler(errorHandler) /** Log feedback for a set of project logs events */ override suspend fun feedback( params: ProjectLogFeedbackParams, requestOptions: RequestOptions ) { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("v1", "project_logs", params.getPathParam(0), "feedback") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.executeAsync(request, requestOptions).let { response -> response.use { feedbackHandler.handle(it) } } } private val fetchHandler: Handler<ProjectLogFetchResponse> = jsonHandler<ProjectLogFetchResponse>(clientOptions.jsonMapper) .withErrorHandler(errorHandler) /** * Fetch the events in a project logs. Equivalent to the POST form of the same path, but with * the parameters in the URL query rather than in the request body */ override suspend fun fetch( params: ProjectLogFetchParams, requestOptions: RequestOptions ): ProjectLogFetchResponse { val request = HttpRequest.builder() .method(HttpMethod.GET) .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .build() return clientOptions.httpClient.executeAsync(request, requestOptions).let { response -> response .use { fetchHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val fetchPostHandler: Handler<ProjectLogFetchPostResponse> = jsonHandler<ProjectLogFetchPostResponse>(clientOptions.jsonMapper) .withErrorHandler(errorHandler) /** * Fetch the events in a project logs. Equivalent to the GET form of the same path, but with the * parameters in the request body rather than in the URL query */ override suspend fun fetchPost( params: ProjectLogFetchPostParams, requestOptions: RequestOptions ): ProjectLogFetchPostResponse { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("v1", "project_logs", params.getPathParam(0), "fetch") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.executeAsync(request, requestOptions).let { response -> response .use { fetchPostHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } private val insertHandler: Handler<ProjectLogInsertResponse> = jsonHandler<ProjectLogInsertResponse>(clientOptions.jsonMapper) .withErrorHandler(errorHandler) /** Insert a set of events into the project logs */ override suspend fun insert( params: ProjectLogInsertParams, requestOptions: RequestOptions ): ProjectLogInsertResponse { val request = HttpRequest.builder() .method(HttpMethod.POST) .addPathSegments("v1", "project_logs", params.getPathParam(0), "insert") .putAllQueryParams(params.getQueryParams()) .putAllHeaders(clientOptions.headers) .putAllHeaders(params.getHeaders()) .body(json(clientOptions.jsonMapper, params.getBody())) .build() return clientOptions.httpClient.executeAsync(request, requestOptions).let { response -> response .use { insertHandler.handle(it) } .apply { if (requestOptions.responseValidation ?: clientOptions.responseValidation) { validate() } } } } }
1
Kotlin
0
2
0e44c52f0b48ed75bf866931b75155a9f7fdbd00
6,062
braintrust-java
Apache License 2.0
app/src/main/java/com/fitless/fitnessX/application/MainApp.kt
SultanS1
767,628,796
false
{"Kotlin": 45701}
package com.fitless.fitnessX.application import android.app.Application import com.fitless.authorization.di.authModule import com.fitless.fitnessX.di.appModule import com.fitless.onboarding.di.onboardingModule import com.github.terrakok.cicerone.Cicerone import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin /** * The main application class for the FitnessX app. * This class initializes the Cicerone navigator and sets up Koin dependency injection. */ class MainApp : Application(){ private val cicerone = Cicerone.create() val router get() = cicerone.router val navigatorHolder get() = cicerone.getNavigatorHolder() override fun onCreate() { super.onCreate() INSTANCE = this startKoin { androidContext(this@MainApp) modules(appModule, onboardingModule, authModule) } } companion object { internal lateinit var INSTANCE: MainApp private set } }
0
Kotlin
0
0
993664c77ae8b2328988733169c8d05badccd26d
995
FitnesX
MIT License
android/src/androidTest/java/io/github/tonnyl/moka/migration/AllMigrationsTest.kt
ETSEmpiricalStudyKotlinAndroidApps
496,360,843
false
{"Kotlin": 1391177, "Swift": 100384, "CSS": 30407, "JavaScript": 13933, "Shell": 2990}
package io.github.tonnyl.moka.migration import androidx.room.Room import androidx.room.testing.MigrationTestHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import io.tonnyl.moka.common.db.MIGRATION_1_2 import io.tonnyl.moka.common.db.MokaDataBase import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.io.IOException @RunWith(AndroidJUnit4::class) class AllMigrationsTest { private val testDbName = "all-migration-test" private val allMigrations = arrayOf(MIGRATION_1_2) @get:Rule val migrationTestHelper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), MokaDataBase::class.java.canonicalName, FrameworkSQLiteOpenHelperFactory() ) @Test @Throws(IOException::class) fun migrateAll() { // Create earliest version of the database. migrationTestHelper.createDatabase(testDbName, 1).apply { close() } // Open latest version of the database. Room will validate the schema // once all migrations execute. Room.databaseBuilder( InstrumentationRegistry.getInstrumentation().targetContext, MokaDataBase::class.java, testDbName ).addMigrations(*allMigrations).build().apply { openHelper.writableDatabase.close() } } }
0
null
0
0
34db6153b274028158de1ee08f080b1a8f985325
1,490
Moka
MIT License
app/src/main/java/com/example/waterme/MainActivity.kt
yonatanBtl
776,541,220
false
{"Kotlin": 18256}
package com.example.waterme import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.example.waterme.ui.WaterMeApp import com.example.waterme.ui.theme.WaterMeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WaterMeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { WaterMeApp() } } } } }
0
Kotlin
0
0
8b4ce62f392d820af8f55585cd4b325af768e706
934
WaterMe_UNIDAD_07
Apache License 2.0
src/main/java/com/cocktailsguru/app/user/domain/User.kt
CocktailsGuru
103,529,993
false
null
package com.cocktailsguru.app.user.domain import java.time.LocalDateTime import javax.persistence.* @Entity @Table(name = "coctail_user") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "registrationType") abstract class User( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) open val id: Long, @Column(name = "userID") open val externalUserId: String, @Column(name = "userName") open var name: String, @Enumerated(EnumType.ORDINAL) @Column(name = "userGender") open val gender: Gender, @Column(name = "userImage") open var image: String, @Column(name = "userCountryCode") open var countryCode: String, open var numPictures: Int, open var numPicturesFav: Int, open var numComments: Int, open var numFollowers: Int, open var numFollowing: Int, open var numCocktailsFav: Int, @Column(name = "numCocktailsRat") open var numCocktailsRated: Int, open var numShown: Int, open var lastDate: LocalDateTime )
0
Kotlin
0
1
f0a447975dedb7f54bd64dba1dce10fefeda64ce
1,136
server
MIT License
src/main/kotlin/org/example/simpleapp/SimpleAppApplication.kt
JulyMak
234,959,536
false
null
package org.example.simpleapp import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class SimpleAppApplication { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(SimpleAppApplication::class.java, *args) } } }
0
Kotlin
0
0
8dfcd72ec80bc51f4f55b204f492c6f5ec113061
384
simple-app
Apache License 2.0
compiler/testData/diagnostics/tests/enum/javaEnumValueOfMethod.kt
chashnikov
14,658,474
false
null
// FILE: A.java public enum A { ENTRY; } // FILE: test.kt fun main() { A.valueOf("ENTRY"): A }
0
null
0
1
88a261234860ff0014e3c2dd8e64072c685d442d
104
kotlin
Apache License 2.0
src/plugins/MySampleService.kt
pallavirawat
254,977,047
false
{"Kotlin": 9735}
package com.example.plugins import io.ktor.application.* import io.ktor.util.* import io.ktor.util.pipeline.* import kotlin.system.exitProcess class MySampleService(monitor: ApplicationEvents) { public class Configuration { } private val starting: (Application) -> Unit = { println("Application starting sns: $it") } private val started: (Application) -> Unit = { println("Application started sns: $it") } private val stopping: (Application) -> Unit = { println("Application stopping sns: $it") } private var stopped: (Application) -> Unit = {} init { stopped = { println("Application stopped sns: $it") monitor.unsubscribe(ApplicationStarting, starting) monitor.unsubscribe(ApplicationStarted, started) monitor.unsubscribe(ApplicationStopping, stopping) monitor.unsubscribe(ApplicationStopped, stopped) } monitor.subscribe(ApplicationStarting, starting) monitor.subscribe(ApplicationStarted, started) monitor.subscribe(ApplicationStopping, stopping) monitor.subscribe(ApplicationStopped, stopped) } fun hello(){ println("hello from mah side") } public companion object Feature : ApplicationFeature<Application, Configuration, MySampleService> { override val key: AttributeKey<MySampleService> = AttributeKey("My Service") override fun install(pipeline: Application, configure: Configuration.() -> Unit): MySampleService { val mahPhase = PipelinePhase("MyService") val configuration = Configuration().apply(configure) val feature = MySampleService( pipeline.environment.monitor ) // pipeline.insertPhaseBefore(ApplicationCallPipeline.Monitoring, mahPhase) pipeline.insertPhaseAfter(ApplicationCallPipeline.Setup, mahPhase) // exitProcess(0) return feature } } }
0
Kotlin
0
0
6499d99fa96a8dfa5cfbf247e9577d6f14fe1a25
1,970
ktor-server-playground
MIT License
ERMSCompany/src/main/java/com/kust/erms_company/ui/profile/ProfileFragment.kt
sabghat90
591,653,827
false
null
package com.camelloncase.testedeperformance09.ui.profile import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.camelloncase.testedeperformance09.R class ProfileFragment : Fragment() { companion object { fun newInstance() = ProfileFragment() } private lateinit var viewModel: ProfileViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_profile, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(ProfileViewModel::class.java) // TODO: Use the ViewModel } }
3
null
0
4
8ceac25585fb78207f14f2f7bfecfcb4d1c82624
933
ERMS
MIT License
sam-kotlin-core/src/main/kotlin/software/elborai/api/models/OrganizationUpdateParams.kt
DefinitelyATestOrg
787,029,213
false
{"Kotlin": 699174, "Shell": 1286, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. package software.elborai.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import java.util.Objects import software.elborai.api.core.ExcludeMissing import software.elborai.api.core.JsonValue import software.elborai.api.core.NoAutoDetect import software.elborai.api.core.toUnmodifiable import software.elborai.api.models.* class OrganizationUpdateParams constructor( private val id: String, private val friendlyId: String, private val name: String, private val defaultLanguage: DefaultLanguage?, private val additionalQueryParams: Map<String, List<String>>, private val additionalHeaders: Map<String, List<String>>, private val additionalBodyProperties: Map<String, JsonValue>, ) { fun id(): String = id fun friendlyId(): String = friendlyId fun name(): String = name fun defaultLanguage(): DefaultLanguage? = defaultLanguage internal fun getBody(): OrganizationUpdateBody { return OrganizationUpdateBody( id, friendlyId, name, defaultLanguage, additionalBodyProperties, ) } internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams internal fun getHeaders(): Map<String, List<String>> = additionalHeaders @JsonDeserialize(builder = OrganizationUpdateBody.Builder::class) @NoAutoDetect class OrganizationUpdateBody internal constructor( private val id: String?, private val friendlyId: String?, private val name: String?, private val defaultLanguage: DefaultLanguage?, private val additionalProperties: Map<String, JsonValue>, ) { private var hashCode: Int = 0 @JsonProperty("id") fun id(): String? = id @JsonProperty("friendlyId") fun friendlyId(): String? = friendlyId @JsonProperty("name") fun name(): String? = name @JsonProperty("defaultLanguage") fun defaultLanguage(): DefaultLanguage? = defaultLanguage @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is OrganizationUpdateBody && this.id == other.id && this.friendlyId == other.friendlyId && this.name == other.name && this.defaultLanguage == other.defaultLanguage && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( id, friendlyId, name, defaultLanguage, additionalProperties, ) } return hashCode } override fun toString() = "OrganizationUpdateBody{id=$id, friendlyId=$friendlyId, name=$name, defaultLanguage=$defaultLanguage, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var id: String? = null private var friendlyId: String? = null private var name: String? = null private var defaultLanguage: DefaultLanguage? = null private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(organizationUpdateBody: OrganizationUpdateBody) = apply { this.id = organizationUpdateBody.id this.friendlyId = organizationUpdateBody.friendlyId this.name = organizationUpdateBody.name this.defaultLanguage = organizationUpdateBody.defaultLanguage additionalProperties(organizationUpdateBody.additionalProperties) } @JsonProperty("id") fun id(id: String) = apply { this.id = id } @JsonProperty("friendlyId") fun friendlyId(friendlyId: String) = apply { this.friendlyId = friendlyId } @JsonProperty("name") fun name(name: String) = apply { this.name = name } @JsonProperty("defaultLanguage") fun defaultLanguage(defaultLanguage: DefaultLanguage) = apply { this.defaultLanguage = defaultLanguage } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): OrganizationUpdateBody = OrganizationUpdateBody( checkNotNull(id) { "`id` is required but was not set" }, checkNotNull(friendlyId) { "`friendlyId` is required but was not set" }, checkNotNull(name) { "`name` is required but was not set" }, defaultLanguage, additionalProperties.toUnmodifiable(), ) } } fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is OrganizationUpdateParams && this.id == other.id && this.friendlyId == other.friendlyId && this.name == other.name && this.defaultLanguage == other.defaultLanguage && this.additionalQueryParams == other.additionalQueryParams && this.additionalHeaders == other.additionalHeaders && this.additionalBodyProperties == other.additionalBodyProperties } override fun hashCode(): Int { return Objects.hash( id, friendlyId, name, defaultLanguage, additionalQueryParams, additionalHeaders, additionalBodyProperties, ) } override fun toString() = "OrganizationUpdateParams{id=$id, friendlyId=$friendlyId, name=$name, defaultLanguage=$defaultLanguage, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } @NoAutoDetect class Builder { private var id: String? = null private var friendlyId: String? = null private var name: String? = null private var defaultLanguage: DefaultLanguage? = null private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(organizationUpdateParams: OrganizationUpdateParams) = apply { this.id = organizationUpdateParams.id this.friendlyId = organizationUpdateParams.friendlyId this.name = organizationUpdateParams.name this.defaultLanguage = organizationUpdateParams.defaultLanguage additionalQueryParams(organizationUpdateParams.additionalQueryParams) additionalHeaders(organizationUpdateParams.additionalHeaders) additionalBodyProperties(organizationUpdateParams.additionalBodyProperties) } fun id(id: String) = apply { this.id = id } fun friendlyId(friendlyId: String) = apply { this.friendlyId = friendlyId } fun name(name: String) = apply { this.name = name } fun defaultLanguage(defaultLanguage: DefaultLanguage) = apply { this.defaultLanguage = defaultLanguage } fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply { this.additionalQueryParams.clear() putAllQueryParams(additionalQueryParams) } fun putQueryParam(name: String, value: String) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) } fun putQueryParams(name: String, values: Iterable<String>) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply { additionalQueryParams.forEach(this::putQueryParams) } fun removeQueryParam(name: String) = apply { this.additionalQueryParams.put(name, mutableListOf()) } fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { this.additionalHeaders.clear() putAllHeaders(additionalHeaders) } fun putHeader(name: String, value: String) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) } fun putHeaders(name: String, values: Iterable<String>) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { additionalHeaders.forEach(this::putHeaders) } fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.clear() this.additionalBodyProperties.putAll(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { this.additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.putAll(additionalBodyProperties) } fun build(): OrganizationUpdateParams = OrganizationUpdateParams( checkNotNull(id) { "`id` is required but was not set" }, checkNotNull(friendlyId) { "`friendlyId` is required but was not set" }, checkNotNull(name) { "`name` is required but was not set" }, defaultLanguage, additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalBodyProperties.toUnmodifiable(), ) } @JsonDeserialize(builder = DefaultLanguage.Builder::class) @NoAutoDetect class DefaultLanguage private constructor( private val code: String?, private val detected: Boolean?, private val additionalProperties: Map<String, JsonValue>, ) { private var hashCode: Int = 0 @JsonProperty("code") fun code(): String? = code @JsonProperty("detected") fun detected(): Boolean? = detected @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is DefaultLanguage && this.code == other.code && this.detected == other.detected && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( code, detected, additionalProperties, ) } return hashCode } override fun toString() = "DefaultLanguage{code=$code, detected=$detected, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var code: String? = null private var detected: Boolean? = null private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(defaultLanguage: DefaultLanguage) = apply { this.code = defaultLanguage.code this.detected = defaultLanguage.detected additionalProperties(defaultLanguage.additionalProperties) } @JsonProperty("code") fun code(code: String) = apply { this.code = code } @JsonProperty("detected") fun detected(detected: Boolean) = apply { this.detected = detected } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): DefaultLanguage = DefaultLanguage( code, detected, additionalProperties.toUnmodifiable(), ) } } }
1
Kotlin
0
0
80a2bb383a75b6f86d5b50a1e9b37fa6d8fce477
14,620
sam-kotlin
Apache License 2.0
app/src/main/java/pt/dbmg/mobiletaiga/network/response/ImageX.kt
worm69
166,021,572
false
{"Gradle": 7, "YAML": 12, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 3, "Kotlin": 464, "XML": 78, "Java": 55, "JSON": 2, "GraphQL": 1, "Dockerfile": 1}
package pt.dbmg.mobiletaiga.network.response import com.google.gson.annotations.SerializedName data class ImageX( @SerializedName("large") val large: String, // https://media.kitsu.io/categories/images/10/large.jpg?1496212711 @SerializedName("medium") val medium: String, // https://media.kitsu.io/categories/images/10/medium.jpg?1496212711 @SerializedName("meta") val meta: MetaX, @SerializedName("original") val original: String, // https://media.kitsu.io/categories/images/10/original.jpg?1496212711 @SerializedName("small") val small: String, // https://media.kitsu.io/categories/images/10/small.jpg?1496212711 @SerializedName("tiny") val tiny: String // https://media.kitsu.io/categories/images/10/tiny.jpg?1496212711 )
0
Kotlin
0
4
8ec09bed018d57225b85e042865608952633c622
774
mobiletaiga
Apache License 2.0
buildSrc/src/main/kotlin/androidx/build/dependencyTracker/DependencyTracker.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.dependencyTracker import org.gradle.api.Project import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.logging.Logger /** * Utility class that traverses all project dependencies and discover which modules depend * on each other. This is mainly used by [AffectedModuleDetector] to find out which projects * should be run. */ internal class DependencyTracker constructor( private val rootProject: Project, private val logger: Logger? ) { private val dependentList: Map<Project, Set<Project>> by lazy { val result = mutableMapOf<Project, MutableSet<Project>>() rootProject.subprojects.forEach { project -> logger?.info("checking ${project.path} for dependencies") project.configurations.forEach { config -> logger?.info("checking config ${project.path}/$config for dependencies") config .dependencies .filterIsInstance(ProjectDependency::class.java) .forEach { logger?.info( "there is a dependency from ${project.path} to " + it.dependencyProject.path ) result.getOrPut(it.dependencyProject) { mutableSetOf() } .add(project) } } } result } fun findAllDependents(project: Project): Set<Project> { logger?.info("finding dependents of ${project.path}") val result = mutableSetOf<Project>() fun addAllDependents(project: Project) { if (result.add(project)) { dependentList[project]?.forEach(::addAllDependents) } } addAllDependents(project) logger?.info( "dependents of ${project.path} is ${result.map { it.path }}" ) // the project isn't a dependent of itself return result.minus(project) } }
8
Java
35
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,639
androidx
Apache License 2.0
couchbase-lite/src/commonMain/kotlin/kotbase/ConfigurationFactories.kt
jeffdgr8
518,984,559
false
{"Kotlin": 2289925, "Python": 294}
/* * Copyright 2022-2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotbase /** * Configuration factory for new DatabaseConfigurations * * Usage: * * val dbConfig = DatabaseConfigurationFactory.newConfig(...) */ public val DatabaseConfigurationFactory: DatabaseConfiguration? = null /** * Create a DatabaseConfiguration, overriding the receiver's * values with the passed parameters: * * @param databasePath The directory in which the database is stored. * * @see DatabaseConfiguration */ public fun DatabaseConfiguration?.newConfig(databasePath: String? = null): DatabaseConfiguration { return DatabaseConfiguration(this).apply { databasePath?.let { setDirectory(it) } } } /** * Configuration factory for new ReplicatorConfigurations * * Usage: * * val replConfig = ReplicatorConfigurationFactory.newConfig(...) */ public val ReplicatorConfigurationFactory: ReplicatorConfiguration? = null /** * Create a ReplicatorConfiguration, overriding the receiver's * values with the passed parameters: * * Note: A document that is blocked by a document Id filter will not be auto-purged * regardless of the setting of the enableAutoPurge property * * @param database (required) the local database. * @param target (required) The max size of the log file in bytes. * @param type replicator type: push, pull, or push and pull: default is push and pull. * @param continuous continuous flag: true for continuous, false by default. * @param authenticator connection authenticator. * @param headers extra HTTP headers to send in all requests to the remote target. * @param pinnedServerCertificate target server's SSL certificate. * @param channels Sync Gateway channel names. * @param documentIDs IDs of documents to be replicated: default is all documents. * @param pushFilter filter for pushed documents. * @param pullFilter filter for pulled documents. * @param conflictResolver conflict resolver. * @param maxAttempts max retry attempts after connection failure. * @param maxAttemptWaitTime max time between retry attempts (exponential backoff). * @param heartbeat heartbeat interval, in seconds. * @param enableAutoPurge auto-purge enabled. * @param acceptParentDomainCookies Advanced: accept cookies for parent domains. * * @see ReplicatorConfiguration */ public fun ReplicatorConfiguration?.newConfig( database: Database? = null, target: Endpoint? = null, type: ReplicatorType? = null, continuous: Boolean? = null, authenticator: Authenticator? = null, headers: Map<String, String>? = null, pinnedServerCertificate: ByteArray? = null, channels: List<String>? = null, documentIDs: List<String>? = null, pushFilter: ReplicationFilter? = null, pullFilter: ReplicationFilter? = null, conflictResolver: ConflictResolver? = null, maxAttempts: Int? = null, maxAttemptWaitTime: Int? = null, heartbeat: Int? = null, enableAutoPurge: Boolean? = null, acceptParentDomainCookies: Boolean? = null ): ReplicatorConfiguration { val orig = this return ReplicatorConfiguration( database ?: this?.database ?: error("A ReplicatorConfiguration must specify a database"), target ?: this?.target ?: error("A ReplicatorConfiguration must specify an endpoint") ).apply { (type ?: orig?.type)?.let { this.type = it } (continuous ?: orig?.isContinuous)?.let { this.isContinuous = it } this.authenticator = authenticator ?: orig?.authenticator this.headers = headers ?: orig?.headers (acceptParentDomainCookies ?: orig?.isAcceptParentDomainCookies)?.let { this.isAcceptParentDomainCookies = it } this.pinnedServerCertificate = pinnedServerCertificate ?: orig?.pinnedServerCertificate this.channels = channels ?: orig?.channels this.documentIDs = documentIDs ?: orig?.documentIDs this.pushFilter = pushFilter ?: orig?.pushFilter this.pullFilter = pullFilter ?: orig?.pullFilter this.conflictResolver = conflictResolver ?: orig?.conflictResolver (maxAttempts ?: orig?.maxAttempts)?.let { this.maxAttempts = it } (maxAttemptWaitTime ?: orig?.maxAttemptWaitTime)?.let { this.maxAttemptWaitTime = it } (heartbeat ?: orig?.heartbeat)?.let { this.heartbeat = it } (enableAutoPurge ?: orig?.isAutoPurgeEnabled)?.let { this.isAutoPurgeEnabled = it } } }
0
Kotlin
0
7
188723bf0c4609b649d157988de44ac140e431dd
4,945
kotbase
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/statistics/FUSEventGroups.kt
cr8tpro
189,964,139
true
{"Kotlin": 37481242, "Java": 7489008, "JavaScript": 157778, "HTML": 74773, "Lex": 23159, "TypeScript": 21255, "IDL": 10895, "ANTLR": 9803, "CSS": 8084, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "Scala": 80}
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.statistics // Note: along with adding a group to this enum you should also add its GROUP_ID to plugin.xml and get it whitelisted // (see https://confluence.jetbrains.com/display/FUS/IntelliJ+Reporting+API). enum class FUSEventGroups(groupIdSuffix: String) { GradleTarget("gradle.target"), MavenTarget("maven.target"), JPSTarget("jps.target"), Refactoring("ide.action.refactoring"), NewFileTemplate("ide.newFileTempl"), NPWizards("ide.npwizards"), DebugEval("ide.debugger.eval"); val GROUP_ID: String = "kotlin.$groupIdSuffix" }
1
Kotlin
1
2
dca23f871cc22acee9258c3d58b40d71e3693858
759
kotlin
Apache License 2.0
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/OneDimensionalFocusSearch.kt
JetBrains
351,708,598
true
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.focus import androidx.compose.ui.focus.FocusDirection.Companion.Next import androidx.compose.ui.focus.FocusDirection.Companion.Previous import androidx.compose.ui.focus.FocusStateImpl.Active import androidx.compose.ui.focus.FocusStateImpl.ActiveParent import androidx.compose.ui.focus.FocusStateImpl.Captured import androidx.compose.ui.focus.FocusStateImpl.Deactivated import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent import androidx.compose.ui.focus.FocusStateImpl.Inactive import androidx.compose.ui.node.ModifiedFocusNode import androidx.compose.ui.util.fastForEach import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract private const val InvalidFocusDirection = "This function should only be used for 1-D focus search" private const val NoActiveChild = "ActiveParent must have a focusedChild" internal fun ModifiedFocusNode.oneDimensionalFocusSearch( direction: FocusDirection ): ModifiedFocusNode? = when (direction) { Next -> forwardFocusSearch() Previous -> backwardFocusSearch() else -> error(InvalidFocusDirection) } private fun ModifiedFocusNode.forwardFocusSearch(): ModifiedFocusNode? = when (focusState) { ActiveParent, DeactivatedParent -> { val focusedChild = focusedChild ?: error(NoActiveChild) focusedChild.forwardFocusSearch() ?: searchChildren(focusedChild, Next) } Active, Captured, Deactivated -> pickChildForForwardSearch() Inactive -> this } private fun ModifiedFocusNode.backwardFocusSearch(): ModifiedFocusNode? = when (focusState) { ActiveParent, DeactivatedParent -> { val focusedChild = focusedChild ?: error(NoActiveChild) // Unlike forwardFocusSearch, backwardFocusSearch visits the children before the parent. when (focusedChild.focusState) { ActiveParent -> focusedChild.backwardFocusSearch() // Don't forget to visit this item after visiting all its children. ?: focusedChild DeactivatedParent -> focusedChild.backwardFocusSearch() // Since this item is deactivated, just skip it and search among its siblings. ?: searchChildren(focusedChild, Previous) // Since this item "is focused", it means we already visited all its children. // So just search among its siblings. Active, Captured -> searchChildren(focusedChild, Previous) Deactivated, Inactive -> error(NoActiveChild) } } // BackwardFocusSearch is invoked at the root, and so it searches among siblings of the // ActiveParent for a child that is focused. If we encounter an active node (instead of an // ActiveParent) or a deactivated node (instead of a deactivated parent), it indicates // that the hierarchy does not have focus. ie. this is the initial focus state. // So we pick one of the children as the result. Active, Captured, Deactivated -> pickChildForBackwardSearch() // If we encounter an inactive node, we attempt to pick one of its children before picking // this node (backward search visits the children before the parent). Inactive -> pickChildForBackwardSearch() ?: this } // Search for the next sibling that should be granted focus. private fun ModifiedFocusNode.searchChildren( focusedItem: ModifiedFocusNode, direction: FocusDirection ): ModifiedFocusNode? { check(focusState == ActiveParent || focusState == DeactivatedParent) { "This function should only be used within a parent that has focus." } // TODO(b/192681045): Instead of fetching the children and then iterating on them, add a // forEachFocusableChild() function that does not allocate a list. val focusableChildren = focusableChildren(excludeDeactivated = false) when (direction) { Next -> focusableChildren.forEachItemAfter(focusedItem) { child -> child.forwardFocusSearch()?.let { return it } } Previous -> focusableChildren.forEachItemBefore(focusedItem) { child -> child.backwardFocusSearch()?.let { return it } } else -> error(InvalidFocusDirection) } // If all the children have been visited, return null if this is a forward search. If it is a // backward search, we want to move focus to the parent unless the parent is deactivated. // We also don't want to move focus to the root because from the user's perspective this would // look like nothing is focused. return this.takeUnless { direction == Next || focusState == DeactivatedParent || isRoot() } } private fun ModifiedFocusNode.pickChildForForwardSearch(): ModifiedFocusNode? { focusableChildren(excludeDeactivated = false).fastForEach { child -> child.forwardFocusSearch()?.let { return it } } return null } private fun ModifiedFocusNode.pickChildForBackwardSearch(): ModifiedFocusNode? { focusableChildren(excludeDeactivated = false).asReversed().fastForEach { child -> child.backwardFocusSearch()?.let { return it } } return null } private fun ModifiedFocusNode.isRoot() = findParentFocusNode() == null @OptIn(ExperimentalContracts::class) private inline fun <T> List<T>.forEachItemAfter(item: T, action: (T) -> Unit) { contract { callsInPlace(action) } var itemFound = false for (index in indices) { if (itemFound) { action(get(index)) } if (get(index) == item) { itemFound = true } } } @OptIn(ExperimentalContracts::class) private inline fun <T> List<T>.forEachItemBefore(item: T, action: (T) -> Unit) { contract { callsInPlace(action) } var itemFound = false for (index in indices.reversed()) { if (itemFound) { action(get(index)) } if (get(index) == item) { itemFound = true } } }
10
Java
16
59
e18ad812b77fc8babb00aacfcea930607b0794b5
6,506
androidx
Apache License 2.0
example/android/app/src/main/kotlin/com/blinck/blinck/MainActivity.kt
berathamzaoglu
847,315,616
false
{"Kotlin": 8169, "Objective-C": 8093, "Dart": 5473, "Ruby": 2945, "Shell": 741}
package com.theantimony.googleplacespickerexample import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
0
Kotlin
0
0
65b99dfe73ad7b78f8bb0c28d79074692822f576
142
blinck_google_places_picker
MIT License
app/src/main/java/de/droidcon/berlin2018/ui/search/SearchViewNavigator.kt
OpenConference
100,889,869
false
null
package de.droidcon.berlin2018.ui.search import android.content.Intent import android.net.Uri import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import de.droidcon.berlin2018.R import de.droidcon.berlin2018.model.Session import de.droidcon.berlin2018.model.Speaker import de.droidcon.berlin2018.ui.applicationComponent import de.droidcon.berlin2018.ui.navigation.Navigator import de.droidcon.berlin2018.ui.sessiondetails.SessionDetailsController import de.droidcon.berlin2018.ui.speakerdetail.SpeakerDetailsController import de.psdev.licensesdialog.LicensesDialog /** * * * @author <NAME> */ class SearchViewNavigator(private val controller: Controller) : Navigator { override fun showHome() { controller.router.popCurrentController() } override fun showSessions() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showMySchedule() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSpeakers() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSpeakerDetails(speaker: Speaker) { controller.router.pushController( RouterTransaction.with(SpeakerDetailsController(speaker.id())) .popChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler()) ) } override fun showSessionDetails(session: Session) { controller.router.pushController( RouterTransaction.with( SessionDetailsController(session.id()) ) .popChangeHandler(HorizontalChangeHandler()) .pushChangeHandler(HorizontalChangeHandler()) ) } override fun showTweets() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun showSearch() { TODO( "not implemented") //To change body of created functions use File | Settings | File Templates. } override fun popSelfFromBackstack() { controller.router.popCurrentController() } override fun showLicences() { controller.applicationComponent().analytics().trackShowLicenses() LicensesDialog.Builder(controller.activity!!) .setNotices(R.raw.notices) .setIncludeOwnLicense(true) .build() .show(); } override fun showSourceCode() { controller.applicationComponent().analytics().trackShowSourceCode() val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://github.com/OpenConference/DroidconBerlin2017") controller.startActivity(intent) } }
1
null
1
27
142effaf4eb04abb12d5b812e797a89922b649a5
2,852
DroidconBerlin2017
Apache License 2.0
sdk/src/main/java/net/activelook/sdk/blemodel/Device.kt
cowboycoder
220,551,642
false
null
package net.activelook.sdk.blemodel internal class Device { companion object { @JvmStatic val RECOGNIZED_DEVICE_NAMES = arrayOf( "a.look", "cobra", "microoled" ) } }
0
Kotlin
0
0
97f76607c7771ebb46e45050590821aa40dababc
236
activelook-sdk-android
Apache License 2.0
src/main/kotlin/icons/Icons.kt
i-am-arunkumar
393,908,591
true
{"Kotlin": 100873}
package icons import com.intellij.openapi.util.IconLoader /** * Icon Constants */ object Icons { @JvmField val LogoIcon = IconLoader.getIcon("/logo.svg", javaClass) }
0
null
0
0
4f72acfdb83c7917faa397818bd198b67fd3d6d8
178
AutoCp
MIT License
example/src/main/java/io/sellmair/example/fragment/ChatFragment.kt
nairobi222
181,482,076
false
null
package io.sellmair.example.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.sellmair.example.R import io.sellmair.example.destination.ChatDestination import io.sellmair.example.viewmodel.ChatViewModel import io.sellmair.kompass.tryAsChatDestination import java.util.* /** * Created by sebastiansellmair on 27.01.18. */ class ChatFragment : Fragment() { private lateinit var viewModel: ChatViewModel private lateinit var destination: ChatDestination override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) destination = arguments?.tryAsChatDestination() ?: throw IllegalStateException() val apCompatActivity = activity as AppCompatActivity apCompatActivity.supportActionBar?.title = destination.chatTitle apCompatActivity.supportActionBar?.subtitle = Date(destination.lastSeenTime).toString() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_chat, container, false) } }
1
null
1
1
855e3905f5367a41c00c7a45e5eaf35905c8f893
1,260
kompass
Apache License 2.0
KotlinMultiplatform/PokedexKMP/shared/src/commonMain/kotlin/core/service/PokemonService.kt
pradyotprksh
385,586,594
false
{"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 8581, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
package core.service import domain.modal.PokemonImage interface PokemonService { suspend fun getPokemonImages(): List<PokemonImage> }
0
Kotlin
11
24
4caa1e3995d2c51de8cc98183dd22486c4309292
139
development_learning
MIT License
common/src/commonMain/kotlin/com/greenmiststudios/common/presenters/HomePresenter.kt
geoff-powell
724,651,026
false
{"Kotlin": 51119, "Shell": 1867, "HTML": 1133, "JavaScript": 1073, "Swift": 590, "CSS": 161}
package com.greenmiststudios.common.presenters import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import com.greenmiststudios.common.viewmodels.HomeViewEvent import com.greenmiststudios.common.viewmodels.HomeViewModel import kotlinx.coroutines.flow.Flow public class HomePresenter : MoleculePresenter<HomeViewModel, HomeViewEvent> { @Composable override fun models(events: Flow<HomeViewEvent>): HomeViewModel { LaunchedEffect(Unit) { events.collect { event -> } } return HomeViewModel } }
7
Kotlin
0
0
b840f07187c079042a4349056d54769b2fe3df62
561
Tidy
Apache License 2.0
app/src/main/java/com/kgurgul/cpuinfo/utils/SingleLiveEvent.kt
kamgurgul
105,620,694
false
{"Kotlin": 296221, "C++": 4516, "CMake": 634, "AIDL": 461}
package com.kgurgul.cpuinfo.utils import androidx.annotation.MainThread import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import timber.log.Timber import java.util.concurrent.atomic.AtomicBoolean /** * A lifecycle-aware observable that sends only new updates after subscription, used for events like * navigation and Snackbar messages. * * This avoids a common problem with events: on configuration change (like rotation) an update * can be emitted if the observer is active. This LiveData only calls the observable if there's an * explicit call to setValue() or call(). * * Note that only one observer is going to be notified of changes. * * Fork from: https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp * /app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java */ class SingleLiveEvent<T> : MutableLiveData<T>() { private val pending = AtomicBoolean(false) override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { if (hasActiveObservers()) { Timber.w("Multiple observers registered but only one will be notified of changes.") } // Observe the internal MutableLiveData super.observe(owner) { t -> if (pending.compareAndSet(true, false)) { observer.onChanged(t) } } } @MainThread override fun setValue(t: T?) { pending.set(true) super.setValue(t) } /** * Used for cases where T is Void, to make calls cleaner. */ @MainThread fun call() { value = null } fun asLiveData(): LiveData<T> = this }
28
Kotlin
89
488
6aab426bc3b00e6c759d5bf64c93b07a36f7f0cf
1,770
cpu-info
Apache License 2.0
compose/common/src/dev/programadorthi/routing/compose/ComposeRoutingExt.kt
programadorthi
626,174,472
false
{"Kotlin": 518630, "JavaScript": 775}
package dev.programadorthi.routing.compose import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.staticCompositionLocalOf import dev.programadorthi.routing.core.Routing public val LocalPopResult: ProvidableCompositionLocal<ComposeRoutingPopResult?> = staticCompositionLocalOf { null } public fun Routing.canPop(): Boolean = contentList.size > 1 public fun Routing.pop(result: Any? = null) { contentList.removeLastOrNull() if (result == null) return val lastIndex = contentList.lastIndex if (lastIndex < 0) return val lastContent = contentList[lastIndex] val popResult = ComposeRoutingPopResult(content = result) contentList[lastIndex] = { CompositionLocalProvider(LocalPopResult provides popResult) { lastContent() } } }
0
Kotlin
2
42
6d289e939d8e317ffd74ea6bfef94ffe6b0734a0
886
kotlin-routing
Apache License 2.0
src/i_introduction/_4_Lambdas/n04Lambdas.kt
hnrck
128,468,183
true
{"Kotlin": 61224, "Java": 4952}
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun todoTask4(collection: Collection<Int>): Boolean = collection.any {it % 2 == 0} fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
0
Kotlin
0
0
03b83f43c416f68c9d9b0f62d8dd418d085bdcca
225
kotlin-koans
MIT License
app/src/main/java/com/sedsoftware/yaptalker/di/modules/contribution/FragmentContributionModule.kt
srihi
117,938,951
true
{"Kotlin": 350092, "Shell": 1229, "IDL": 510, "Prolog": 237, "CSS": 50}
package com.sedsoftware.yaptalker.di.modules.contribution import com.sedsoftware.yaptalker.di.scopes.FragmentScope import com.sedsoftware.yaptalker.presentation.features.activetopics.ActiveTopicsFragment import com.sedsoftware.yaptalker.presentation.features.activetopics.di.ActiveTopicsFragmentModule import com.sedsoftware.yaptalker.presentation.features.authorization.AuthorizationFragment import com.sedsoftware.yaptalker.presentation.features.authorization.di.AuthorizationFragmentModule import com.sedsoftware.yaptalker.presentation.features.bookmarks.BookmarksFragment import com.sedsoftware.yaptalker.presentation.features.bookmarks.di.BookmarksFragmentModule import com.sedsoftware.yaptalker.presentation.features.forum.ChosenForumFragment import com.sedsoftware.yaptalker.presentation.features.forum.di.ChosenForumFragmentModule import com.sedsoftware.yaptalker.presentation.features.forumslist.ForumsFragment import com.sedsoftware.yaptalker.presentation.features.forumslist.di.ForumsFragmentModule import com.sedsoftware.yaptalker.presentation.features.news.NewsFragment import com.sedsoftware.yaptalker.presentation.features.news.di.NewsFragmentModule import com.sedsoftware.yaptalker.presentation.features.posting.AddMessageFragment import com.sedsoftware.yaptalker.presentation.features.posting.di.AddMessageFragmentModule import com.sedsoftware.yaptalker.presentation.features.topic.ChosenTopicFragment import com.sedsoftware.yaptalker.presentation.features.topic.di.ChosenTopicFragmentModule import com.sedsoftware.yaptalker.presentation.features.userprofile.UserProfileFragment import com.sedsoftware.yaptalker.presentation.features.userprofile.di.UserProfileFragmentModule import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.android.support.AndroidSupportInjectionModule @Module(includes = [(AndroidSupportInjectionModule::class)]) interface FragmentContributionModule { @FragmentScope @ContributesAndroidInjector(modules = [(NewsFragmentModule::class)]) fun newsFragmentInjector(): NewsFragment @FragmentScope @ContributesAndroidInjector(modules = [(ActiveTopicsFragmentModule::class)]) fun activeTopicsFragmentInjector(): ActiveTopicsFragment @FragmentScope @ContributesAndroidInjector(modules = [(AuthorizationFragmentModule::class)]) fun authorizationFragmentInjector(): AuthorizationFragment @FragmentScope @ContributesAndroidInjector(modules = [(BookmarksFragmentModule::class)]) fun bookmarksFragmentInjector(): BookmarksFragment @FragmentScope @ContributesAndroidInjector(modules = [(ForumsFragmentModule::class)]) fun forumsListFragmentInjector(): ForumsFragment @FragmentScope @ContributesAndroidInjector(modules = [(ChosenForumFragmentModule::class)]) fun chosenForumFragmentInjector(): ChosenForumFragment @FragmentScope @ContributesAndroidInjector(modules = [(ChosenTopicFragmentModule::class)]) fun chosenTopicFragmentInjector(): ChosenTopicFragment @FragmentScope @ContributesAndroidInjector(modules = [(UserProfileFragmentModule::class)]) fun userProfileFragmentInjector(): UserProfileFragment @FragmentScope @ContributesAndroidInjector(modules = [(AddMessageFragmentModule::class)]) fun addMessageFragmentInjector(): AddMessageFragment }
0
Kotlin
0
0
e90fd7f7ed3024e1a58f9f8e0e1ba01cd986bcd1
3,271
YapTalker
Apache License 2.0
app/src/main/java/me/hegj/wandroid/mvp/presenter/main/tree/treeinfo/TreeinfoPresenter.kt
hegaojian
206,478,384
false
null
package me.hegj.wandroid.mvp.presenter.main.publicNumber import android.app.Application import com.jess.arms.di.scope.FragmentScope import com.jess.arms.http.imageloader.ImageLoader import com.jess.arms.integration.AppManager import com.jess.arms.mvp.BasePresenter import com.jess.arms.utils.RxLifecycleUtils import com.trello.rxlifecycle2.android.FragmentEvent import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import me.hegj.wandroid.app.utils.HttpUtils import me.hegj.wandroid.mvp.contract.main.publicNumber.PublicChildContract import me.hegj.wandroid.mvp.model.entity.ApiPagerResponse import me.hegj.wandroid.mvp.model.entity.ApiResponse import me.hegj.wandroid.mvp.model.entity.ArticleResponse import me.jessyan.rxerrorhandler.core.RxErrorHandler import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber import me.jessyan.rxerrorhandler.handler.RetryWithDelay import javax.inject.Inject /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 08/09/2019 11:03 * <a href="mailto:<EMAIL>">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ @FragmentScope class PublicChildPresenter @Inject constructor(model: PublicChildContract.Model, rootView: PublicChildContract.View) : BasePresenter<PublicChildContract.Model, PublicChildContract.View>(model, rootView) { @Inject lateinit var mErrorHandler: RxErrorHandler @Inject lateinit var mApplication: Application @Inject lateinit var mImageLoader: ImageLoader @Inject lateinit var mAppManager: AppManager fun getPublicDataByType(pageNo: Int, cid: Int) { mModel.getPublicDatas(pageNo, cid) .subscribeOn(Schedulers.io()) .retryWhen(RetryWithDelay(1, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(RxLifecycleUtils.bindUntilEvent(mRootView,FragmentEvent.DESTROY))//fragment的绑定方式 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁 .subscribe(object : ErrorHandleSubscriber<ApiResponse<ApiPagerResponse<MutableList<ArticleResponse>>>>(mErrorHandler) { override fun onNext(response: ApiResponse<ApiPagerResponse<MutableList<ArticleResponse>>>) { if (response.isSucces()) { mRootView.requestDataSuccess(response.data) } else { mRootView.requestDataFailed(response.errorMsg) } } override fun onError(t: Throwable) { super.onError(t) mRootView.requestDataFailed(HttpUtils.getErrorText(t)) } }) } /** * 收藏 */ fun collect(id:Int,position:Int) { mModel.collect(id) .subscribeOn(Schedulers.io()) .retryWhen(RetryWithDelay(1, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(RxLifecycleUtils.bindUntilEvent(mRootView, FragmentEvent.DESTROY))//fragment的绑定方式 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁 .subscribe(object : ErrorHandleSubscriber<ApiResponse<Any>>(mErrorHandler) { override fun onNext(response: ApiResponse<Any>) { if (response.isSucces()) { //收藏成功 mRootView.collect(true,position) }else{ //收藏失败 mRootView.collect(false,position) mRootView.showMessage(response.errorMsg) } } override fun onError(t: Throwable) { super.onError(t) //收藏失败 mRootView.collect(false,position) mRootView.showMessage(HttpUtils.getErrorText(t)) } }) } /** * 取消收藏 */ fun unCollect(id:Int, position:Int) { mModel.unCollect(id) .subscribeOn(Schedulers.io()) .retryWhen(RetryWithDelay(1, 0))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .compose(RxLifecycleUtils.bindUntilEvent(mRootView,FragmentEvent.DESTROY))//fragment的绑定方式 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁 .subscribe(object : ErrorHandleSubscriber<ApiResponse<Any>>(mErrorHandler) { override fun onNext(response: ApiResponse<Any>) { if (response.isSucces()) { //取消收藏成功 mRootView.collect(false,position) }else{ //取消收藏失败 mRootView.collect(true,position) mRootView.showMessage(response.errorMsg) } } override fun onError(t: Throwable) { super.onError(t) //取消收藏失败 mRootView.collect(true,position) mRootView.showMessage(HttpUtils.getErrorText(t)) } }) } }
1
null
100
713
622016c9695c01f3a134a23c4af1f76686aad6f1
5,867
WanAndroid
Apache License 2.0
library/src/main/java/com/github/skgmn/startactivityx/FragmentApplicationSupplier.kt
skgmn
389,001,523
false
null
package com.github.skgmn.startactivityx import android.app.Application import androidx.fragment.app.Fragment internal class FragmentApplicationSupplier(private val fragment: Fragment): ApplicationSupplier { private var app: Application? = null override fun getApplication(): Application? { return app ?: tryGetApplication()?.also { app = it } } private fun tryGetApplication(): Application? { return fragment.activity?.application ?: fragment.context?.applicationContext?.let { ctx -> ctx as? Application ?: InternalUtils.iterateContext(ctx).firstNotNullOfOrNull { it as? Application } } } }
0
Kotlin
0
5
43d4f12a2bae501dd26ebbc252a80b3638dad51c
712
StartActivityX
MIT License
ads/src/main/java/com/hms/lib/commonmobileservices/ads/rewarded/implementation/GoogleRewardedAd.kt
Explore-In-HMS
402,745,331
false
{"Kotlin": 593917}
// Copyright 2020. Explore in HMS. 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 com.hms.lib.commonmobileservices.ads.rewarded.implementation import android.app.Activity import android.os.Bundle import com.google.android.gms.ads.OnUserEarnedRewardListener import com.google.android.gms.ads.rewarded.OnAdMetadataChangedListener import com.google.android.gms.ads.rewarded.RewardItem import com.google.android.gms.ads.rewarded.RewardedAd import com.hms.lib.commonmobileservices.ads.rewarded.common.IRewardItem import com.hms.lib.commonmobileservices.ads.rewarded.common.UserRewardEarnedListener import com.hms.lib.commonmobileservices.ads.rewarded.common.MetaDataChangedListener class GoogleRewardedAd(private var _rewarded: RewardedAd) : IRewardedAd { override fun getMetaData(): Bundle = _rewarded.adMetadata override fun setOnMetadataChangedListener(callback: MetaDataChangedListener) { val listener = OnAdMetadataChangedListener { callback.onMetaDataChanged() } _rewarded.onAdMetadataChangedListener = listener } override fun setImmersive(value: Boolean) { _rewarded.setImmersiveMode(value) } override fun show(activity: Activity, callback: UserRewardEarnedListener) { val listener = object : OnUserEarnedRewardListener { override fun onUserEarnedReward(p0: RewardItem) { val rewardItem = object : IRewardItem { override fun getAmount(): Int { return p0.amount } override fun getTypeOrName(): String { return p0.type } } callback.onUserEarnedReward(rewardItem) } } _rewarded.show(activity, listener) } }
3
Kotlin
6
50
68640eadd9950bbdd9aac52dad8d22189a301859
2,322
common-mobile-services
Apache License 2.0
frogothemoviedbapi/src/main/java/com/frogobox/frogothemoviedbapi/data/response/TvContentRatings.kt
amirisback
244,968,500
false
null
package com.frogobox.frogothemoviedbapi.data.response import com.frogobox.frogothemoviedbapi.data.model.TvContentRatingsResult data class TvContentRatings( val id: Int?, val results: List<TvContentRatingsResult>? )
0
Kotlin
2
17
ba2dd472185525a52c505e353c04fc5cc8f501b0
224
consumable-code-movie-tmdb-api
Apache License 2.0
app/src/main/java/com/vipulasri/jetinstagram/ui/home/Profile.kt
mkCoding
811,348,897
false
{"Kotlin": 55389}
package com.vipulasri.jetinstagram.ui.home fun Profile(){ }
0
Kotlin
0
0
72280c926c9ca92c686726e6d097b9fb066ad2f0
63
JetInstagram
Apache License 2.0
entity/src/main/java/com/kevalpatel2106/yip/entity/DeadlineType.kt
kevalpatel2106
166,789,807
false
null
package com.kevalpatel2106.yip.entity @Suppress("MagicNumber") enum class DeadlineType(val key: Int, val color: DeadlineColor) { YEAR_DEADLINE(key = 8459, color = DeadlineColor.COLOR_BLUE), DAY_DEADLINE(key = 346, color = DeadlineColor.COLOR_PINK), WEEK_DEADLINE(key = 54532, color = DeadlineColor.COLOR_YELLOW), MONTH_DEADLINE(key = 123, color = DeadlineColor.COLOR_GREEN), QUARTER_DEADLINE(key = 4534, color = DeadlineColor.COLOR_TILL), CUSTOM(key = 3411, color = DeadlineColor.COLOR_PINK) }
0
Kotlin
1
16
61311ba7d40802ba7fed87b2f16b72089c6f7746
519
year-in-progress
Apache License 2.0
androidutilskt/src/main/java/com/lindroid/androidutilskt/extension/logcat/LogLevel.kt
Lindroy
172,827,942
false
null
package com.lindroid.androidutilskt.extension.logcat import android.support.annotation.IntDef import android.util.Log /** * @author Lin * @date 2019/3/19 * @function 日志等级 * @Description */ const val VERBOSE = Log.VERBOSE const val DEBUG = Log.DEBUG const val INFO = Log.INFO const val WARN = Log.WARN const val ERROR = Log.ERROR const val ASSERT = Log.ASSERT @IntDef(VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT) @Target(AnnotationTarget.FIELD, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE) @Retention(AnnotationRetention.SOURCE) annotation class LogLevel fun logLevel(@LogLevel level: Int) = when(level){ VERBOSE->"VERBOSE" DEBUG->"DEBUG" INFO->"INFO" WARN->"WARN" ERROR->"ERROR" ASSERT->"ASSERT" else->"UNKNOWN" }
0
null
19
48
5d6832813a4a0dba7290ad5ef92959f638ea51ab
761
AndroidUtilsKt
Apache License 2.0
buildSrc/src/main/kotlin/Plugin.kt
maksonic
580,058,579
false
null
import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.kotlin import org.gradle.kotlin.dsl.version import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.PluginDependencySpec /** * @Author maksonic on 15.12.2022 */ fun PluginDependenciesSpec.pluginAndroidApp(): PluginDependencySpec = id("com.android.application") version ("7.4.1") apply false fun PluginDependenciesSpec.pluginAndroidLibrary(): PluginDependencySpec = id("com.android.library") version ("7.4.1") apply false fun PluginDependenciesSpec.pluginKotlinAndroid(): PluginDependencySpec = kotlin("android") version (Build.Version.KOTLIN_GRADLE) apply false fun PluginDependenciesSpec.pluginKotlinSerialization(): PluginDependencySpec = kotlin("plugin.serialization") version (Build.Version.KOTLIN_GRADLE) apply false fun PluginDependenciesSpec.androidApp(): PluginDependencySpec = id("com.android.application") fun PluginDependenciesSpec.androidLibrary(): PluginDependencySpec = id("com.android.library") fun PluginDependenciesSpec.kotlinAndroid(): PluginDependencySpec = kotlin("android") fun PluginDependenciesSpec.kotlinSerialization(): PluginDependencySpec = id("kotlinx-serialization") fun PluginDependenciesSpec.ksp(): PluginDependencySpec = id("com.google.devtools.ksp") version Config.kspVersion fun PluginDependenciesSpec.parcelize(): PluginDependencySpec = id("kotlin-parcelize")
0
Kotlin
0
0
5704d413cd57a8eabe27b02a185a999fce2ca1e4
1,436
Beresta
MIT License
app/src/main/java/com/udacity/shoestore/screens/shoe_list/ShopViewModelFactory.kt
adrianpbv
372,412,404
false
null
package com.udacity.shoestore.screens.shoe_list import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.udacity.shoestore.models.Shoe // factory to create a ShopViewModel with an argument as it is initialized class ShopViewModelFactory(private val shoe: Shoe?) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(ShopViewModel::class.java)) { //return ShopViewModel(shoe) as return ShopViewModel() as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
0
37cdb5c9fa823d0eb5aa3b3eeabf5595c8467986
691
shoestore
MIT License
src/main/kotlin/dev/fakek/interfaces/Company.kt
CodyEngel
226,218,138
false
null
package dev.fakek.interfaces /** * Company in an interface to implement fake companies. */ interface Company { /** * @property bs company corporate speak ex: "energistically mesh e-business opportunities". */ val bs: String /** * @property buzzword */ val buzzword: String /** * @property catchPhrase */ val catchPhrase: String /** * @property industry */ val industry: String /** * @property logo random url of the company logo. */ val logo: String /** * @property name */ val name: String /** * @property profession */ val profession: String /** * @property suffix */ val suffix: String /** * @property url random url of company website. */ val url: String }
6
Kotlin
7
7
e3d1442059b1196a020c71fb9424266bf12fe1a1
826
fakek
Apache License 2.0
app/src/main/java/com/peruapps/christopher_elias/ui/holder/MasterViewHolder.kt
ChristopherME
189,524,605
false
null
package com.peruapps.christopher_elias.ui.holder import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView /** * Created by <NAME> on 29-may-2019 * <EMAIL> * Lima, Perú * Copyright (c) 2019 All rights reserved. */ class MasterViewHolder<out V : ViewDataBinding>(val binding: V) : RecyclerView.ViewHolder(binding.root)
0
Kotlin
0
0
785b1e3938a69936b0c0732f82cb6b40fbfc8d0b
361
senior-test
Apache License 2.0
ui/ui-core/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeView.kt
zengjuly
351,458,785
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.content.res.Configuration import android.graphics.Rect import android.os.Build import android.os.Handler import android.os.Looper import android.util.Log import android.util.SparseArray import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewStructure import android.view.ViewTreeObserver import android.view.autofill.AutofillValue import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import androidx.compose.runtime.ExperimentalComposeApi import androidx.compose.runtime.snapshots.SnapshotStateObserver import androidx.compose.ui.DrawLayerModifier import androidx.compose.ui.Modifier import androidx.compose.ui.RootMeasureBlocks import androidx.compose.ui.autofill.AndroidAutofill import androidx.compose.ui.autofill.Autofill import androidx.compose.ui.autofill.AutofillTree import androidx.compose.ui.autofill.performAutofill import androidx.compose.ui.autofill.populateViewStructure import androidx.compose.ui.autofill.registerCallback import androidx.compose.ui.autofill.unregisterCallback import androidx.compose.ui.drawLayer import androidx.compose.ui.focus.ExperimentalFocus import androidx.compose.ui.focus.FOCUS_TAG import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.focus.FocusManagerImpl import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.CanvasHolder import androidx.compose.ui.hapticfeedback.AndroidHapticFeedback import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.input.key.ExperimentalKeyInput import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventAndroid import androidx.compose.ui.input.key.KeyInputModifier import androidx.compose.ui.input.pointer.MotionEventAdapter import androidx.compose.ui.input.pointer.PointerInputEventProcessor import androidx.compose.ui.input.pointer.ProcessResult import androidx.compose.ui.node.ExperimentalLayoutNodeApi import androidx.compose.ui.node.InternalCoreApi import androidx.compose.ui.node.OwnerScope import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.node.LayoutNode.UsageByParent import androidx.compose.ui.node.MeasureAndLayoutDelegate import androidx.compose.ui.node.OwnedLayer import androidx.compose.ui.semantics.SemanticsModifierCore import androidx.compose.ui.semantics.SemanticsOwner import androidx.compose.ui.text.InternalTextApi import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.input.TextInputServiceAndroid import androidx.compose.ui.text.input.textInputServiceFactory import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.util.trace import androidx.core.os.HandlerCompat import androidx.core.view.ViewCompat import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.lifecycle.ViewTreeViewModelStoreOwner import androidx.savedstate.ViewTreeSavedStateRegistryOwner import java.lang.reflect.Method import android.view.KeyEvent as AndroidKeyEvent @SuppressLint("ViewConstructor") @OptIn( ExperimentalComposeApi::class, ExperimentalFocus::class, ExperimentalKeyInput::class, ExperimentalLayoutNodeApi::class ) @TargetApi(Build.VERSION_CODES.LOLLIPOP) internal class AndroidComposeView(context: Context) : ViewGroup(context), AndroidOwner { override val view: View = this override var density = Density(context) private set private val semanticsModifier = SemanticsModifierCore( id = SemanticsModifierCore.generateSemanticsId(), mergeAllDescendants = false, properties = {} ) private val _focusManager: FocusManagerImpl = FocusManagerImpl() override val focusManager: FocusManager get() = _focusManager private val keyInputModifier = KeyInputModifier(null, null) private val canvasHolder = CanvasHolder() override val root = LayoutNode().also { it.measureBlocks = RootMeasureBlocks it.modifier = Modifier .drawLayer() .then(semanticsModifier) .then(_focusManager.modifier) .then(keyInputModifier) } override val semanticsOwner: SemanticsOwner = SemanticsOwner(root) private val accessibilityDelegate = AndroidComposeViewAccessibilityDelegateCompat(this) // Used by components that want to provide autofill semantic information. // TODO: Replace with SemanticsTree: Temporary hack until we have a semantics tree implemented. // TODO: Replace with SemanticsTree. // This is a temporary hack until we have a semantics tree implemented. override val autofillTree = AutofillTree() // OwnedLayers that are dirty and should be redrawn. internal val dirtyLayers = mutableListOf<OwnedLayer>() private val motionEventAdapter = MotionEventAdapter() private val pointerInputEventProcessor = PointerInputEventProcessor(root) // TODO(mount): reinstate when coroutines are supported by IR compiler // private val ownerScope = CoroutineScope(Dispatchers.Main.immediate + Job()) // Used for updating the ConfigurationAmbient when configuration changes - consume the // configuration ambient instead of changing this observer if you are writing a component that // adapts to configuration changes. override var configurationChangeObserver: (Configuration) -> Unit = {} private val _autofill = if (autofillSupported()) AndroidAutofill(this, autofillTree) else null // Used as an ambient for performing autofill. override val autofill: Autofill? get() = _autofill private var observationClearRequested = false override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) Log.d(FOCUS_TAG, "Owner FocusChanged($gainFocus)") with(_focusManager) { if (gainFocus) takeFocus() else releaseFocus() } } override fun sendKeyEvent(keyEvent: KeyEvent): Boolean { return keyInputModifier.processKeyInput(keyEvent) } override fun dispatchKeyEvent(event: AndroidKeyEvent): Boolean { return sendKeyEvent(KeyEventAndroid(event)) } private val snapshotObserver = SnapshotStateObserver { command -> if (handler.looper === Looper.myLooper()) { command() } else { handler.post(command) } } private val onCommitAffectingMeasure: (LayoutNode) -> Unit = { layoutNode -> onRequestMeasure(layoutNode) } private val onCommitAffectingLayout: (LayoutNode) -> Unit = { layoutNode -> if (measureAndLayoutDelegate.requestRelayout(layoutNode)) { scheduleMeasureAndLayout() } } private val onCommitAffectingLayer: (OwnedLayer) -> Unit = { layer -> layer.invalidate() } private val onCommitAffectingLayerParams: (OwnedLayer) -> Unit = { layer -> handler.postAtFrontOfQueue { updateLayerProperties(layer) } } @OptIn(InternalCoreApi::class) override var showLayoutBounds = false override fun pauseModelReadObserveration(block: () -> Unit) = snapshotObserver.pauseObservingReads(block) init { setWillNotDraw(false) isFocusable = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { focusable = View.FOCUSABLE // not to add the default focus highlight to the whole compose view defaultFocusHighlightEnabled = false } isFocusableInTouchMode = true clipChildren = false root.isPlaced = true ViewCompat.setAccessibilityDelegate(this, accessibilityDelegate) AndroidOwner.onAndroidOwnerCreatedCallback?.invoke(this) } override fun onAttach(node: LayoutNode) { } override fun onDetach(node: LayoutNode) { measureAndLayoutDelegate.onNodeDetached(node) requestClearInvalidObservations() } fun requestClearInvalidObservations() { if (!observationClearRequested) { observationClearRequested = true post { observationClearRequested = false snapshotObserver.removeObservationsFor { !(it as OwnerScope).isValid } } } } private var _androidViewsHandler: AndroidViewsHandler? = null private val androidViewsHandler: AndroidViewsHandler get() { if (_androidViewsHandler == null) { _androidViewsHandler = AndroidViewsHandler(context) addView(_androidViewsHandler) } return _androidViewsHandler!! } private val viewLayersContainer by lazy(LazyThreadSafetyMode.NONE) { ViewLayerContainer(context).also { addView(it) } } override fun addAndroidView(view: View, layoutNode: LayoutNode) { androidViewsHandler.layoutNode[view] = layoutNode androidViewsHandler.addView(view) } override fun removeAndroidView(view: View) { androidViewsHandler.removeView(view) androidViewsHandler.layoutNode.remove(view) } // [ Layout block start ] // The constraints being used by the last onMeasure. It is set to null in onLayout. It allows // us to detect the case when the View was measured twice with different constraints within // the same measure pass. private var onMeasureConstraints: Constraints? = null // Will be set to true when we were measured twice with different constraints during the last // measure pass. private var wasMeasuredWithMultipleConstraints = false private val measureAndLayoutDelegate = MeasureAndLayoutDelegate(root) private var measureAndLayoutScheduled = false private val measureAndLayoutHandler: Handler = HandlerCompat.createAsync(Looper.getMainLooper()) { measureAndLayoutScheduled = false measureAndLayout() true } private fun scheduleMeasureAndLayout(nodeToRemeasure: LayoutNode? = null) { if (!isLayoutRequested) { if (wasMeasuredWithMultipleConstraints && nodeToRemeasure != null) { // if nodeToRemeasure can potentially resize the root and the view was measured // twice with different constraints last time it means the constraints we have could // be not the final constraints and in fact our parent ViewGroup can remeasure us // with larger constraints if we call requestLayout() var node = nodeToRemeasure while (node != null && node.measuredByParent == UsageByParent.InMeasureBlock) { node = node.parent } if (node === root) { requestLayout() return } } if (!measureAndLayoutScheduled) { measureAndLayoutScheduled = true measureAndLayoutHandler.sendEmptyMessage(0) } } } override val measureIteration: Long get() = measureAndLayoutDelegate.measureIteration override fun measureAndLayout() { val rootNodeResized = measureAndLayoutDelegate.measureAndLayout() if (rootNodeResized) { requestLayout() } measureAndLayoutDelegate.dispatchOnPositionedCallbacks() } override fun onRequestMeasure(layoutNode: LayoutNode) { if (measureAndLayoutDelegate.requestRemeasure(layoutNode)) { scheduleMeasureAndLayout(layoutNode) } } override fun onRequestRelayout(layoutNode: LayoutNode) { if (measureAndLayoutDelegate.requestRelayout(layoutNode)) { scheduleMeasureAndLayout() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { trace("AndroidOwner:onMeasure") { val (minWidth, maxWidth) = convertMeasureSpec(widthMeasureSpec) val (minHeight, maxHeight) = convertMeasureSpec(heightMeasureSpec) val constraints = Constraints(minWidth, maxWidth, minHeight, maxHeight) if (onMeasureConstraints == null) { // first onMeasure after last onLayout onMeasureConstraints = constraints wasMeasuredWithMultipleConstraints = false } else if (onMeasureConstraints != constraints) { // we were remeasured twice with different constraints after last onLayout wasMeasuredWithMultipleConstraints = true } measureAndLayoutDelegate.updateRootConstraints(constraints) measureAndLayoutDelegate.measureAndLayout() setMeasuredDimension(root.width, root.height) } } private fun convertMeasureSpec(measureSpec: Int): Pair<Int, Int> { val mode = MeasureSpec.getMode(measureSpec) val size = MeasureSpec.getSize(measureSpec) return when (mode) { MeasureSpec.EXACTLY -> size to size MeasureSpec.UNSPECIFIED -> 0 to Constraints.Infinity MeasureSpec.AT_MOST -> 0 to size else -> throw IllegalStateException() } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { onMeasureConstraints = null // we postpone onPositioned callbacks until onLayout as LayoutCoordinates // are currently wrong if you try to get the global(activity) coordinates - // View is not yet laid out. updatePositionCacheAndDispatch() if (_androidViewsHandler != null && androidViewsHandler.isLayoutRequested) { // Even if we laid out during onMeasure, this can happen when the Views hierarchy // receives forceLayout(). We need to relayout to clear the isLayoutRequested info // on the Views, as otherwise further layout requests will be discarded. androidViewsHandler.layout(0, 0, r - l, b - t) } } override val hasPendingMeasureOrLayout get() = measureAndLayoutDelegate.hasPendingMeasureOrLayout private var globalPosition: IntOffset = IntOffset.Zero private val tmpPositionArray = intArrayOf(0, 0) // Used to track whether or not there was an exception while creating an MRenderNode // so that we don't have to continue using try/catch after fails once. private var isRenderNodeCompatible = true private fun updatePositionCacheAndDispatch() { var positionChanged = false getLocationOnScreen(tmpPositionArray) if (globalPosition.x != tmpPositionArray[0] || globalPosition.y != tmpPositionArray[1]) { globalPosition = IntOffset(tmpPositionArray[0], tmpPositionArray[1]) positionChanged = true } measureAndLayoutDelegate.dispatchOnPositionedCallbacks(forceDispatch = positionChanged) } // [ Layout block end ] override fun observeLayoutModelReads(node: LayoutNode, block: () -> Unit) { snapshotObserver.observeReads(node, onCommitAffectingLayout, block) } override fun observeMeasureModelReads(node: LayoutNode, block: () -> Unit) { snapshotObserver.observeReads(node, onCommitAffectingMeasure, block) } override fun <T : OwnerScope> observeReads( target: T, onChanged: (T) -> Unit, block: () -> Unit ) { snapshotObserver.observeReads(target, onChanged, block) } fun observeLayerModelReads(layer: OwnedLayer, block: () -> Unit) { snapshotObserver.observeReads(layer, onCommitAffectingLayer, block) } override fun onDraw(canvas: android.graphics.Canvas) { } override fun createLayer( drawLayerModifier: DrawLayerModifier, drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit ): OwnedLayer { val layer = instantiateLayer(drawLayerModifier, drawBlock, invalidateParentLayer) updateLayerProperties(layer) return layer } private fun instantiateLayer( drawLayerModifier: DrawLayerModifier, drawBlock: (Canvas) -> Unit, invalidateParentLayer: () -> Unit ): OwnedLayer { // RenderNode is supported on Q+ for certain, but may also be supported on M-O. // We can't be confident that RenderNode is supported, so we try and fail over to // the ViewLayer implementation. We'll try even on on P devices, but it will fail // until ART allows things on the unsupported list on P. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isRenderNodeCompatible) { try { return RenderNodeLayer( this, drawLayerModifier, drawBlock, invalidateParentLayer ) } catch (_: Throwable) { isRenderNodeCompatible = false } } return ViewLayer( this, viewLayersContainer, drawLayerModifier, drawBlock, invalidateParentLayer ) } override fun onSemanticsChange() { accessibilityDelegate.onSemanticsChange() } private fun updateLayerProperties(layer: OwnedLayer) { snapshotObserver.observeReads(layer, onCommitAffectingLayerParams) { layer.updateLayerProperties() } } override fun dispatchDraw(canvas: android.graphics.Canvas) { measureAndLayout() // we don't have to observe here because the root has a layer modifier // that will observe all children. The AndroidComposeView has only the // root, so it doesn't have to invalidate itself based on model changes. canvasHolder.drawInto(canvas) { root.draw(this) } if (dirtyLayers.isNotEmpty()) { for (i in 0 until dirtyLayers.size) { val layer = dirtyLayers[i] layer.updateDisplayList() } dirtyLayers.clear() } } override var viewTreeOwners: AndroidOwner.ViewTreeOwners? = null private set override fun setOnViewTreeOwnersAvailable(callback: (AndroidOwner.ViewTreeOwners) -> Unit) { val viewTreeOwners = viewTreeOwners if (viewTreeOwners != null) { callback(viewTreeOwners) } else { onViewTreeOwnersAvailable = callback } } private var onViewTreeOwnersAvailable: ((AndroidOwner.ViewTreeOwners) -> Unit)? = null // executed when the layout pass has been finished. as a result of it our view could be moved // inside the window (we are interested not only in the event when our parent positioned us // on a different position, but also in the position of each of the grandparents as all these // positions add up to final global position) private val globalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener { updatePositionCacheAndDispatch() } // executed when a scrolling container like ScrollView of RecyclerView performed the scroll, // this could affect our global position private val scrollChangedListener = ViewTreeObserver.OnScrollChangedListener { updatePositionCacheAndDispatch() } override fun onAttachedToWindow() { super.onAttachedToWindow() showLayoutBounds = getIsShowingLayoutBounds() snapshotObserver.enableStateUpdatesObserving(true) ifDebug { if (autofillSupported()) _autofill?.registerCallback() } root.attach(this) if (viewTreeOwners == null) { val lifecycleOwner = ViewTreeLifecycleOwner.get(this) ?: throw IllegalStateException( "Composed into the View which doesn't propagate ViewTreeLifecycleOwner!" ) val viewModelStoreOwner = ViewTreeViewModelStoreOwner.get(this) ?: throw IllegalStateException( "Composed into the View which doesn't propagate ViewTreeViewModelStoreOwner!" ) val savedStateRegistryOwner = ViewTreeSavedStateRegistryOwner.get(this) ?: throw IllegalStateException( "Composed into the View which doesn't propagate" + "ViewTreeSavedStateRegistryOwner!" ) val viewTreeOwners = AndroidOwner.ViewTreeOwners( lifecycleOwner = lifecycleOwner, viewModelStoreOwner = viewModelStoreOwner, savedStateRegistryOwner = savedStateRegistryOwner ) this.viewTreeOwners = viewTreeOwners onViewTreeOwnersAvailable?.invoke(viewTreeOwners) onViewTreeOwnersAvailable = null } viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener) viewTreeObserver.addOnScrollChangedListener(scrollChangedListener) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() snapshotObserver.clear() snapshotObserver.enableStateUpdatesObserving(false) ifDebug { if (autofillSupported()) _autofill?.unregisterCallback() } if (measureAndLayoutScheduled) { measureAndLayoutHandler.removeMessages(0) } root.detach() viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener) viewTreeObserver.removeOnScrollChangedListener(scrollChangedListener) } override fun onProvideAutofillVirtualStructure(structure: ViewStructure?, flags: Int) { if (autofillSupported() && structure != null) _autofill?.populateViewStructure(structure) } override fun autofill(values: SparseArray<AutofillValue>) { if (autofillSupported()) _autofill?.performAutofill(values) } // TODO(shepshapard): Test this method. override fun dispatchTouchEvent(motionEvent: MotionEvent): Boolean { measureAndLayout() // TODO(b/166848812): Calling updatePositionCacheAndDispatch here seems necessary because // if the soft keyboard being displayed causes the AndroidComposeView to be offset from // the screen, we don't seem to have any timely callback that updates our globalPosition // cache. ViewTreeObserver.OnGlobalLayoutListener gets called, but not when the keyboard // opens. And when it gets called as the keyboard is closing, it is called before the // keyboard actually closes causing the globalPosition to be wrong. // TODO(shepshapard): There is no test to garuntee that this method is called here as doing // so proved to be very difficult. A test should be added. updatePositionCacheAndDispatch() val processResult = trace("AndroidOwner:onTouch") { val pointerInputEvent = motionEventAdapter.convertToPointerInputEvent(motionEvent) if (pointerInputEvent != null) { pointerInputEventProcessor.process(pointerInputEvent) } else { pointerInputEventProcessor.processCancel() ProcessResult( dispatchedToAPointerInputModifier = false, anyMovementConsumed = false ) } } if (processResult.anyMovementConsumed) { parent.requestDisallowInterceptTouchEvent(true) } return processResult.dispatchedToAPointerInputModifier } private val textInputServiceAndroid = TextInputServiceAndroid(this) override val textInputService = @OptIn(InternalTextApi::class) @Suppress("DEPRECATION_ERROR") textInputServiceFactory(textInputServiceAndroid) override val fontLoader: Font.ResourceLoader = AndroidFontResourceLoader(context) override var layoutDirection = context.resources.configuration.localeLayoutDirection private set /** * Provide haptic feedback to the user. Use the Android version of haptic feedback. */ override val hapticFeedBack: HapticFeedback = AndroidHapticFeedback(this) /** * Provide clipboard manager to the user. Use the Android version of clipboard manager. */ override val clipboardManager: ClipboardManager = AndroidClipboardManager(context) /** * Provide textToolbar to the user, for text-related operation. Use the Android version of * floating toolbar(post-M) and primary toolbar(pre-M). */ override val textToolbar: TextToolbar = AndroidTextToolbar(this) override fun onCheckIsTextEditor(): Boolean = textInputServiceAndroid.isEditorFocused() override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? = textInputServiceAndroid.createInputConnection(outAttrs) override fun calculatePosition(): IntOffset = globalPosition override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) density = Density(context) layoutDirection = context.resources.configuration.localeLayoutDirection configurationChangeObserver(newConfig) } private fun autofillSupported() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O public override fun dispatchHoverEvent(event: MotionEvent): Boolean { return accessibilityDelegate.dispatchHoverEvent(event) } companion object { private var systemPropertiesClass: Class<*>? = null private var getBooleanMethod: Method? = null // TODO(mount): replace with ViewCompat.isShowingLayoutBounds() when it becomes available. @SuppressLint("PrivateApi") private fun getIsShowingLayoutBounds(): Boolean = try { if (systemPropertiesClass == null) { systemPropertiesClass = Class.forName("android.os.SystemProperties") getBooleanMethod = systemPropertiesClass?.getDeclaredMethod( "getBoolean", String::class.java, Boolean::class.java ) } getBooleanMethod?.invoke(null, "debug.layout", false) as? Boolean ?: false } catch (e: Exception) { false } } } /** * Return the layout direction set by the [Locale][java.util.Locale]. * * A convenience getter that translates [Configuration.getLayoutDirection] result into * [LayoutDirection] instance. */ internal val Configuration.localeLayoutDirection: LayoutDirection // We don't use the attached View's layout direction here since that layout direction may not // be resolved since the composables may be composed without attaching to the RootViewImpl. // In Jetpack Compose, use the locale layout direction (i.e. layoutDirection came from // configuration) as a default layout direction. get() = when (layoutDirection) { android.util.LayoutDirection.LTR -> LayoutDirection.Ltr android.util.LayoutDirection.RTL -> LayoutDirection.Rtl // Configuration#getLayoutDirection should only return a resolved layout direction, LTR // or RTL. Fallback to LTR for unexpected return value. else -> LayoutDirection.Ltr }
1
null
1
1
fbe346d9edeb2b6137e327e16d0fe6c67364e28b
27,975
androidx
Apache License 2.0
src/main/kotlin/io/unthrottled/amii/assets/APIContentManager.kt
ani-memes
303,354,188
false
null
package io.unthrottled.amii.assets import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import io.unthrottled.amii.assets.LocalStorageService.readLocalFile import io.unthrottled.amii.platform.LifeCycleManager import io.unthrottled.amii.platform.UpdateAssetsListener import io.unthrottled.amii.services.ExecutionService import io.unthrottled.amii.tools.doOrElse import java.io.InputStream import java.net.URI import java.util.Optional // todo: post mvp: consolidate abstract class APIContentManager<T : AssetRepresentation>( private val assetCategory: AssetCategory, ) : HasStatus { private lateinit var assetRepresentations: List<T> override var status = Status.UNKNOWN private val log = Logger.getInstance(this::class.java) init { val apiPath = "assets/${assetCategory.category}" cachedInitialization(apiPath) LifeCycleManager.registerAssetUpdateListener(object : UpdateAssetsListener { override fun onRequestedUpdate() { ExecutionService.executeAsynchronously { initializeAssetCaches( APIAssetManager.forceResolveAssetUrl(apiPath), breakOnFailure = false ) } } override fun onRequestedBackgroundUpdate() { cachedInitialization(apiPath) } }) } private fun cachedInitialization(apiPath: String) { initializeAssetCaches( APIAssetManager.resolveAssetUrl(apiPath) { convertToDefinitions(it) } ) } private fun initializeAssetCaches( assetFileUrl: Optional<URI>, breakOnFailure: Boolean = true ) { assetFileUrl .flatMap { assetUrl -> initializeRemoteAssets(assetUrl) } .doOrElse({ allAssetDefinitions -> status = Status.OK assetRepresentations = allAssetDefinitions }) { if (breakOnFailure) { status = Status.BROKEN assetRepresentations = listOf() } } ApplicationManager.getApplication().messageBus.syncPublisher(ContentManagerListener.TOPIC) .onUpdate(assetCategory) } fun supplyAssets(): List<T> = assetRepresentations private fun initializeRemoteAssets(assetUrl: URI): Optional<List<T>> = try { readLocalFile(assetUrl) .flatMap { convertToDefinitions(it) } } catch (e: Throwable) { log.error("Unable to initialize asset metadata.", e) Optional.empty() } abstract fun convertToDefinitions(defJson: String): Optional<List<T>> abstract fun convertToDefinitions(defJson: InputStream): Optional<List<T>> }
7
null
14
257
c9a4ef10f6e1a5ce68dc3a007b45cadbc33deed0
2,586
AMII
Apache License 2.0
api/coroutines/v1.5.4/src/commonMain/kotlin/dev/whyoleg/ktd/api/contact/ImportContacts.kt
whyoleg
202,767,670
false
null
@file:Suppress( "unused" ) @file:UseExperimental( BotsOnly::class, TestingOnly::class ) package dev.whyoleg.ktd.api.contact import dev.whyoleg.ktd.* import dev.whyoleg.ktd.api.* import dev.whyoleg.ktd.api.TdApi.* /** * Adds new contacts or edits existing contacts by their phone numbers * Contacts' user identifiers are ignored * * @contacts - The list of contacts to import or edit * Contacts' vCard are ignored and are not imported */ suspend fun TelegramClient.importContacts( contacts: Array<Contact> = emptyArray() ): ImportedContacts = contact( ImportContacts( contacts ) ) /** * Adds new contacts or edits existing contacts by their phone numbers * Contacts' user identifiers are ignored */ suspend fun TelegramClient.contact( f: ImportContacts ): ImportedContacts = exec(f) as ImportedContacts
7
Kotlin
11
45
7284eeabef0bd002dc72634351ab751b048900e9
863
ktd
Apache License 2.0
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/uicomponents/conversationinfo/media/viewmodel/ChannelAttachmentsViewModel.kt
sceyt
549,073,085
false
{"Kotlin": 2713714, "Java": 107920}
package com.sceyt.chatuikit.presentation.components.channel_info.media.viewmodel import android.app.Application import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asFlow import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewModelScope import androidx.work.ExistingWorkPolicy import com.sceyt.chatuikit.data.models.PaginationResponse import com.sceyt.chatuikit.data.models.SceytResponse import com.sceyt.chatuikit.data.models.messages.AttachmentTypeEnum import com.sceyt.chatuikit.data.models.messages.AttachmentWithUserData import com.sceyt.chatuikit.data.models.messages.LinkPreviewDetails import com.sceyt.chatuikit.data.models.messages.SceytAttachment import com.sceyt.chatuikit.persistence.extensions.asLiveData import com.sceyt.chatuikit.persistence.file_transfer.FileTransferHelper import com.sceyt.chatuikit.persistence.file_transfer.FileTransferService import com.sceyt.chatuikit.persistence.file_transfer.NeedMediaInfoData import com.sceyt.chatuikit.persistence.file_transfer.TransferData import com.sceyt.chatuikit.persistence.file_transfer.TransferState import com.sceyt.chatuikit.persistence.logic.PersistenceAttachmentLogic import com.sceyt.chatuikit.persistence.workers.SendAttachmentWorkManager import com.sceyt.chatuikit.presentation.components.channel_info.ChannelFileItem import com.sceyt.chatuikit.presentation.root.BaseViewModel import com.sceyt.chatuikit.shared.helpers.LinkPreviewHelper import com.sceyt.chatuikit.shared.utils.DateTimeUtil import com.sceyt.chatuikit.styles.channel_info.ChannelInfoStyle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch class ChannelAttachmentsViewModel( private val attachmentLogic: PersistenceAttachmentLogic, private val fileTransferService: FileTransferService, private val application: Application ) : BaseViewModel() { private val linkPreviewHelper by lazy { LinkPreviewHelper(application, viewModelScope) } private val needToUpdateTransferAfterOnResume = hashMapOf<Long, TransferData>() lateinit var infoStyle: ChannelInfoStyle private val _filesFlow = MutableSharedFlow<List<ChannelFileItem>>( extraBufferCapacity = 5, onBufferOverflow = BufferOverflow.DROP_OLDEST) val filesFlow: SharedFlow<List<ChannelFileItem>> = _filesFlow private val _loadMoreFilesFlow = MutableSharedFlow<List<ChannelFileItem>>( extraBufferCapacity = 5, onBufferOverflow = BufferOverflow.DROP_OLDEST) val loadMoreFilesFlow: SharedFlow<List<ChannelFileItem>> = _loadMoreFilesFlow private val _linkPreviewLiveData = MutableLiveData<LinkPreviewDetails>() val linkPreviewLiveData = _linkPreviewLiveData.asLiveData() init { viewModelScope.launch(Dispatchers.IO) { attachmentLogic.setupFileTransferUpdateObserver() } } fun loadAttachments(channelId: Long, lastAttachmentId: Long, isLoadingMore: Boolean, type: List<String>, offset: Int) { setPagingLoadingStarted(PaginationResponse.LoadType.LoadPrev) notifyPageLoadingState(isLoadingMore) viewModelScope.launch(Dispatchers.IO) { attachmentLogic.getPrevAttachments(channelId, lastAttachmentId, type, offset).collect { response -> initPaginationResponse(response) } } } private fun initPaginationResponse(response: PaginationResponse<AttachmentWithUserData>) { when (response) { is PaginationResponse.DBResponse -> { if (!checkIgnoreDatabasePagingResponse(response)) { initPaginationDbResponse(response) } } is PaginationResponse.ServerResponse -> initPaginationServerResponse(response) else -> return } pagingResponseReceived(response) } private fun initPaginationDbResponse(response: PaginationResponse.DBResponse<AttachmentWithUserData>) { val data = mapToFileListItem(response.data, response.hasPrev) if (response.offset == 0) { _filesFlow.tryEmit(data) } else _loadMoreFilesFlow.tryEmit(data) notifyPageStateWithResponse(SceytResponse.Success(null), response.offset > 0, response.data.isEmpty()) } private fun initPaginationServerResponse(response: PaginationResponse.ServerResponse<AttachmentWithUserData>) { when (response.data) { is SceytResponse.Success -> { if (response.hasDiff) { val newMessages = mapToFileListItem(data = response.cacheData, hasPrev = response.hasPrev) _filesFlow.tryEmit(newMessages) } else if (response.hasPrev.not()) _loadMoreFilesFlow.tryEmit(emptyList()) } is SceytResponse.Error -> { if (hasNextDb.not()) _loadMoreFilesFlow.tryEmit(emptyList()) } } notifyPageStateWithResponse(response.data, response.offset > 0, response.cacheData.isEmpty()) } private fun mapToFileListItem(data: List<AttachmentWithUserData>?, hasPrev: Boolean): List<ChannelFileItem> { if (data.isNullOrEmpty()) return arrayListOf() val fileItems = arrayListOf<ChannelFileItem>() var prevItem: AttachmentWithUserData? = null data.sortedByDescending { it.attachment.createdAt }.forEach { item -> if (prevItem == null || !DateTimeUtil.isSameDay(prevItem?.attachment?.createdAt ?: 0, item.attachment.createdAt)) { fileItems.add(ChannelFileItem.MediaDate(item)) } val fileItem: ChannelFileItem? = when (item.attachment.type) { AttachmentTypeEnum.Video.value -> ChannelFileItem.Video(item) AttachmentTypeEnum.Image.value -> ChannelFileItem.Image(item) AttachmentTypeEnum.File.value -> ChannelFileItem.File(item) AttachmentTypeEnum.Voice.value -> ChannelFileItem.Voice(item) AttachmentTypeEnum.Link.value -> ChannelFileItem.Link(item) else -> null } fileItem?.let { fileItems.add(it) } prevItem = item } if (hasPrev) fileItems.add(ChannelFileItem.LoadingMoreItem) return fileItems } private fun prepareToPauseOrResumeUpload(item: SceytAttachment, channelId: Long) { when (val state = item.transferState ?: return) { TransferState.PendingUpload, TransferState.ErrorUpload -> { SendAttachmentWorkManager.schedule(application, item.messageTid, channelId) } TransferState.PendingDownload, TransferState.ErrorDownload -> { fileTransferService.download(item, FileTransferHelper.createTransferTask(item)) } TransferState.PauseDownload -> { val task = fileTransferService.findTransferTask(item) if (task != null) fileTransferService.resume(item.messageTid, item, state) else fileTransferService.download(item, FileTransferHelper.createTransferTask(item)) } TransferState.PauseUpload -> { val task = fileTransferService.findTransferTask(item) if (task != null) fileTransferService.resume(item.messageTid, item, state) else { // Update transfer state to Uploading, otherwise SendAttachmentWorkManager will // not start uploading. viewModelScope.launch(Dispatchers.IO) { attachmentLogic.updateTransferDataByMsgTid(TransferData( item.messageTid, item.progressPercent ?: 0f, TransferState.Uploading, item.filePath, item.url)) } SendAttachmentWorkManager.schedule(application, item.messageTid, channelId, ExistingWorkPolicy.REPLACE) } } TransferState.Uploading, TransferState.Downloading, TransferState.Preparing, TransferState.FilePathChanged, TransferState.WaitingToUpload -> { fileTransferService.pause(item.messageTid, item, state) } TransferState.Uploaded, TransferState.Downloaded, TransferState.ThumbLoaded -> { val transferData = TransferData( item.messageTid, item.progressPercent ?: 0f, item.transferState, item.filePath, item.url) FileTransferHelper.emitAttachmentTransferUpdate(transferData) } } } fun needMediaInfo(data: NeedMediaInfoData) { val attachment = data.item when (data) { is NeedMediaInfoData.NeedDownload -> { viewModelScope.launch(Dispatchers.IO) { fileTransferService.download(attachment, fileTransferService.findOrCreateTransferTask(attachment)) } } is NeedMediaInfoData.NeedThumb -> { viewModelScope.launch(Dispatchers.IO) { fileTransferService.getThumb(attachment.messageTid, attachment, data.thumbData) } } is NeedMediaInfoData.NeedLinkPreview -> { if (data.onlyCheckMissingData && attachment.linkPreviewDetails != null) { linkPreviewHelper.checkMissedData(attachment.linkPreviewDetails) { _linkPreviewLiveData.postValue(it) } } else { linkPreviewHelper.getPreview(attachment, true, successListener = { _linkPreviewLiveData.postValue(it) }) } } } } fun pauseOrResumeUpload(item: ChannelFileItem, channelId: Long) { viewModelScope.launch(Dispatchers.IO) { if (item.isFileItemInitialized) prepareToPauseOrResumeUpload(item.file, channelId) } } fun observeToUpdateAfterOnResume(fragment: Fragment) { FileTransferHelper.onTransferUpdatedLiveData.asFlow().onEach { viewModelScope.launch(Dispatchers.Default) { if (!fragment.isResumed) needToUpdateTransferAfterOnResume[it.messageTid] = it } }.launchIn(viewModelScope) viewModelScope.launch { fragment.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { needToUpdateTransferAfterOnResume.forEach { (_, transferData) -> FileTransferHelper.emitAttachmentTransferUpdate(transferData) } needToUpdateTransferAfterOnResume.clear() } } } }
0
Kotlin
1
2
ce9c1b95555fadaafcd11f0d073fcdb07ca49600
11,144
sceyt-chat-android-uikit
MIT License
app/src/main/java/crupest/cruphysics/data/world/processed/ProcessedWorldRecordForLatest.kt
crupest
112,487,340
false
null
package crupest.cruphysics.data.world.processed import crupest.cruphysics.serialization.data.CameraData import crupest.cruphysics.serialization.data.WorldData import java.util.Date data class ProcessedWorldRecordForLatest(val timestamp: Date, val world: WorldData, val camera: CameraData)
1
Kotlin
0
0
7e56c159068bc7cac9777e004793e74f94900c88
291
Android-CruPhysics
Apache License 2.0
common/src/commonMain/kotlin/com/artemchep/keyguard/provider/bitwarden/model/Login.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.provider.bitwarden.model import kotlinx.datetime.Instant data class Login( val accessToken: String, val accessTokenType: String, val accessTokenExpiryDate: Instant, val refreshToken: String, val scope: String?, )
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
266
keyguard-app
Linux Kernel Variant of OpenIB.org license
core/domain/src/main/java/com/season/winter/core/domain/repository/CachedImageRepository.kt
winter-love-dev
660,596,555
false
{"Kotlin": 266095}
package com.season.winter.core.domain.repository interface CachedImageRepository { suspend fun getImageUrl(fileName: String): String? }
0
Kotlin
0
0
d84a7f228b553a631bccaf2352be0ae88ed22b8e
140
CatchBottle
Apache License 2.0
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/api/targets/LLFirWholeElementResolveTarget.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.low.level.api.fir.api.targets import org.jetbrains.kotlin.analysis.low.level.api.fir.util.errorWithFirSpecificEntries import org.jetbrains.kotlin.analysis.low.level.api.fir.util.forEachDeclaration import org.jetbrains.kotlin.analysis.low.level.api.fir.util.isDeclarationContainer import org.jetbrains.kotlin.fir.FirElementWithResolveState import org.jetbrains.kotlin.fir.declarations.FirDeclaration import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.fir.declarations.FirRegularClass import org.jetbrains.kotlin.fir.declarations.FirScript /** * [LLFirResolveTarget] representing all declarations in [target] recursively. * All of them are going to be resolved. */ internal class LLFirWholeElementResolveTarget( firFile: FirFile, containerClasses: List<FirRegularClass>, target: FirElementWithResolveState, ) : LLFirResolveTarget(firFile, containerClasses, target) { constructor(firFile: FirFile) : this(firFile, emptyList(), firFile) override fun visitTargetElement( element: FirElementWithResolveState, visitor: LLFirResolveTargetVisitor, ) { if (element !is FirFile) { visitor.performAction(element) } when { element !is FirDeclaration || !element.isDeclarationContainer -> {} element is FirRegularClass -> visitor.withRegularClass(element) { element.forEachDeclaration { visitTargetElement(it, visitor) } } element is FirFile -> { element.forEachDeclaration { visitTargetElement(it, visitor) } } element is FirScript -> visitor.withScript(element) { element.forEachDeclaration { visitTargetElement(it, visitor) } } else -> errorWithFirSpecificEntries("Unexpected declaration: ${element::class.simpleName}", fir = element) } } override fun toStringAdditionalSuffix(): String = "*" }
166
Kotlin
5771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,318
kotlin
Apache License 2.0
app/src/main/java/com/github2136/base/model/HttpModel.kt
github2136
210,985,491
false
null
package com.github2136.base.model import android.content.Context import com.github2136.basemvvm.BaseWebModel /** * Created by yb on 2019/10/7 */ class HttpModel private constructor(context: Context) : BaseWebModel(context) { var api: HttpService init { baseUrl = "http://www.weather.com.cn/" api = getRetrofit().create(HttpService::class.java) } override fun resetBaseUrl(url: String) { super.resetBaseUrl(url) api = getRetrofit().create(HttpService::class.java) } override fun addHead(): MutableMap<String, String>? = null override fun preProcessing(code: Int, body: String?) { } companion object { private lateinit var context: Context private val instances: HttpModel by lazy { HttpModel(context) } fun getInstance(context: Context): HttpModel { if (!this::context.isInitialized) { this.context = context } return instances } } }
0
null
0
2
8ec63d87d4a25c599704ced72bb842513f16975e
996
Base
Apache License 2.0
guide/src/test/kotlin/examples/example-schedule-01.kt
arrow-kt
557,761,845
false
null
// This file was automatically generated from retry-and-repeat.md by Knit tool. Do not edit. package arrow.website.examples.exampleSchedule01 import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import arrow.resilience.* import io.kotest.matchers.shouldBe fun <A> recurTenTimes() = Schedule.recurs<A>(10)
12
Kotlin
7
6
c1e8cff959fa376b32007b27c17955a38262b447
387
arrow-website
Apache License 2.0
hoplite-aws2/src/main/kotlin/com/sksamuel/hoplite/aws2/AwsSecretsManagerPreprocessor.kt
sksamuel
187,727,131
false
{"Kotlin": 582464}
package com.sksamuel.hoplite.aws import com.amazonaws.AmazonClientException import com.amazonaws.AmazonServiceException import com.amazonaws.services.secretsmanager.AWSSecretsManager import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder import com.amazonaws.services.secretsmanager.model.DecryptionFailureException import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest import com.amazonaws.services.secretsmanager.model.InvalidParameterException import com.amazonaws.services.secretsmanager.model.LimitExceededException import com.amazonaws.services.secretsmanager.model.ResourceNotFoundException import com.sksamuel.hoplite.CommonMetadata import com.sksamuel.hoplite.ConfigFailure import com.sksamuel.hoplite.ConfigResult import com.sksamuel.hoplite.DecoderContext import com.sksamuel.hoplite.Node import com.sksamuel.hoplite.PrimitiveNode import com.sksamuel.hoplite.StringNode import com.sksamuel.hoplite.fp.invalid import com.sksamuel.hoplite.fp.valid import com.sksamuel.hoplite.preprocessor.TraversingPrimitivePreprocessor import com.sksamuel.hoplite.withMeta import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json /** * @param report set to true to output a report on secrets used. * Requires the overall hoplite report to be enabled. */ class AwsSecretsManagerPreprocessor( private val report: Boolean = false, private val json: Json, private val createClient: () -> AWSSecretsManager = { AWSSecretsManagerClientBuilder.standard().build() } ) : TraversingPrimitivePreprocessor() { constructor( report: Boolean = false, createClient: () -> AWSSecretsManager = { AWSSecretsManagerClientBuilder.standard().build() } ) : this(report, Json.Default, createClient) private val client by lazy { createClient() } private val regex1 = "\\$\\{awssecret:(.+?)}".toRegex() private val regex2 = "secretsmanager://(.+?)".toRegex() private val regex3 = "awssm://(.+?)".toRegex() private val keyRegex = "(.+)\\[(.+)]".toRegex() override fun handle(node: PrimitiveNode, context: DecoderContext): ConfigResult<Node> = when (node) { is StringNode -> { when ( val match = regex1.matchEntire(node.value) ?: regex2.matchEntire(node.value) ?: regex3.matchEntire(node.value) ) { null -> node.valid() else -> { val value = match.groupValues[1].trim() val keyMatch = keyRegex.matchEntire(value) val (key, index) = if (keyMatch == null) Pair(value, null) else Pair(keyMatch.groupValues[1], keyMatch.groupValues[2]) fetchSecret(key, index, node, context) } } } else -> node.valid() } private fun fetchSecret(key: String, index: String?, node: StringNode, context: DecoderContext): ConfigResult<Node> { return try { val req = GetSecretValueRequest().withSecretId(key) val value = client.getSecretValue(req) if (report) context.reporter.report( "AWS Secrets Manager Lookups", mapOf( "Name" to value.name, "Arn" to value.arn, "Created Date" to value.createdDate.toString(), "Version Id" to value.versionId ) ) val secret = value.secretString if (secret.isNullOrBlank()) ConfigFailure.PreprocessorWarning("Empty secret '$key' in AWS SecretsManager").invalid() else { if (index == null) { node.copy(value = secret) .withMeta(CommonMetadata.Secret, true) .withMeta(CommonMetadata.UnprocessedValue, node.value) .withMeta(CommonMetadata.RemoteLookup, "AWS '$key'") .valid() } else { val map = runCatching { json.decodeFromString<Map<String, String>>(secret) }.getOrElse { emptyMap() } val indexedValue = map[index] if (indexedValue == null) ConfigFailure.PreprocessorWarning( "Index '$index' not present in secret '$key'. Available keys are ${ map.keys.joinToString( "," ) }" ).invalid() else node.copy(value = indexedValue) .withMeta(CommonMetadata.Secret, true) .withMeta(CommonMetadata.UnprocessedValue, node.value) .withMeta(CommonMetadata.RemoteLookup, "AWS '$key[$index]'") .valid() } } } catch (e: ResourceNotFoundException) { ConfigFailure.PreprocessorWarning("Could not locate resource '$key' in AWS SecretsManager").invalid() } catch (e: DecryptionFailureException) { ConfigFailure.PreprocessorWarning("Could not decrypt resource '$key' in AWS SecretsManager").invalid() } catch (e: LimitExceededException) { ConfigFailure.PreprocessorWarning("Could not load resource '$key' due to limits exceeded").invalid() } catch (e: InvalidParameterException) { ConfigFailure.PreprocessorWarning("Invalid parameter name '$key' in AWS SecretsManager").invalid() } catch (e: AmazonServiceException) { ConfigFailure.PreprocessorFailure("Failed loading secret '$key' from AWS SecretsManager", e).invalid() } catch (e: AmazonClientException) { ConfigFailure.PreprocessorFailure("Failed loading secret '$key' from AWS SecretsManager", e).invalid() } catch (e: Exception) { ConfigFailure.PreprocessorFailure("Failed loading secret '$key' from AWS SecretsManager", e).invalid() } } }
9
Kotlin
74
918
c21e77ea11e26d7852cb6a1859bfc26dee74974e
5,507
hoplite
Apache License 2.0
app/src/main/java/edu/mum/mumwhere/MainActivity.kt
mutkan
279,480,566
true
{"XML": 107, "Gradle": 3, "Java Properties": 4, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 25, "Java": 2, "HTML": 1, "INI": 2}
package edu.mum.mumwhere import android.Manifest import android.app.Activity import android.app.ProgressDialog.show import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.menu.MenuBuilder import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.esri.arcgisruntime.geometry.DatumTransformation import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.SpatialReference import com.esri.arcgisruntime.geometry.TransformationCatalog import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.Basemap import com.esri.arcgisruntime.mapping.view.* import com.esri.arcgisruntime.mapping.view.LocationDisplay.DataSourceStatusChangedListener import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.esri.arcgisruntime.symbology.TextSymbol import edu.mum.mumwhere.Models.Building import edu.mum.mumwhere.Models.Classrooms import edu.mum.mumwhere.spinner.ItemData import edu.mum.mumwhere.spinner.SpinnerAdapter import kotlinx.android.synthetic.main.activity_main.* import java.util.* import java.util.concurrent.ExecutionException import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() , View.OnClickListener, IdentifyFeature.DialogListener{ internal var dbHelper = DatabaseHelper(this) private lateinit var mNavigationDrawerItemTitles: Array<String> private val wgs84 = SpatialReference.create(3857) private lateinit var mMapView: MapView private var mLocationDisplay: LocationDisplay? = null var graphicsOverlay: GraphicsOverlay? = null private var mSpinner: Spinner? = null private var mBasemap: Spinner? = null lateinit var mapPoint: Point lateinit var isAdminMode: String lateinit var spf: SharedPreferences private lateinit var strings1: Array<String> private lateinit var stringsList:ArrayList<String> private lateinit var stringArrr: Array<String> private val requestCode = 2 var reqPermissions = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //initDatabase() initMap() registerChangeBasemap() registerCurrentLocation() updateOnTouchListener() displayPoints() initSearch() supportActionBar?.apply { // setDisplayHomeAsUpEnabled(true) // setHomeButtonEnabled(true) // set opening basemap title to Topographic title = "MIU Where?" } // TODO : mapping function to fix the shifting issue //-91.96765780448914,41.015310287475586 //-91.96036219596863,41.0209321975708 } private fun initSearch(){ var stringsl: ArrayList<String>? var stringsll: List<String>? = ArrayList() val list: ArrayList<String> = ArrayList() stringsll=null val sr:String ="haha" list.add(sr) var s1 = list?.get(0) var lsize = list?.size print("Size is "+lsize) /*strings1 = arrayOf("Asia","Australia","America","Belgium","Brazil","Canada","California","Dubai","France","Paris")*/ val res = dbHelper.allDataBuilding while (res.moveToNext()) { list?.add(res.getString(4)) } val classes = dbHelper.allDataClassrooms try{ while (classes.moveToNext()) { list?.add(classes.getString(1)) } }catch(excep: Exception){ } /*stringArrr = stringsl.toArray()*/ /*showDialog("Data Listing", buffer.toString())*/ /*strings1 = arrayOf("Asia","Australia","America","Belgium","Brazil","Canada","California","Dubai","France","Paris")*/ // Get the XML configured vales into the Activity and stored into an String Array //strings = getResources().getStringArray(R.array.countries); /* Pass three parameters to the ArrayAdapter 1. The current context, 2. The resource ID for a built-in layout file containing a TextView to use when instantiating views, which are available in android.R.layout 3. The objects to represent in the values */ val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list) actv2.setAdapter(adapter) actv2.threshold = 1 actv2.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> Toast.makeText(this,"Item selected is " + parent.getItemAtPosition(position),Toast.LENGTH_LONG).show() val iName:String = parent.getItemAtPosition(position).toString() var x:Double = 0.0 var y:Double = 0.0 val res = dbHelper.allDataBuilding while (res.moveToNext()) { if (res.getString(4) == iName) { x = res.getDouble(3).toDouble() y = res.getDouble(2).toDouble() break } } val point = Point(x,y) mMapView.setViewpointCenterAsync(point) /* mLocationDisplay?.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER)*/ if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } } private fun initDatabase() { //Code : Adnan : For DataBase Inintialization var data:Building=Building("Argiro","Student Center","image_url",41.01614713668823,-91.96762561798096) var data1:Building=Building("Argiro","Student Center","image_url",41.0161471366844,-91.96762561798096) var data2:Building=Building("Argiro","Student Center","image_url",41.0161471366822,-91.96762561798096) var data3:Building=Building("Argiro","Student Center","image_url",41.01614713668999,-91.96762561798096) //dbHelper.insertDataintoLogin() dbHelper.insertdataintoBuilding(data) dbHelper.insertdataintoBuilding(data1) dbHelper.insertdataintoBuilding(data2) dbHelper.insertdataintoBuilding(data3) /* db.execSQL("CREATE TABLE $TABLE_OFFICE (ID INTEGER PRIMARY KEY " + "AUTOINCREMENT,CATEGORY TEXT,CONTACT TEXT,NUMBER TEXT,PERSON_NAME TEXT,EMAIL TEXT,HOURS TEXT,BUILD_ID INTEGER,FOREIGN KEY(BUILD_ID) REFERENCES $TABLE_BUILDING(ID))") db.execSQL("CREATE TABLE $TABLE_CLASSROOM (ID INTEGER PRIMARY KEY " + "AUTOINCREMENT,CURR_COURSE TEXT, DESC TEXT,CURR_INST_LOCATION TEXT,BUILD_ID INTEGER,FOREIGN KEY(BUILD_ID) REFERENCES $TABLE_BUILDING(ID))") db.execSQL("CREATE TABLE $TABLE_POI (ID INTEGER PRIMARY KEY " + "AUTOINCREMENT,SERVICE_TYPE TEXT,SERVICE_NAME TEXT,SERVICE_DESC TEXT,BUILD_ID INTEGER,FOREIGN KEY(BUILD_ID) REFERENCES $TABLE_BUILDING(ID))") */ var classRoom:Classrooms= Classrooms( "MDP","Android/Kotlin Course. Room #233", "Dr. Renuka ", 1) var classRoom1:Classrooms= Classrooms( "MDP","Android/Kotlin Course. Room #233", "Dr. Renuka ", 1) var classRoom2:Classrooms= Classrooms( "MDP","Android/Kotlin Course. Room #233", "Dr. Renuka ", 1) var classRoom3:Classrooms= Classrooms( "MDP","Android/Kotlin Course. Room #233", "Dr. Renuka ", 1) //dbHelper.insertDataintoLogin() dbHelper.insertdataintoClassroom(classRoom) dbHelper.insertdataintoClassroom(classRoom1) dbHelper.insertdataintoClassroom(classRoom2) dbHelper.insertdataintoClassroom(classRoom3) //dbHelper.insertdataintoOffice("Clerk",2) //dbHelper.insertdataintoClassroom("WAP","VERILHALL",3) //dbHelper.insertdataintoPOI("Entertainment",3) Log.d("Insert data manually","message") //End here } private fun initMap() { mNavigationDrawerItemTitles = Basemap.Type.values().map { it.name.replace("_", " ").toLowerCase().capitalize() }.toTypedArray() // Get the Spinner from layout mSpinner = findViewById<View>(R.id.spinner) as Spinner // Get the basemap from layout mBasemap = findViewById<View>(R.id.basemap) as Spinner // inflate MapView from layout mMapView = findViewById(R.id.mapView) as MapView val map = ArcGISMap(Basemap.Type.IMAGERY,41.01614713668823,-91.96762561798096, 17) // add graphics overlay to MapView. graphicsOverlay = addGraphicsOverlay(mMapView) // set the map to be displayed in the layout's MapView mMapView.map = map editOptions.visibility = View.INVISIBLE val geti = intent //isAdminMode = geti.getStringExtra("isLogin")?: "" val spfr = getSharedPreferences("login",Context.MODE_PRIVATE) val name= spfr.getString("username","") isAdminMode = spfr.getString("isLogin","").toString() if (isAdminMode=="y"){ editOptions.visibility = View.VISIBLE } spf = getSharedPreferences("login", Context.MODE_PRIVATE) } /** * Select the Basemap item based on position in the navigation drawer * * @param position order int in navigation drawer */ private fun selectBasemap(position: Int) { // get basemap title by position val baseMapTitle = mNavigationDrawerItemTitles[position] //supportActionBar?.title = baseMapTitle // select basemap by title mapView.map.basemap = when (Basemap.Type.valueOf(baseMapTitle.replace(" ", "_").toUpperCase())) { Basemap.Type.DARK_GRAY_CANVAS_VECTOR -> Basemap.createDarkGrayCanvasVector() Basemap.Type.IMAGERY -> Basemap.createImagery() Basemap.Type.IMAGERY_WITH_LABELS -> Basemap.createImageryWithLabels() Basemap.Type.IMAGERY_WITH_LABELS_VECTOR -> Basemap.createImageryWithLabelsVector() Basemap.Type.LIGHT_GRAY_CANVAS -> Basemap.createLightGrayCanvas() Basemap.Type.LIGHT_GRAY_CANVAS_VECTOR -> Basemap.createDarkGrayCanvasVector() Basemap.Type.NATIONAL_GEOGRAPHIC -> Basemap.createNationalGeographic() Basemap.Type.NAVIGATION_VECTOR -> Basemap.createNavigationVector() Basemap.Type.OCEANS -> Basemap.createOceans() Basemap.Type.OPEN_STREET_MAP -> Basemap.createOceans() Basemap.Type.STREETS -> Basemap.createStreets() Basemap.Type.STREETS_NIGHT_VECTOR -> Basemap.createStreetsNightVector() Basemap.Type.STREETS_WITH_RELIEF_VECTOR -> Basemap.createStreetsWithReliefVector() Basemap.Type.STREETS_VECTOR -> Basemap.createStreetsVector() Basemap.Type.TOPOGRAPHIC -> Basemap.createTopographic() Basemap.Type.TERRAIN_WITH_LABELS -> Basemap.createTerrainWithLabels() Basemap.Type.TERRAIN_WITH_LABELS_VECTOR -> Basemap.createTerrainWithLabelsVector() Basemap.Type.TOPOGRAPHIC_VECTOR -> Basemap.createTopographicVector() } } private fun handleAdminEvents(event: MotionEvent, point:android.graphics.Point){ // add/delete/update a new feature if its on the edit mode. if (rbAddFeature.isChecked){ val point = android.graphics.Point(event.x.toInt(), event.y.toInt()) val location: com.esri.arcgisruntime.geometry.Point = mMapView.screenToLocation(point) //val defaultTransform = TransformationCatalog.get.getTransformation(mMapView.spatialReference, wgs84,location) var tempPoint: com.esri.arcgisruntime.geometry.Point = Point(location.x, location.y,location.spatialReference) addFeature(tempPoint) }else if (rbUpdateFeature.isChecked){ // TODO : implement update feature // identify graphics on the graphics overlay // identify graphics on the graphics overlay val identifyGraphic = mMapView.identifyGraphicsOverlayAsync( graphicsOverlay, point, 10.0, false, 2 ) identifyGraphic.addDoneListener { try { val grOverlayResult = identifyGraphic.get() // get the list of graphics returned by identify graphic overlay val graphic = grOverlayResult.graphics // get size of list in results val identifyResultSize = graphic.size if (!graphic.isEmpty()) { // show a toast message if graphic was returned Toast.makeText( applicationContext, "Tapped on $identifyResultSize Graphic", Toast.LENGTH_SHORT ).show() } } catch (ie: InterruptedException) { ie.printStackTrace() } catch (ie: ExecutionException) { ie.printStackTrace() } } }else if (rbDeleteFeature.isChecked){ // TODO : implement delete feature // identify graphics on the graphics overlay // identify graphics on the graphics overlay val identifyGraphic = mMapView.identifyGraphicsOverlayAsync( graphicsOverlay, point, 25.0, false, 2 ) identifyGraphic.addDoneListener { try { val grOverlayResult = identifyGraphic.get() // get the list of graphics returned by identify graphic overlay val graphics = grOverlayResult.graphics // get size of list in results val identifyResultSize = graphics.size if (!graphics.isEmpty()) { // show a toast message if graphic was returned var dbHelper = DatabaseHelper(applicationContext) var result = dbHelper.deletedatafromBuilding(graphicsOverlay!!.graphics[0].attributes.get("BUILD_ID").toString()) if (graphicsOverlay!!.graphics[1] != null) dbHelper.deletedatafromBuilding(graphicsOverlay!!.graphics[1].attributes.get("BUILD_ID").toString()) graphicsOverlay!!.graphics.removeAll(graphics) Toast.makeText( applicationContext, "Deleted successfully!", Toast.LENGTH_SHORT ).show() } } catch (ie: InterruptedException) { ie.printStackTrace() } catch (ie: ExecutionException) { ie.printStackTrace() } } } } private fun updateOnTouchListener() { mapView.setOnTouchListener(object : DefaultMapViewOnTouchListener(this, mapView) { override fun onSingleTapConfirmed(event: MotionEvent): Boolean { // create a point from where the user clicked try { val point = android.graphics.Point(event.x.toInt(), event.y.toInt()) // create a map point from a point mapPoint = mMapView.screenToLocation(point) if (isAdminMode == "y" && ( rbAddFeature.isChecked || rbUpdateFeature.isChecked || rbDeleteFeature.isChecked )) handleAdminEvents(event,point) else { // handle identify for regular user // identify graphics on the graphics overlay val identifyGraphic = mMapView.identifyGraphicsOverlayAsync( graphicsOverlay, point, 10.0, false, 2 ) identifyGraphic.addDoneListener { try { val grOverlayResult = identifyGraphic.get() // get the list of graphics returned by identify graphic overlay val graphic = grOverlayResult.graphics // get size of list in results val identifyResultSize = graphic.size if (!graphic.isEmpty()) { // show a toast message if graphic was returned val dialogFragment = IdentifyFeature() val bundle = Bundle() bundle.putString("id", graphic[0].attributes.get("BUILD_ID").toString()) bundle.putString("name", graphic[0].attributes.get("NAME").toString()) bundle.putString("desc", graphic[0].attributes.get("DESC").toString()) dialogFragment.arguments = bundle val ft = supportFragmentManager.beginTransaction() ft.replace(R.id.frameLayout, dialogFragment) ft.commit() } } catch (ie: InterruptedException) { ie.printStackTrace() } catch (ie: ExecutionException) { ie.printStackTrace() } } } return super.onSingleTapConfirmed(event) } catch ( e: Exception ) { Toast.makeText( applicationContext, "Check your internet, Please!", Toast.LENGTH_LONG ) } return false } }) } private fun displayPoints() { // reading all data from buildings table val res = dbHelper.allDataBuilding if (res.count == 0) { //showDialog("Error", "No Data Found") Toast.makeText(applicationContext, "No Features!" , Toast.LENGTH_LONG) } val buffer = StringBuffer() // show data on the map. while (res.moveToNext()) { /*buffer.append("BUILD_ID :" + res.getString(0) + "\n") buffer.append("IMAGE :" + res.getString(1) + "\n") buffer.append("LATITUDE :" + res.getString(2) + "\n") buffer.append("LONGITUDE :" + res.getString(3) + "\n\n") buffer.append("NAME :" + res.getString(4) + "\n\n") buffer.append("DESC :" + res.getString(5) + "\n\n")*/ var mapPoint: com.esri.arcgisruntime.geometry.Point = Point((res.getString(3)).toDouble(), (res.getString(2)).toDouble(),wgs84) var attributes: MutableMap<String, Any> = HashMap() attributes["BUILD_ID"] = res.getString(0) attributes["IMAGE"] = res.getString(1) attributes["LATITUDE"] = res.getString(2) attributes["LONGITUDE"] = res.getString(3) attributes["NAME"] = res.getString(4) attributes["DESC"] = res.getString(5) addBuoyPoints(graphicsOverlay!!, mapPoint, attributes) addText(graphicsOverlay!!, mapPoint, attributes) } } private fun registerChangeBasemap() { // Populate the list for the Location display options for the spinner's Adapter val list: ArrayList<ItemData> = ArrayList<ItemData>() list.add(ItemData(resources.getString(R.string.DarkGrayCanvasVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.Imagery),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.ImageryWithLabels),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.LightGrayCanvas),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.LightGrayCanvasVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.NationalGeographic),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.NavigationVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.Oceans),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.OpenStreetMap),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.Streets),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.StreetsNightVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.StreetsVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.StreetsWithReliefVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.TerrainWithLabels),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.TerrainWithLabelsVector),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.Topographic),R.drawable.basemap)) list.add(ItemData(resources.getString(R.string.TopographicVector),R.drawable.basemap)) val adapter = SpinnerAdapter(this, R.layout.basemap_layout, R.id.txt, list) mBasemap!!.adapter = adapter mBasemap!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { selectBasemap(position) } override fun onNothingSelected(parent: AdapterView<*>?) {} } mBasemap!!.setSelection(1, true) } private fun registerCurrentLocation() { // get the MapView's LocationDisplay mLocationDisplay = mMapView.getLocationDisplay() // Listen to changes in the status of the location data source. // Listen to changes in the status of the location data source. mLocationDisplay?.addDataSourceStatusChangedListener(DataSourceStatusChangedListener { dataSourceStatusChangedEvent -> // If LocationDisplay started OK, then continue. if (dataSourceStatusChangedEvent.isStarted) return@DataSourceStatusChangedListener // No error is reported, then continue. if (dataSourceStatusChangedEvent.error == null) return@DataSourceStatusChangedListener // If an error is found, handle the failure to start. // Check permissions to see if failure may be due to lack of permissions. val permissionCheck1 = ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[0]) == PackageManager.PERMISSION_GRANTED val permissionCheck2 = ContextCompat.checkSelfPermission(this@MainActivity, reqPermissions[1]) == PackageManager.PERMISSION_GRANTED if (!(permissionCheck1 && permissionCheck2)) { // If permissions are not already granted, request permission from the user. ActivityCompat.requestPermissions( this@MainActivity, reqPermissions, requestCode ) } else { // Report other unknown failure types to the user - for example, location services may not // be enabled on the device. val message = String.format( "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent .source.locationDataSource.error.message ) Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show() // Update UI to reflect that the location display did not actually start mSpinner!!.setSelection(0, true) } }) // Populate the list for the Location display options for the spinner's Adapter val list: ArrayList<ItemData> = ArrayList<ItemData>() list.add(ItemData(resources.getString(R.string.stop), R.drawable.locationdisplaydisabled)) list.add(ItemData(resources.getString(R.string.on), R.drawable.locationdisplayon)) list.add(ItemData(resources.getString(R.string.recenter), R.drawable.locationdisplayrecenter)) list.add(ItemData(resources.getString(R.string.navigation), R.drawable.locationdisplaynavigation)) list.add(ItemData(resources.getString(R.string.compass), R.drawable.locationdisplayheading)) val adapter = SpinnerAdapter(this, R.layout.spinner_layout, R.id.txt, list) mSpinner!!.adapter = adapter mSpinner!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { when (position) { 0 -> // Stop Location Display if (mLocationDisplay!!.isStarted()) mLocationDisplay?.stop() 1 -> // Start Location Display if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() 2 -> { // Re-Center MapView on Location // AutoPanMode - Default: In this mode, the MapView attempts to keep the location symbol on-screen by // re-centering the location symbol when the symbol moves outside a "wander extent". The location symbol // may move freely within the wander extent, but as soon as the symbol exits the wander extent, the MapView // re-centers the map on the symbol. mLocationDisplay?.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } 3 -> { // Start Navigation Mode // This mode is best suited for in-vehicle navigation. mLocationDisplay!!.setAutoPanMode(LocationDisplay.AutoPanMode.NAVIGATION) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } 4 -> { // Start Compass Mode // This mode is better suited for waypoint navigation when the user is walking. mLocationDisplay!!.setAutoPanMode(LocationDisplay.AutoPanMode.COMPASS_NAVIGATION) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } } } override fun onNothingSelected(parent: AdapterView<*>?) {} } } /** * Adds a new Feature to a ServiceFeatureTable and applies the changes to the * server. * * @param mapPoint location to add feature * @param featureTable service feature table to add feature */ private fun addFeature(tempPoint: com.esri.arcgisruntime.geometry.Point) { // create default attributes for the feature var i = Intent(this, EditorActivity::class.java) i.putExtra("mappointx",tempPoint.x) i.putExtra("mappointy",tempPoint.y) startActivityForResult(i, 1) } override fun onActivityResult( requestCode: Int, resultCode:Int, data:Intent?) { super.onActivityResult(requestCode,resultCode,data) if (1 == requestCode) { if(resultCode == Activity.RESULT_OK){ Toast.makeText(this.applicationContext, data?.data.toString() , Toast.LENGTH_LONG) val attributes: MutableMap<String, Any> = HashMap() attributes["newPlace"] = data?.getStringExtra("username").toString() attributes["primcause"] = "Earthquake" addBuoyPoints(graphicsOverlay!!, mapPoint, attributes) addText(graphicsOverlay!!, mapPoint, attributes) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu,menu) // Code to get the title and icon on the option overflow if (menu is MenuBuilder) { menu.setOptionalIconsVisible(true) } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem):Boolean { Toast.makeText( applicationContext, item.title.toString(), Toast.LENGTH_LONG).show() if (item.title.toString() == "Login"){ var i = Intent(this, LoginActivity::class.java) startActivity(i) return super.onOptionsItemSelected(item) } if (item.title.toString() == "Logout"){ var spe=spf.edit() spe.putString("isLogin","") spe.apply() editOptions.visibility = View.INVISIBLE return super.onOptionsItemSelected(item) } if (item.title.toString() == "Scan QR"){ var i = Intent(this, ScanMainActivity::class.java) startActivity(i) return super.onOptionsItemSelected(item) } if (item.title.toString() == "About Us"){ var i = Intent(this, AboutActivity::class.java) startActivity(i) return super.onOptionsItemSelected(item) } else{ //for now, else will run route activity var r = Intent(this, RouteActivity::class.java) r.putExtra("sourceY", "41.00612") r.putExtra("sourceX", "-91.9849627") r.putExtra("destY", "41.005917") r.putExtra("destX", "-91.9767849") startActivityForResult(r, 1) return super.onOptionsItemSelected(item) } } override fun onPause() { super.onPause() mMapView.pause() } override fun onResume() { displayPoints() editOptions.clearCheck() initSearch() super.onResume() mMapView.resume() } override fun onDestroy() { super.onDestroy() mMapView.dispose() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // Checks the orientation of the screen /* if (newConfig.orientation === Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show() } else if (newConfig.orientation === Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show() }*/ } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String?>, grantResults: IntArray ) { // If request is cancelled, the result arrays are empty. if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Location permission was granted. This would have been triggered in response to failing to start the // LocationDisplay, so try starting this again. mLocationDisplay!!.startAsync() } else { // If permission was denied, show toast to inform user what was chosen. If LocationDisplay is started again, // request permission UX will be shown again, option should be shown to allow never showing the UX again. // Alternative would be to disable functionality so request is not shown again. Toast.makeText( this@MainActivity, resources.getString(R.string.location_permission_denied), Toast.LENGTH_SHORT ).show() // Update UI to reflect that the location display did not actually start mSpinner!!.setSelection(0, true) } } private fun addGraphicsOverlay(mapView: MapView): GraphicsOverlay? { //create the graphics overlay val graphicsOverlay = GraphicsOverlay() //add the overlay to the map view mapView.graphicsOverlays.add(graphicsOverlay) return graphicsOverlay } private fun addBuoyPoints(graphicOverlay: GraphicsOverlay, point:com.esri.arcgisruntime.geometry.Point, attr: MutableMap<String, Any> ) { //define the buoy locations val buoy1Loc = point // com.esri.arcgisruntime.geometry.Point(point.x, point.y, wgs84) //create a marker symbol val buoyMarker = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10.0f) buoyMarker.outline = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK,1.0f) //create graphics val buoyGraphic1 = Graphic(buoy1Loc,attr, buoyMarker) //add the graphics to the graphics overlay graphicOverlay.graphics.add(buoyGraphic1) } private fun addText(graphicOverlay: GraphicsOverlay, point:com.esri.arcgisruntime.geometry.Point, attr: MutableMap<String, Any>) { //create a point geometry val bassLocation = point //com.esri.arcgisruntime.geometry.Point(point.x, point.y, wgs84) //create text symbols val bassRockSymbol = TextSymbol( 20.0f, attr.get("NAME").toString(), Color.rgb(0, 0, 230), TextSymbol.HorizontalAlignment.LEFT, TextSymbol.VerticalAlignment.BOTTOM ) bassRockSymbol.fontWeight = TextSymbol.FontWeight.BOLD bassRockSymbol.haloColor = titleColor //define a graphic from the geometry and symbol val bassRockGraphic = Graphic(bassLocation, attr, bassRockSymbol) //add the text to the graphics overlay graphicOverlay.graphics.add(bassRockGraphic) // get the MapView's LocationDisplay mLocationDisplay = mMapView.getLocationDisplay() // Listen to changes in the status of the location data source. mLocationDisplay?.addDataSourceStatusChangedListener(LocationDisplay.DataSourceStatusChangedListener { dataSourceStatusChangedEvent -> // If LocationDisplay started OK, then continue. if (dataSourceStatusChangedEvent.isStarted) return@DataSourceStatusChangedListener // No error is reported, then continue. if (dataSourceStatusChangedEvent.error == null) return@DataSourceStatusChangedListener // If an error is found, handle the failure to start. // Check permissions to see if failure may be due to lack of permissions. val permissionCheck1 = ContextCompat.checkSelfPermission(this, reqPermissions[0]) == PackageManager.PERMISSION_GRANTED val permissionCheck2 = ContextCompat.checkSelfPermission(this, reqPermissions[1]) == PackageManager.PERMISSION_GRANTED if (!(permissionCheck1 && permissionCheck2)) { // If permissions are not already granted, request permission from the user. ActivityCompat.requestPermissions( this, reqPermissions, requestCode ) } else { // Report other unknown failure types to the user - for example, location services may not // be enabled on the device. val message = String.format( "Error in DataSourceStatusChangedListener: %s", dataSourceStatusChangedEvent .source.locationDataSource.error.message ) Toast.makeText(this, message, Toast.LENGTH_LONG).show() // Update UI to reflect that the location display did not actually start mSpinner!!.setSelection(0, true) } }) // Populate the list for the Location display options for the spinner's Adapter // Populate the list for the Location display options for the spinner's Adapter val list: ArrayList<ItemData> = ArrayList<ItemData>() list.add(ItemData("Stop", R.drawable.locationdisplaydisabled)) list.add(ItemData("On", R.drawable.locationdisplayon)) list.add(ItemData("Re-Center", R.drawable.locationdisplayrecenter)) list.add(ItemData("Navigation", R.drawable.locationdisplaynavigation)) list.add(ItemData("Compass", R.drawable.locationdisplayheading)) val adapter = SpinnerAdapter(this, R.layout.spinner_layout, R.id.txt, list) mSpinner!!.adapter = adapter mSpinner!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { when (position) { 0 -> // Stop Location Display if (mLocationDisplay!!.isStarted()) mLocationDisplay?.stop() 1 -> // Start Location Display if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() 2 -> { // Re-Center MapView on Location // AutoPanMode - Default: In this mode, the MapView attempts to keep the location symbol on-screen by // re-centering the location symbol when the symbol moves outside a "wander extent". The location symbol // may move freely within the wander extent, but as soon as the symbol exits the wander extent, the MapView // re-centers the map on the symbol. mLocationDisplay?.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } 3 -> { // Start Navigation Mode // This mode is best suited for in-vehicle navigation. mLocationDisplay!!.setAutoPanMode(LocationDisplay.AutoPanMode.NAVIGATION) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } 4 -> { // Start Compass Mode // This mode is better suited for waypoint navigation when the user is walking. mLocationDisplay!!.setAutoPanMode(LocationDisplay.AutoPanMode.COMPASS_NAVIGATION) if (!mLocationDisplay!!.isStarted()) mLocationDisplay?.startAsync() } } } override fun onNothingSelected(parent: AdapterView<*>?) {} } } override fun onClick(v: View?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. val dialogFragment = IdentifyFeature() val ft = supportFragmentManager.beginTransaction() ft.replace(R.id.frameLayout, dialogFragment) ft.commit() } override fun onFinishEditDialog(inputText: String) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
0
null
0
1
cd2927ed56c14ca34ac9400b6c53a45878f390ad
40,805
MIUWhere
Apache License 2.0
src/main/kotlin/util/Colors.kt
McAJBen
81,295,567
false
{"Kotlin": 110086}
package util import java.awt.Color /** * contains colors * @author <EMAIL> */ object Colors { /** * the color of an active button - (153, 255, 187) */ val ACTIVE = Color( 153, 255, 187 ) /** * the color of an inactive button - (255, 128, 128) */ val INACTIVE = Color( 255, 128, 128 ) /** * the color of an enabled button - Color.GREEN */ val ENABLE_COLOR = Color( 0, 255, 0 ) /** * the color of an disabled button - Color.GRAY */ val DISABLE_COLOR = Color( 128, 128, 128 ) /** * the green color used on `DrawPanel` to show a visible part of the map */ val CLEAR = Color( 100, 255, 100, 153 ) /** * the red color used on `DrawPanel` to show a blocked part of the map */ val OPAQUE = Color( 255, 100, 100, 153 ) /** * the clear color used on `DisplayPaint` to show through the mask */ val TRANSPARENT = Color( 0, 0, 0, 0 ) /** * the black color used on `DisplayPaint` to hide with the mask */ val BLACK = Color( 0, 0, 0 ) /** * the grey color used by default for `GridMenu` */ val TRANSPARENT_GREY = Color( 128, 128, 128, 192 ) /** * the pink color used on `DrawPanel` to show the cursor and outline of player's view */ val PINK = Color( 255, 0, 255 ) /** * the semi-transparent pink color used on `DrawPanel` */ val PINK_CLEAR = Color( 255, 0, 255, 25 ) /** * the background color used through Dungeon Board - (153, 153, 153) */ val BACKGROUND = Color( 153, 153, 153 ) /** * the background for user controls like `JButtons` and `JComboBoxes` - (200, 200, 200) */ val CONTROL_BACKGROUND = Color( 200, 200, 200 ) }
8
Kotlin
16
48
e34a1dc550d19b4762a741a6b6e210c7c7b38b43
1,708
DungeonBoard
MIT License
app/src/main/java/com/github/muellerma/tabletoptools/ui/fragments/CounterFragment.kt
mueller-ma
313,100,168
false
{"Kotlin": 59623}
package com.github.muellerma.tabletoptools.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.widget.doOnTextChanged import com.github.muellerma.tabletoptools.databinding.CounterBinding import com.github.muellerma.tabletoptools.databinding.FragmentCounterBinding class CounterFragment : AbstractBaseFragment() { private lateinit var binding: FragmentCounterBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentCounterBinding.inflate(inflater, container, false) setupScreenOn(binding.root) return binding.root } override fun onResume() { super.onResume() listOf( binding.counter1, binding.counter2, binding.counter3, binding.counter4, binding.counter5, binding.counter6, binding.counter7, binding.counter8 ).forEachIndexed { index, counterBinding -> setupCounter(index + 1, counterBinding) } } private fun setupCounter(id: Int, counter: CounterBinding) { fun getInput() = counter.count.text.toString().toIntOrNull() ?: 0 counter.less1.setOnClickListener { counter.count.setText(getInput().dec().toString()) } counter.less10.setOnClickListener { counter.count.setText(getInput().minus(10).toString()) } counter.more1.setOnClickListener { counter.count.setText(getInput().inc().toString()) } counter.more10.setOnClickListener { counter.count.setText(getInput().plus(10).toString()) } val prefs = prefs.Counter(id) counter.label.setText(prefs.label) counter.label.doOnTextChanged { text, _, _, _ -> prefs.label = text?.toString() } counter.count.setText(prefs.count.toString()) counter.count.doOnTextChanged { _, _, _, _ -> prefs.count = getInput() } } }
13
Kotlin
19
36
fad1132b058614c9cd0a441e246c8c127cabd9d0
2,128
TabletopTools
Apache License 2.0
examples/jpa-querydsl/src/main/kotlin/io/bluetape4k/examples/jpa/querydsl/spring/SpringRepositoryQuerydslSupport.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.examples.jpa.querydsl.spring import com.querydsl.core.types.dsl.PathBuilder import com.querydsl.jpa.impl.JPAQuery import com.querydsl.jpa.impl.JPAQueryFactory import io.bluetape4k.support.assertNotNull import jakarta.annotation.PostConstruct import jakarta.persistence.EntityManager import jakarta.persistence.PersistenceContext import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport import org.springframework.data.jpa.repository.support.Querydsl import org.springframework.data.querydsl.SimpleEntityPathResolver import org.springframework.data.support.PageableExecutionUtils import org.springframework.stereotype.Repository @Repository class SpringRepositoryQuerydslSupport(private val entityClass: Class<*>) { private var entityManager: EntityManager? = null private var querydsl: Querydsl? = null private var queryFactory: JPAQueryFactory? = null @PersistenceContext fun setEntityManager(entityManager: EntityManager) { entityManager.assertNotNull("entityManager") val entityInfo = JpaEntityInformationSupport.getEntityInformation(entityClass, entityManager) val resolver = SimpleEntityPathResolver.INSTANCE val path = resolver.createPath(entityInfo.javaType) this.entityManager = entityManager this.querydsl = Querydsl(entityManager, PathBuilder(path.type, path.metadata)) this.queryFactory = JPAQueryFactory(entityManager) } @PostConstruct fun assertProperProperty() { entityManager.assertNotNull("entityManager") querydsl.assertNotNull("querydsl") queryFactory.assertNotNull("queryFactory") } protected fun getEntityManager(): EntityManager = entityManager!! protected fun getQuerydsl(): Querydsl = querydsl!! protected fun getQueryFactory(): JPAQueryFactory = queryFactory!! @Suppress("DEPRECATION") protected fun <T> withPaging(pageable: Pageable, queryAction: (JPAQueryFactory) -> JPAQuery<T>): Page<T> { val contentQuery = queryAction(getQueryFactory()) val content = getQuerydsl().applyPagination(pageable, contentQuery).fetch() // NOTE: fetchCount 를 쓰지말고 Blaze-Persistence for Querydsl 를 쓰라고 하네요. // Blaze Persistence 예제는 quarkus-workshop 에 있습니다. // 참고 : https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/index.html#querydsl-integration return PageableExecutionUtils.getPage(content, pageable) { contentQuery.fetchCount() } } @Suppress("DEPRECATION") protected fun <T> withPaging( pageable: Pageable, contentQueryAction: (JPAQueryFactory) -> JPAQuery<T>, countQueryAction: (JPAQueryFactory) -> JPAQuery<T>, ): Page<T> { val contentQuery = contentQueryAction(getQueryFactory()) val content = getQuerydsl().applyPagination(pageable, contentQuery).fetch() val countQuery = countQueryAction(getQueryFactory()) // NOTE: fetchCount 를 쓰지말고 Blaze-Persistence for Querydsl 를 쓰라고 하네요. // Blaze Persistence 예제는 quarkus-workshop 에 있습니다. // 참고 : https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/index.html#querydsl-integration return PageableExecutionUtils.getPage(content, pageable) { countQuery.fetchCount() } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
3,393
bluetape4k
MIT License
app/src/main/java/com/github/ephelsa/mycareer/delivery/survey/pojo/AnswerJSON.kt
ephelsa
312,443,837
false
null
package com.github.ephelsa.mycareer.delivery.survey.pojo import com.github.ephelsa.mycareer.delivery.shared.mapper.DomainMappable import com.github.ephelsa.mycareer.domain.survey.AnswerRemote import com.google.gson.annotations.SerializedName data class AnswerJSON( @SerializedName("id") val id: Int, @SerializedName("value") val value: String ) : DomainMappable<AnswerRemote> { override fun toDomain(): AnswerRemote = AnswerRemote(id, value) }
5
Kotlin
0
2
d68ee1b43b6df9e95aa58db72e2999f2207fb94d
458
my-career
MIT License