path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/search/SearchRequest.kt
djkovrik
98,050,611
false
{"Gradle": 7, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 6, "Proguard": 14, "XML": 201, "Kotlin": 418, "Java Properties": 1, "JSON": 2, "Java": 2, "CSS": 1, "INI": 1, "YAML": 1}
package com.sedsoftware.yaptalker.presentation.feature.search import android.annotation.SuppressLint import android.os.Parcelable import com.sedsoftware.yaptalker.presentation.feature.search.options.SearchConditions import com.sedsoftware.yaptalker.presentation.feature.search.options.SortingMode import com.sedsoftware.yaptalker.presentation.feature.search.options.TargetPeriod import kotlinx.android.parcel.Parcelize @SuppressLint("ParcelCreator") @Parcelize data class SearchRequest( val searchFor: String, val targetForums: List<String> = emptyList(), val searchIn: String = "", val searchInTags: Boolean = false, @SearchConditions.Value val searchHow: String = SearchConditions.ALL_WORDS, @SortingMode.Value val sortBy: String = SortingMode.DATE, @TargetPeriod.Value val periodInDays: Long = TargetPeriod.ALL_TIME ) : Parcelable
0
Kotlin
4
9
465c34c3dc0dd0488b637073fddf6cd797e78613
864
YapTalker
Apache License 2.0
adoptopenjdk-api-v3-frontend/src/test/kotlin/net/adoptopenjdk/api/ReleaseNamesPathTest.kt
xunanmu
280,589,423
true
{"Kotlin": 409616, "HTML": 1846, "Shell": 1234, "CSS": 992, "Dockerfile": 655}
package net.adoptopenjdk.api import io.quarkus.test.junit.QuarkusTest import io.restassured.RestAssured import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test @QuarkusTest class ReleaseNamesPathTest : BaseTest() { companion object { @JvmStatic @BeforeAll fun before() { populateDb() } } @Test fun releaseNames() { RestAssured.given() .`when`() .get("/v3/info/release_names") .then() .statusCode(200) } @Test fun releaseNamesPageSize() { RestAssured.given() .`when`() .get("/v3/info/release_names?page_size=50") .then() .statusCode(200) } @Test fun releaseNamesSortOrder() { RestAssured.given() .`when`() .get("/v3/info/release_names?sort_order=DESC") .then() .statusCode(200) } @Test fun releaseVersions() { RestAssured.given() .`when`() .get("/v3/info/release_versions") .then() .statusCode(200) } @Test fun releaseVersionsPageSize() { RestAssured.given() .`when`() .get("/v3/info/release_versions?page_size=50") .then() .statusCode(200) } @Test fun releaseVersionsSortOrder() { RestAssured.given() .`when`() .get("/v3/info/release_versions?sort_order=ASC") .then() .statusCode(200) } }
0
Kotlin
0
0
fc6204c8b5ca7ab0560629321a2d107bb2d83ef5
1,676
openjdk-api-v3
Apache License 2.0
ui-app/src/androidMain/kotlin/com/alexvanyo/composelife/ui/app/component/EdgeToEdgeModalBottomSheet.kt
alexvanyo
375,146,193
false
null
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alexvanyo.composelife.ui.app.component import androidx.activity.ComponentActivity import androidx.activity.enableEdgeToEdge import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.exponentialDecay import androidx.compose.animation.core.spring import androidx.compose.foundation.Canvas import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.AnchoredDraggableState import androidx.compose.foundation.gestures.DraggableAnchors import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.anchoredDraggable import androidx.compose.foundation.gestures.animateTo import androidx.compose.foundation.gestures.animateToWithDecay import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.snapTo import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.BasicText import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetValue import androidx.compose.material3.SheetValue.Expanded import androidx.compose.material3.SheetValue.Hidden import androidx.compose.material3.SheetValue.PartiallyExpanded import androidx.compose.material3.Surface import androidx.compose.material3.TextField import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.collapse import androidx.compose.ui.semantics.dismiss import androidx.compose.ui.semantics.expand import androidx.compose.ui.semantics.paneTitle import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.compose.ui.util.lerp import androidx.compose.ui.window.DialogProperties import com.alexvanyo.composelife.ui.util.CompletablePredictiveBackState import com.alexvanyo.composelife.ui.util.EdgeToEdgeDialog import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlin.math.max @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Suppress("LongParameterList", "CyclomaticComplexMethod", "LongMethod") @Composable fun EdgeToEdgeModalBottomSheet( onDismissRequest: () -> Unit, modifier: Modifier = Modifier, sheetState: SheetState = rememberModalBottomSheetState(), sheetMaxWidth: Dp = BottomSheetDefaults.SheetMaxWidth, sheetWindowInsets: @Composable () -> WindowInsets = { WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top) }, shape: Shape = BottomSheetDefaults.ExpandedShape, containerColor: Color = BottomSheetDefaults.ContainerColor, contentColor: Color = contentColorFor(containerColor), contentWindowInsets: @Composable () -> WindowInsets = { WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom) }, tonalElevation: Dp = BottomSheetDefaults.Elevation, scrimColor: Color = BottomSheetDefaults.ScrimColor, dragHandle: @Composable (() -> Unit)? = { BottomSheetDefaults.DragHandle() }, properties: DialogProperties = DialogProperties(), content: @Composable ColumnScope.() -> Unit, ) { // b/291735717 Remove this once deprecated methods without density are removed val density = LocalDensity.current SideEffect { sheetState.density = density } val scope = rememberCoroutineScope() val animateToDismiss: () -> Unit = { if (sheetState.confirmValueChange(Hidden)) { scope.launch { sheetState.hide() } } } val settleToDismiss: (velocity: Float) -> Unit = { scope.launch { sheetState.settle(it) } } val currentOnDismissRequest by rememberUpdatedState(onDismissRequest) LaunchedEffect(Unit) { sheetState.animateTo(if (sheetState.skipPartiallyExpanded) Expanded else PartiallyExpanded) snapshotFlow { !sheetState.anchoredDraggableState.isAnimationRunning && !sheetState.isVisible } .filter { it } .onEach { currentOnDismissRequest() } .collect() } EdgeToEdgeDialog( properties = properties, onDismissRequest = { scope.launch { sheetState.hide() } }, ) { predictiveBackStateHolder -> Box( Modifier.fillMaxSize(), ) { Scrim( color = scrimColor, onDismissRequest = animateToDismiss, visible = sheetState.targetValue != Hidden, ) val bottomSheetPaneTitle = "bottom sheet" // TODO: getString(string = Strings.BottomSheetPaneTitle) val ime = WindowInsets.ime val lastRunningValue by remember { mutableStateOf<CompletablePredictiveBackState.Running?>(null) }.apply { when (val predictiveBackState = predictiveBackStateHolder.value) { CompletablePredictiveBackState.NotRunning -> value = null is CompletablePredictiveBackState.Running -> if (predictiveBackState.progress >= 0.01f) { // Only save that we were disappearing if the progress is at least 1% along value = predictiveBackState } CompletablePredictiveBackState.Completed -> Unit } } var fullWidth by remember { mutableIntStateOf(0) } Surface( modifier = modifier .fillMaxSize() .windowInsetsPadding(sheetWindowInsets()) .wrapContentSize() .widthIn(max = sheetMaxWidth) .fillMaxWidth() .layout { measurable, constraints -> val placeable = measurable.measure(constraints) val fullHeight = constraints.maxHeight.toFloat() fullWidth = constraints.maxWidth val sheetSize = IntSize(placeable.width, placeable.height) val partiallyExpandedOffset = max(0f, fullHeight / 2f - ime.getBottom(density)) val newAnchors = DraggableAnchors { Hidden at fullHeight if (sheetSize.height > (fullHeight / 2) && !sheetState.skipPartiallyExpanded) { PartiallyExpanded at partiallyExpandedOffset } if (sheetSize.height != 0) { Expanded at max(0f, fullHeight - sheetSize.height) } } val newTarget = when (sheetState.anchoredDraggableState.targetValue) { Hidden -> Hidden PartiallyExpanded -> if (newAnchors.hasAnchorFor(PartiallyExpanded)) { PartiallyExpanded } else if (newAnchors.hasAnchorFor(Expanded)) { Expanded } else { Hidden } Expanded -> if (newAnchors.hasAnchorFor(Expanded)) { Expanded } else if (newAnchors.hasAnchorFor(PartiallyExpanded)) { PartiallyExpanded } else { Hidden } } sheetState.anchoredDraggableState.updateAnchors(newAnchors, newTarget) layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) } } .semantics { paneTitle = bottomSheetPaneTitle } .offset { IntOffset( 0, max( 0, sheetState .requireOffset() .toInt(), ), ) } .nestedScroll( remember(sheetState) { ConsumeSwipeWithinBottomSheetBoundsNestedScrollConnection( sheetState = sheetState, orientation = Orientation.Vertical, onFling = settleToDismiss, ) }, ) .anchoredDraggable( state = sheetState.anchoredDraggableState, orientation = Orientation.Vertical, enabled = sheetState.isVisible, startDragImmediately = sheetState.anchoredDraggableState.isAnimationRunning, ) .graphicsLayer { val predictiveBackState = predictiveBackStateHolder.value val scale = lerp( 1f, 1f - (48.dp.toPx() / fullWidth), when (predictiveBackState) { CompletablePredictiveBackState.NotRunning -> 0f is CompletablePredictiveBackState.Running -> predictiveBackState.progress CompletablePredictiveBackState.Completed -> if (lastRunningValue == null) 0f else 1f }, ) scaleX = scale scaleY = scale // Set the transform origin to be at the point of the sheet that is at the bottom // edge of the screen transformOrigin = TransformOrigin( 0.5f, (size.height - sheetState.requireOffset()) / size.height, ) }, shape = shape, color = containerColor, contentColor = contentColor, tonalElevation = tonalElevation, ) { Column( Modifier .fillMaxWidth() .windowInsetsPadding(contentWindowInsets()), ) { if (dragHandle != null) { val collapseActionLabel = "collapse" // TODO: getString(Strings.BottomSheetPartialExpandDescription) val dismissActionLabel = "dismiss" // TODO: getString(Strings.BottomSheetDismissDescription) val expandActionLabel = "expand" // TODO: getString(Strings.BottomSheetExpandDescription) Box( Modifier .align(Alignment.CenterHorizontally) .semantics(mergeDescendants = true) { // Provides semantics to interact with the bottomsheet based on its // current value. with(sheetState) { dismiss(dismissActionLabel) { animateToDismiss() true } if (currentValue == PartiallyExpanded) { expand(expandActionLabel) { if (sheetState.confirmValueChange(Expanded)) { scope.launch { sheetState.expand() } } true } } else if (hasPartiallyExpandedState) { collapse(collapseActionLabel) { if (sheetState.confirmValueChange(PartiallyExpanded)) { scope.launch { partialExpand() } } true } } } }, ) { dragHandle() } } content() } } } } } @Composable private fun Scrim( color: Color, onDismissRequest: () -> Unit, visible: Boolean, ) { if (color.isSpecified) { val alpha by animateFloatAsState( targetValue = if (visible) 1f else 0f, animationSpec = TweenSpec(), ) val dismissSheet = if (visible) { Modifier .pointerInput(onDismissRequest) { detectTapGestures { onDismissRequest() } } .clearAndSetSemantics {} } else { Modifier } Canvas( Modifier .fillMaxSize() .then(dismissSheet), ) { drawRect(color = color, alpha = alpha) } } } @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) internal fun ConsumeSwipeWithinBottomSheetBoundsNestedScrollConnection( sheetState: SheetState, orientation: Orientation, onFling: (velocity: Float) -> Unit, ): NestedScrollConnection = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { val delta = available.toFloat() return if (delta < 0 && source == NestedScrollSource.Drag) { sheetState.anchoredDraggableState.dispatchRawDelta(delta).toOffset() } else { Offset.Zero } } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource, ): Offset { return if (source == NestedScrollSource.Drag) { sheetState.anchoredDraggableState.dispatchRawDelta(available.toFloat()).toOffset() } else { Offset.Zero } } override suspend fun onPreFling(available: Velocity): Velocity { val toFling = available.toFloat() val currentOffset = sheetState.requireOffset() val minAnchor = sheetState.anchoredDraggableState.anchors.minAnchor() return if (toFling < 0 && currentOffset > minAnchor) { onFling(toFling) // since we go to the anchor with tween settling, consume all for the best UX available } else { Velocity.Zero } } override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity { onFling(available.toFloat()) return available } private fun Float.toOffset(): Offset = Offset( x = if (orientation == Orientation.Horizontal) this else 0f, y = if (orientation == Orientation.Vertical) this else 0f, ) @JvmName("velocityToFloat") private fun Velocity.toFloat() = if (orientation == Orientation.Horizontal) x else y @JvmName("offsetToFloat") private fun Offset.toFloat(): Float = if (orientation == Orientation.Horizontal) x else y } /** * State of a sheet composable, such as [ModalBottomSheet] * * Contains states relating to its swipe position as well as animations between state values. * * @param skipPartiallyExpanded Whether the partially expanded state, if the sheet is large * enough, should be skipped. If true, the sheet will always expand to the [Expanded] state and move * to the [Hidden] state if available when hiding the sheet, either programmatically or by user * interaction. * @param density The density that this state can use to convert values to and from dp. * @param initialValue The initial value of the state. * @param confirmValueChange Optional callback invoked to confirm or veto a pending state change. * @param skipHiddenState Whether the hidden state should be skipped. If true, the sheet will always * expand to the [Expanded] state and move to the [PartiallyExpanded] if available, either * programmatically or by user interaction. */ @Stable @ExperimentalMaterial3Api @OptIn(ExperimentalFoundationApi::class) class SheetState( internal val skipPartiallyExpanded: Boolean, internal var density: Density, initialValue: SheetValue = Hidden, internal val confirmValueChange: (SheetValue) -> Boolean = { true }, internal val skipHiddenState: Boolean = false, ) { init { if (skipPartiallyExpanded) { require(initialValue != PartiallyExpanded) { "The initial value must not be set to PartiallyExpanded if skipPartiallyExpanded " + "is set to true." } } if (skipHiddenState) { require(initialValue != Hidden) { "The initial value must not be set to Hidden if skipHiddenState is set to true." } } } /** * The current value of the state. * * If no swipe or animation is in progress, this corresponds to the state the bottom sheet is * currently in. If a swipe or an animation is in progress, this corresponds the state the sheet * was in before the swipe or animation started. */ val currentValue: SheetValue get() = anchoredDraggableState.currentValue /** * The target value of the bottom sheet state. * * If a swipe is in progress, this is the value that the sheet would animate to if the * swipe finishes. If an animation is running, this is the target value of that animation. * Finally, if no swipe or animation is in progress, this is the same as the [currentValue]. */ val targetValue: SheetValue get() = anchoredDraggableState.targetValue /** * Whether the modal bottom sheet is visible. */ val isVisible: Boolean get() = anchoredDraggableState.currentValue != Hidden /** * Require the current offset (in pixels) of the bottom sheet. * * The offset will be initialized during the first measurement phase of the provided sheet * content. * * These are the phases: * Composition { -> Effects } -> Layout { Measurement -> Placement } -> Drawing * * During the first composition, an [IllegalStateException] is thrown. In subsequent * compositions, the offset will be derived from the anchors of the previous pass. Always prefer * accessing the offset from a LaunchedEffect as it will be scheduled to be executed the next * frame, after layout. * * @throws IllegalStateException If the offset has not been initialized yet */ fun requireOffset(): Float = anchoredDraggableState.requireOffset() /** * Whether the sheet has an expanded state defined. */ val hasExpandedState: Boolean get() = anchoredDraggableState.anchors.hasAnchorFor(Expanded) /** * Whether the modal bottom sheet has a partially expanded state defined. */ val hasPartiallyExpandedState: Boolean get() = anchoredDraggableState.anchors.hasAnchorFor(PartiallyExpanded) /** * Fully expand the bottom sheet with animation and suspend until it is fully expanded or * animation has been cancelled. * * * @throws [CancellationException] if the animation is interrupted */ suspend fun expand() { anchoredDraggableState.animateTo(Expanded) } /** * Animate the bottom sheet and suspend until it is partially expanded or animation has been * cancelled. * @throws [CancellationException] if the animation is interrupted * @throws [IllegalStateException] if [skipPartiallyExpanded] is set to true */ suspend fun partialExpand() { check(!skipPartiallyExpanded) { "Attempted to animate to partial expanded when skipPartiallyExpanded was enabled. Set" + " skipPartiallyExpanded to false to use this function." } animateTo(PartiallyExpanded) } /** * Expand the bottom sheet with animation and suspend until it is [PartiallyExpanded] if defined * else [Expanded]. * @throws [CancellationException] if the animation is interrupted */ suspend fun show() { val targetValue = when { hasPartiallyExpandedState -> PartiallyExpanded else -> Expanded } animateTo(targetValue) } /** * Hide the bottom sheet with animation and suspend until it is fully hidden or animation has * been cancelled. * @throws [CancellationException] if the animation is interrupted */ suspend fun hide() { check(!skipHiddenState) { "Attempted to animate to hidden when skipHiddenState was enabled. Set skipHiddenState" + " to false to use this function." } animateTo(Hidden) } /** * Animate to a [targetValue]. * If the [targetValue] is not in the set of anchors, the [currentValue] will be updated to the * [targetValue] without updating the offset. * * @throws CancellationException if the interaction interrupted by another interaction like a * gesture interaction or another programmatic interaction like a [animateTo] or [snapTo] call. * * @param targetValue The target value of the animation */ internal suspend fun animateTo( targetValue: SheetValue, velocity: Float = anchoredDraggableState.lastVelocity, ) { anchoredDraggableState.animateToWithDecay(targetValue, velocity) } /** * Snap to a [targetValue] without any animation. * * @throws CancellationException if the interaction interrupted by another interaction like a * gesture interaction or another programmatic interaction like a [animateTo] or [snapTo] call. * * @param targetValue The target value of the animation */ internal suspend fun snapTo(targetValue: SheetValue) { anchoredDraggableState.snapTo(targetValue) } /** * Find the closest anchor taking into account the velocity and settle at it with an animation. */ internal suspend fun settle(velocity: Float) { anchoredDraggableState.settle(velocity) } internal var anchoredDraggableState = AnchoredDraggableState( initialValue = initialValue, snapAnimationSpec = spring(), decayAnimationSpec = exponentialDecay(), confirmValueChange = confirmValueChange, positionalThreshold = { with(density) { 56.dp.toPx() } }, velocityThreshold = { with(density) { 125.dp.toPx() } }, ) internal val offset: Float get() = anchoredDraggableState.offset companion object { /** * The default [Saver] implementation for [SheetState]. */ fun Saver( skipPartiallyExpanded: Boolean, confirmValueChange: (SheetValue) -> Boolean, density: Density, ) = Saver<SheetState, SheetValue>( save = { it.currentValue }, restore = { savedValue -> SheetState(skipPartiallyExpanded, density, savedValue, confirmValueChange) }, ) } } @Composable @ExperimentalMaterial3Api internal fun rememberSheetState( skipPartiallyExpanded: Boolean = false, confirmValueChange: (SheetValue) -> Boolean = { true }, initialValue: SheetValue = Hidden, skipHiddenState: Boolean = false, ): SheetState { val density = LocalDensity.current return rememberSaveable( skipPartiallyExpanded, confirmValueChange, saver = SheetState.Saver( skipPartiallyExpanded = skipPartiallyExpanded, confirmValueChange = confirmValueChange, density = density, ), ) { SheetState( skipPartiallyExpanded, density, initialValue, confirmValueChange, skipHiddenState, ) } } /** * Create and [remember] a [SheetState] for [ModalBottomSheet]. * * @param skipPartiallyExpanded Whether the partially expanded state, if the sheet is tall enough, * should be skipped. If true, the sheet will always expand to the [Expanded] state and move to the * [Hidden] state when hiding the sheet, either programmatically or by user interaction. * @param confirmValueChange Optional callback invoked to confirm or veto a pending state change. */ @Composable @ExperimentalMaterial3Api fun rememberModalBottomSheetState( skipPartiallyExpanded: Boolean = false, confirmValueChange: (SheetValue) -> Boolean = { true }, ) = rememberSheetState(skipPartiallyExpanded, confirmValueChange, Hidden) @OptIn(ExperimentalMaterial3Api::class) @Preview @Composable internal fun EdgeToEdgeModalBottomSheetPreview() { var showEdgeToEdgeModalBottomSheet by rememberSaveable { mutableStateOf(false) } var showModalBottomSheet by rememberSaveable { mutableStateOf(false) } val context = LocalContext.current SideEffect { (context as? ComponentActivity)?.enableEdgeToEdge() } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { BasicText( modifier = Modifier .height(64.dp) .clickable { showEdgeToEdgeModalBottomSheet = true }, text = "Show edge-to-edge modal bottom sheet", ) BasicText( modifier = Modifier .height(64.dp) .clickable { showModalBottomSheet = true }, text = "Show built-in modal bottom sheet", ) } if (showEdgeToEdgeModalBottomSheet) { EdgeToEdgeModalBottomSheet( onDismissRequest = { showEdgeToEdgeModalBottomSheet = false }, ) { LazyColumn { items(100) { _ -> var textFieldValue by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue()) } TextField(value = textFieldValue, onValueChange = { textFieldValue = it }) } } } } if (showModalBottomSheet) { ModalBottomSheet( onDismissRequest = { showModalBottomSheet = false }, ) { LazyColumn { items(100) { _ -> var textFieldValue by remember { mutableStateOf(TextFieldValue()) } TextField(value = textFieldValue, onValueChange = { textFieldValue = it }) } } } } }
43
null
11
99
64595b8d36c559a70ca52d578069fe4df8d170c7
30,865
composelife
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/Fragment.kt
Hexworks
94,116,947
false
{"Kotlin": 1614685, "Shell": 64}
package org.hexworks.zircon.api.component /** * A [Fragment] is a reusable container for a [Component]. This [Component] * can be accessed by [root]. * * A [Fragment] usually contains view logic that works with the controls that are * present in [root]. * * @sample org.hexworks.zircon.samples.ConfirmButton */ interface Fragment { /** * The [Component] this [Fragment] contains. */ val root: Component }
42
Kotlin
138
738
55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6
433
zircon
Apache License 2.0
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/Utility.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing import silentorb.mythic.spatial.Vector3 import silentorb.mythic.spatial.Vector3i import silentorb.mythic.spatial.toVector3 fun isInsideBounds(bounds: DecimalBounds, position: Vector3) = position.x >= bounds.start.x && position.y >= bounds.start.y && position.z >= bounds.start.z && position.x < bounds.end.x && position.y < bounds.end.y && position.z < bounds.end.z fun getBoundsDimensions(bounds: GridBounds): Vector3i = bounds.end - bounds.start fun getBoundsCellCount(bounds: GridBounds): Int { val dimensions = getBoundsDimensions(bounds) return dimensions.x * dimensions.y * dimensions.z } fun toDecimalBounds(scale: Float, bounds: GridBounds) = DecimalBounds( start = bounds.start.toVector3() * scale, end = bounds.end.toVector3() * scale ) fun edgeContains(edge: Edge, vertex: Vector3): Boolean = edge.first == vertex || edge.second == vertex fun getEdgeVector(edge: Edge): Vector3 = (edge.second - edge.first).normalize() fun getEdgeVertices(edge: Edge): List<Vector3> = listOf(edge.first, edge.second) fun replaceEdgeVertex(edge: Edge, old: Vector3, replacement: Vector3): Edge = if (edge.first == old) Edge(replacement, edge.second) else if (edge.second == old) Edge(edge.first, replacement) else edge fun getOtherVertex(edge: Edge, vertex: Vector3): Vector3 = if (vertex == edge.first) edge.second else edge.first fun getFaceNormal(face: VertexFace): Vector3 { val second = face[1] val a = (second - face[0]).normalize() val b = (face[2] - second).normalize() return a.cross(b) } fun edgesMatch(a: Edge, b: Edge): Boolean = a == b || (a.second == b.first && a.first == b.second)
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
1,794
mythic-kotlin
MIT License
src/main/kotlin/org/xpathqs/core/selector/selector/SelectorModificationExtensions.kt
xpathqs
363,898,788
false
null
/* * Copyright (c) 2021 XPATH-QS * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.xpathqs.core.selector.selector import org.xpathqs.core.reflection.setProps import org.xpathqs.core.selector.extensions.core.clone /** * Modifies `tag` value of [Selector] */ fun <T : Selector> T.tag(value: String): T { val res = this.clone() res.setProps(props.clone(tag = value)) return res } /** * Modifies `prefix` value of [Selector] */ fun <T : Selector> T.prefix(value: String) = clone { setProps(props.clone(prefix = value)) } /** * Modifies `postfix` value of [Selector] */ fun <T : Selector> T.postfix(value: String) = clone { setProps(props.clone(postfix = value)) } private fun <T : Selector> T.clone(f: Selector.() -> Unit): T { val res = this.clone() res.f() return res }
3
null
8
5
1dcbdf054cd9621090bedc511f37920e53b56514
1,854
core
MIT License
Controls/src/commonMain/kotlin/io/nacular/doodle/controls/panels/GridPanel.kt
nacular
108,631,782
false
null
package io.nacular.doodle.controls.panels import io.nacular.doodle.controls.panels.SizingPolicy.OverlappingView import io.nacular.doodle.core.Layout import io.nacular.doodle.core.PositionableContainer import io.nacular.doodle.core.View import io.nacular.doodle.geometry.Rectangle import io.nacular.doodle.geometry.Size import io.nacular.doodle.layout.Constraints import io.nacular.doodle.layout.constrain import io.nacular.doodle.layout.fill import kotlin.math.max import kotlin.math.min /** * Created by <NAME> on 5/1/20. */ public interface SizingPolicy { public class OverlappingView(public val span: Int, public val size: Double, public val idealSize: Double?) public operator fun invoke(panelSize: Double, spacing: Double, views: Map<Int, List<OverlappingView>>): Map<Int, Double> } public typealias SpacingPolicy = (panelSize: Double) -> Double private class FitContent: SizingPolicy { override fun invoke(panelSize: Double, spacing: Double, views: Map<Int, List<OverlappingView>>): Map<Int, Double> = views.mapValues { entry -> var size = 0.0 entry.value.forEach { size = max(size, (it.size - spacing * (it.span - 1)) / it.span) } size } } private class FitPanel: SizingPolicy { override fun invoke(panelSize: Double, spacing: Double, views: Map<Int, List<OverlappingView>>): Map<Int, Double> = views.mapValues { max(0.0, (panelSize - spacing * (views.size - 1)) / views.size) } } public open class GridPanel: View() { private class Location(val row: Int, val column: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Location) return false if (row != other.row) return false if (column != other.column) return false return true } override fun hashCode(): Int { var result = row result = 31 * result + column return result } } private class Dimensions(var offset: Double = 0.0, var size: Double = 0.0) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Dimensions) return false if (offset != other.offset) return false if (size != other.size) return false return true } override fun hashCode(): Int { var result = offset.hashCode() result = 31 * result + size.hashCode() return result } } private val locations = mutableMapOf<View, Set<Location>>() private val rowSpans = mutableMapOf<View, Int>().withDefault { 1 } private val columnSpans = mutableMapOf<View, Int>().withDefault { 1 } private var rowDimensions = mapOf<Int, Dimensions>() private var columnDimensions = mapOf<Int, Dimensions>() public var cellAlignment : Constraints.() -> Unit = fill //center public var verticalSpacing : SpacingPolicy = { 0.0 } public var horizontalSpacing : SpacingPolicy = { 0.0 } public var rowSizingPolicy : SizingPolicy = FitContent public var columnSizingPolicy: SizingPolicy = FitContent final override var layout: Layout? = GridLayout() public fun add(child: View, row: Int = 0, column: Int = 0, rowSpan: Int = 1, columnSpan: Int = 1) { locations[child] = mutableSetOf<Location>().apply { repeat(rowSpan) { r -> repeat(columnSpan) { c -> add(Location(row = max(0, row + r), column = max(0, column + c))) } } } if (rowSpan > 1) rowSpans [child] = rowSpan if (columnSpan > 1) columnSpans[child] = columnSpan children += child } public fun remove(child: View) { locations -= child rowSpans -= child columnSpans -= child children -= child } public fun clear() { locations.clear () rowSpans.clear () columnSpans.clear() children.clear () } private inner class GridLayout: Layout { private var idealWidth = null as Double? private var idealHeight = null as Double? override fun idealSize(container: PositionableContainer, default: Size?) = idealWidth?.let { w -> idealHeight?.let { h -> Size(w, h) } } override fun layout(container: PositionableContainer) { val rowLanes = mutableMapOf<Int, MutableList<OverlappingView>>() val colLanes = mutableMapOf<Int, MutableList<OverlappingView>>() // Calculate row and column sizes children.forEach { child -> locations[child]?.forEach { val rowSpan = rowSpans.getValue (child) val colSpan = columnSpans.getValue(child) rowLanes.getOrPut(it.row ) { mutableListOf() }.also { it += OverlappingView(rowSpan, child.size.height, child.idealSize?.height) } colLanes.getOrPut(it.column) { mutableListOf() }.also { it += OverlappingView(colSpan, child.size.width, child.idealSize?.width ) } } } val verticalSpacing = verticalSpacing (height) val horizontalSpacing = horizontalSpacing(width ) rowDimensions = rowSizingPolicy (height, verticalSpacing, rowLanes).mapValues { Dimensions(0.0, it.value) } columnDimensions = columnSizingPolicy(width, horizontalSpacing, colLanes).mapValues { Dimensions(0.0, it.value) } var offset = 0.0 rowDimensions.entries.sortedBy { it.key }.forEach { it.value.offset = offset offset += it.value.size + verticalSpacing } idealHeight = offset - if (rowDimensions.size > 1) verticalSpacing else 0.0 offset = 0.0 columnDimensions.entries.sortedBy { it.key }.forEach { it.value.offset = offset offset += it.value.size + horizontalSpacing } idealWidth = offset - if (columnDimensions.size > 1) horizontalSpacing else 0.0 children.forEach { child -> var x = null as Double? var y = null as Double? val widths = mutableSetOf<Dimensions>() val heights = mutableSetOf<Dimensions>() locations[child]?.forEach { val rowDim = rowDimensions.getValue (it.row ) val colDim = columnDimensions.getValue(it.column) x = min(x ?: colDim.offset, colDim.offset) y = min(y ?: rowDim.offset, rowDim.offset) widths.add (colDim) heights.add(rowDim) } constrain(child, within = Rectangle( x ?: 0.0, y ?: 0.0, widths.map { it.size }.sum() + horizontalSpacing * (widths.size - 1), heights.map { it.size }.sum() + verticalSpacing * (heights.size - 1)), block = cellAlignment) } container.idealSize = Size(idealWidth!!, idealHeight!!) } } public companion object { public val FitPanel : SizingPolicy = FitPanel () public val FitContent: SizingPolicy = FitContent() } }
3
null
12
273
40d6b729126013456b479702c7266a8dc902fe3c
7,593
doodle
MIT License
server/src/main/kotlin/com/github/vatbub/matchmaking/server/WebsocketEndpoint.kt
vatbub
162,929,659
false
null
/*- * #%L * matchmaking.server * %% * Copyright (C) 2016 - 2019 <NAME> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.github.vatbub.matchmaking.server import com.github.vatbub.matchmaking.common.InteractionConverter import com.github.vatbub.matchmaking.common.Request import com.github.vatbub.matchmaking.common.logger import com.github.vatbub.matchmaking.server.logic.IpAddressHelper import com.github.vatbub.matchmaking.server.logic.ServerContext import com.github.vatbub.matchmaking.server.logic.configuration.Configuration import com.github.vatbub.matchmaking.server.logic.configuration.ConfigurationManager import java.net.Inet4Address import java.net.Inet6Address import javax.websocket.* import javax.websocket.CloseReason.CloseCodes import javax.websocket.server.HandshakeRequest import javax.websocket.server.ServerEndpoint import javax.websocket.server.ServerEndpointConfig const val httpHeadersKey = "httpHeaders" @ServerEndpoint("/websocket", configurator = WebSocketSessionConfigurator::class) class WebsocketEndpoint(initialServerContext: ServerContext? = null) { private var sessionWrapper: WebsocketSessionWrapper? = null private var endpointConfig: EndpointConfig? = null @Suppress("UNCHECKED_CAST") private val httpHeaders: Map<String, List<String>>? get() { val endpointConfigCopy = endpointConfig ?: return null return endpointConfigCopy.userProperties[httpHeadersKey] as Map<String, List<String>>? } private val remoteIpString: String? get() { val forwardedForHeaderUppercase = getHeaderIfExists("X-FORWARDED-FOR") if (forwardedForHeaderUppercase != null) return forwardedForHeaderUppercase val forwardedForHeaderLowercase = getHeaderIfExists("x-forwarded-for") if (forwardedForHeaderLowercase != null) return forwardedForHeaderLowercase val originHeaderUppercase = getHeaderIfExists("ORIGIN") if (originHeaderUppercase != null) return originHeaderUppercase val originHeaderLowercase = getHeaderIfExists("origin") if (originHeaderLowercase != null) return originHeaderLowercase return null } private val remoteInet4Address: Inet4Address? get() = IpAddressHelper.convertToIpv4(remoteIpString) private val remoteInet6Address: Inet6Address? get() = IpAddressHelper.convertToIpv6(remoteIpString) private fun getHeaderIfExists(headerName: String): String? { val httpHeadersCopy = httpHeaders ?: return null if (!httpHeadersCopy.containsKey(headerName)) return null val result = httpHeadersCopy[headerName] ?: return null if (result.isEmpty()) return null return result[0] } var serverContext: ServerContext private set init { serverContext = if (initialServerContext != null) initialServerContext else { ConfigurationManager.onChangeListeners.add(this::reloadConfiguration) ConfigurationManager.currentConfiguration.getAsServerContext() } serverContext.resetMessageHandlers() } @Suppress("UNUSED_PARAMETER") private fun reloadConfiguration(oldConfiguration: Configuration, newConfiguration: Configuration) { logger.info { "Loading new configuration into WebsocketEndpoint..." } serverContext = newConfiguration.getAsServerContext() serverContext.resetMessageHandlers() } @OnOpen fun open(session: Session, endpointConfig: EndpointConfig) { logger.info { "A new websocket was opened" } this.sessionWrapper = WebsocketSessionWrapper(session) this.endpointConfig = endpointConfig } @OnMessage fun onTextMessage(session: Session, message: String) { logger.debug { "Received a text message through WebsocketEndpoint" } logger.trace { "Received the following text message through WebsocketEndpoint: $message" } val request = InteractionConverter.deserialize<Request>(message) val responseInteraction = serverContext.messageDispatcher.dispatchOrCreateException( request, remoteInet4Address, remoteInet6Address, sessionWrapper!! ) logger.debug { "Response generated, now serializing..." } val responseJson = InteractionConverter.serialize(responseInteraction) logger.trace { "The following response was generated: $responseJson" } session.asyncRemote.sendText(responseJson) logger.debug { "Response sent" } } @OnClose fun onSessionClose(session: Session, closeReason: CloseReason) { when (closeReason.closeCode) { CloseCodes.PROTOCOL_ERROR, CloseCodes.CANNOT_ACCEPT, CloseCodes.NO_STATUS_CODE, CloseCodes.CLOSED_ABNORMALLY, CloseCodes.NOT_CONSISTENT, CloseCodes.VIOLATED_POLICY, CloseCodes.TOO_BIG, CloseCodes.NO_EXTENSION, CloseCodes.UNEXPECTED_CONDITION, CloseCodes.SERVICE_RESTART, CloseCodes.TRY_AGAIN_LATER, CloseCodes.TLS_HANDSHAKE_FAILURE -> logger.error (closeReason::generateLogMessage) else -> logger.info (closeReason::generateLogMessage) } val sessionWrapperCopy = sessionWrapper ?: return serverContext.messageDispatcher.dispatchWebsocketSessionClosed(sessionWrapperCopy) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is WebsocketEndpoint) return false if (serverContext != other.serverContext) return false return true } override fun hashCode(): Int { return serverContext.hashCode() } } class WebSocketSessionConfigurator : ServerEndpointConfig.Configurator() { override fun modifyHandshake( serverEndpointConfig: ServerEndpointConfig?, request: HandshakeRequest?, response: HandshakeResponse? ) { if (request == null) return if (serverEndpointConfig == null) return serverEndpointConfig.userProperties[httpHeadersKey] = request.headers } }
11
Kotlin
5
32
7ece6b79c6ea15dcf636851a61fde6dc6615188d
6,835
matchmaking
Apache License 2.0
core/src/main/java/com/abhat/core/model/ChildrenData.kt
AnirudhBhat
257,323,871
false
null
package com.abhat.core.model import com.abhat.core.PointsFormatter import com.squareup.moshi.Json /** * Created by Anirudh Uppunda on 04,May,2020 */ data class ChildrenData( var isGif: Boolean, var gifLink: String?, var indent: Int, var shouldUseGlideForGif: Boolean = false, var imageUrl: String? = null, @field:Json(name="over_18") val over18: Boolean? = null, @field:Json(name = "crosspost_parent_list") val crossPost: List<CrossPost>, @field:Json(name = "saved") var saved:Boolean, @field:Json(name = "upvoted") var upvoted:Boolean, @field:Json(name = "downvoted") var downvoted:Boolean, @field:Json(name = "likes") var likes:Any, @field:Json(name = "subreddit") val subreddit:String, @field:Json(name = "subreddit_id") val subredditId:String, @field:Json(name = "link_id") val linkId:String, @field:Json(name = "author") val author:String, @field:Json(name = "body") val body: String, @field:Json(name = "body_html") val bodyHtml:String?, @field:Json(name = "selftext_html") val selfTextHtml:String?, @field:Json(name = "children") val children: List<String>?, @field:Json(name = "count") val count: Int, @field:Json(name = "created_utc") val createdUtc:Long, @field:Json(name = "depth") val depth: Int, @field:Json(name = "id") val id: String, @field:Json(name = "is_submitter") val isSubmitter: Boolean, @field:Json(name = "name") val name: String, @field:Json(name="num_comments") val numComments:Int, @field:Json(name = "parent_id") val parentId: String, @field:Json(name = "replies") val replies: RedditResponse?, @field:Json(name="score") val score:Int, @field:Json(name="title") val title:String, @field:Json(name="link_title") val linkTitle:String, @field:Json(name="url") val url:String?, @field:Json(name="thumbnail") val thumbnail:String?, @field:Json(name="preview") val preview: Preview?, @field:Json(name="media") val media: Media?, @field:Json(name="secure_media") val secureMedia: SecureMedia?, @field:Json(name="is_video") val isVideo: Boolean = false, @field:Json(name="domain") val domain: String )
1
null
1
1
9036e653ed15d34241dcc5397efc687bae89328f
2,310
Reddit-client
Apache License 2.0
src/commonMain/kotlin/nl/astraeus/css/properties/TextTransform.kt
rnentjes
413,056,107
false
{"Kotlin": 117943}
package nl.astraeus.css.properties class TextTransform( value: String ) : CssProperty(value) { companion object { val none = TextTransform("none") val capitalize = TextTransform("capitalize") val uppercase = TextTransform("uppercase") val lowercase = TextTransform("lowercase") val initial = TextTransform("initial") val inherit = TextTransform("inherit") } }
0
Kotlin
0
0
d2349c930846fec7a57c879cdacd931368dda965
393
kotlin-css-generator
MIT License
plugins/android-extensions/android-extensions-compiler/test/org/jetbrains/kotlin/android/synthetic/test/AbstractAndroidSyntheticPropertyDescriptorTest.kt
JetBrains
3,432,266
false
null
/* * 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.android.synthetic.test import org.jetbrains.kotlin.android.synthetic.res.AndroidPackageFragmentProviderExtension import org.jetbrains.kotlin.android.synthetic.res.AndroidSyntheticPackageFragmentProvider import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.MemberComparator import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension import org.jetbrains.kotlin.resolve.lazy.JvmResolveUtil import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.test.ConfigurationKind import org.jetbrains.kotlin.test.DummyTraces import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TestJdkKind import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase import java.io.File abstract class AbstractAndroidSyntheticPropertyDescriptorTest : KtUsefulTestCase() { fun doTest(path: String) { val config = KotlinTestUtils.newConfiguration(ConfigurationKind.ALL, TestJdkKind.ANDROID_API) val env = createTestEnvironment(config, getResPaths(path)) val project = env.project val ext = PackageFragmentProviderExtension.getInstances(project).first { it is AndroidPackageFragmentProviderExtension } val analysisResult = JvmResolveUtil.analyzeAndCheckForErrors(listOf(), env) val fragmentProvider = ext.getPackageFragmentProvider( project, analysisResult.moduleDescriptor, LockBasedStorageManager.NO_LOCKS, DummyTraces.DUMMY_EXCEPTION_ON_ERROR_TRACE, null, LookupTracker.DO_NOTHING ) as AndroidSyntheticPackageFragmentProvider val renderer = DescriptorRenderer.COMPACT_WITH_MODIFIERS val expected = fragmentProvider.packages.values .map { it() } .sortedBy { it.fqName.asString() } .joinToString(separator = "\n\n\n") { packageFragment -> val descriptors = packageFragment.getMemberScope().getContributedDescriptors() .sortedWith(MemberComparator.INSTANCE) .joinToString("\n") { " " + renderer.render(it) } packageFragment.fqName.asString() + (if (descriptors.isNotEmpty()) "\n\n" + descriptors else "") } KotlinTestUtils.assertEqualsToFile(File(path, "result.txt"), expected) } }
179
null
5706
48,889
c46c3c26038158cf80a739431ac8807ac4bbbc0c
2,602
kotlin
Apache License 2.0
instrumentation-tests/src/androidTest/java/com/mapbox/navigation/instrumentation_tests/utils/assertions/RoadObject.kt
mapbox
87,455,763
false
{"Kotlin": 9692008, "Python": 65081, "Java": 36829, "HTML": 17811, "Makefile": 9840, "Shell": 7129}
package com.mapbox.navigation.instrumentation_tests.utils.assertions import com.mapbox.navigation.base.trip.model.roadobject.RoadObject fun RoadObject.compareIdWithIncidentId(incidentId: String): Boolean = id.contains(incidentId)
505
Kotlin
319
621
ad73c6011348cb9b24b92a369024ca06f48845ab
232
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/flowfoundation/wallet/utils/image/SvgModel.kt
Outblock
692,942,645
false
{"Kotlin": 2429248, "Java": 104150}
package com.flowfoundation.wallet.utils.image import android.graphics.drawable.PictureDrawable import android.util.Base64 import com.bumptech.glide.Priority import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.Options import com.bumptech.glide.load.data.DataFetcher import com.bumptech.glide.load.model.ModelLoader import com.bumptech.glide.load.model.ModelLoaderFactory import com.bumptech.glide.load.model.MultiModelLoaderFactory import com.bumptech.glide.signature.ObjectKey import com.caverock.androidsvg.SVG import com.caverock.androidsvg.SVGParseException class SvgModel(val svgString: String) class SvgModelLoader : ModelLoader<SvgModel, PictureDrawable> { override fun handles(model: SvgModel): Boolean = true override fun buildLoadData( model: SvgModel, width: Int, height: Int, options: Options ): ModelLoader.LoadData<PictureDrawable>? { return ModelLoader.LoadData(ObjectKey(model), SvgDataFetcher(model.svgString)) } } // Custom DataFetcher for SVG class SvgDataFetcher(private val svgString: String) : DataFetcher<PictureDrawable> { override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in PictureDrawable>) { try { val decodedBytes = Base64.decode(svgString, Base64.DEFAULT) val svg = SVG.getFromString(String(decodedBytes)) val drawable = PictureDrawable(svg.renderToPicture()) callback.onDataReady(drawable) } catch (e: SVGParseException) { callback.onLoadFailed(e) } } override fun cleanup() { // no-op } override fun cancel() { // no-op } override fun getDataClass(): Class<PictureDrawable> { return PictureDrawable::class.java } override fun getDataSource(): DataSource = DataSource.LOCAL } // Custom ModelLoaderFactory for SVG class SvgModelLoaderFactory : ModelLoaderFactory<SvgModel, PictureDrawable> { override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<SvgModel, PictureDrawable> { return SvgModelLoader() } override fun teardown() { // no-op } }
62
Kotlin
5
0
8ad633b7bccc02ae6b3005ca3989379ed8fb248d
2,177
FRW-Android
Apache License 2.0
src/main/kotlin/ch/sourcemotion/vertx/redis/client/heimdall/impl/subscription/connection/RedisHeimdallSubscriptionConnection.kt
wem
305,085,016
false
{"Kotlin": 162547}
package ch.sourcemotion.vertx.redis.client.heimdall.impl.subscription.connection import ch.sourcemotion.vertx.redis.client.heimdall.RedisHeimdallException import ch.sourcemotion.vertx.redis.client.heimdall.RedisHeimdallException.Reason import ch.sourcemotion.vertx.redis.client.heimdall.impl.connection.RedisHeimdallConnection import ch.sourcemotion.vertx.redis.client.heimdall.impl.subscription.SubscriptionStore import ch.sourcemotion.vertx.redis.client.heimdall.impl.subscription.verifySubscriptionCommandOnly import ch.sourcemotion.vertx.redis.client.heimdall.impl.subscription.verifySubscriptionCommandsOnly import io.vertx.core.CompositeFuture import io.vertx.core.Future import io.vertx.core.Handler import io.vertx.core.Promise import io.vertx.core.logging.LoggerFactory import io.vertx.redis.client.Command import io.vertx.redis.client.RedisConnection import io.vertx.redis.client.Request import io.vertx.redis.client.Response /** * Redis connection designed to be used for subscription purposes only. */ internal class RedisHeimdallSubscriptionConnection( delegate: RedisConnection, connectionIssueHandler: Handler<Throwable>, private val subscriptionStore: SubscriptionStore, private val messageHandler: Handler<Response>, ) : RedisHeimdallConnection(delegate, connectionIssueHandler) { companion object { private val logger = LoggerFactory.getLogger(RedisHeimdallSubscriptionConnection::class.java) val supportedCommands = listOf(Command.SUBSCRIBE, Command.UNSUBSCRIBE, Command.PSUBSCRIBE, Command.PUNSUBSCRIBE) } override fun initConnection(): RedisHeimdallConnection { super.initConnection() // Call super instead of this reference is mandatory here, as this implementation prevents setting the handler by interface. super.handler(this::handleSubscriptionMessage) return this } override fun handler(handler: Handler<Response>): RedisConnection { // Avoid user bypasses the implementation throw RedisHeimdallException( Reason.UNSUPPORTED_ACTION, "In subscription mode, you should not register your own subscription handler, as it's handled by Redis Heimdall." ) } override fun send(command: Request): Future<Response> { val promise = Promise.promise<Response>() return if (verifySubscriptionCommandOnly(command.command(), promise)) { super.send(command) } else promise.future() // Future already completed here verifySubscriptionCommandsOnly will complete it } override fun batch(commands: List<Request>): Future<List<Response>> { val promise = Promise.promise<List<Response>>() return if (verifySubscriptionCommandsOnly(commands.map { it.command() }, promise)) { super.batch(commands) } else promise.future() // Future already completed here verifySubscriptionCommandsOnly will complete it } fun subscribeToChannelsAndPatterns( channelNames: List<String>, channelPatterns: List<String>, ): Future<Unit> { val promise = Promise.promise<Unit>() val commandFutures = ArrayList<Future<*>>() if (channelNames.isNotEmpty()) { val cmd = Request.cmd(Command.SUBSCRIBE) channelNames.addToCommandArgs(cmd) val future = send(cmd) .onSuccess { logger.info("Channel(s) $channelNames subscribed") } .onFailure { logger.warn("Subscription to channel(s) $channelNames failed", it) } commandFutures.add(future) } if (channelPatterns.isNotEmpty()) { val cmd = Request.cmd(Command.PSUBSCRIBE) channelPatterns.addToCommandArgs(cmd) val future = send(cmd) .onSuccess { logger.info("Channel pattern(s) $channelPatterns subscribed") }.onFailure { logger.warn("Subscription to channel pattern(s) $channelPatterns failed", it) } commandFutures.add(future) } if (commandFutures.isNotEmpty()) { CompositeFuture.all(commandFutures.toList()).onSuccess { promise.complete() }.onFailure { promise.fail(it) } } else { promise.complete() } return promise.future() } fun subscribeAfterReconnect(): Future<Unit> { val channelNames = subscriptionStore.subscriptions()?.toList() ?: emptyList() val patterns = subscriptionStore.patterns()?.toList() ?: emptyList() return subscribeToChannelsAndPatterns(channelNames, patterns) } private fun handleSubscriptionMessage(response: Response) { when { "${response[0]}" == "subscribe" -> subscriptionStore.addSubscription("${response[1]}") "${response[0]}" == "unsubscribe" -> subscriptionStore.removeSubscription("${response[1]}") "${response[0]}" == "psubscribe" -> subscriptionStore.addPattern("${response[1]}") "${response[0]}" == "punsubscribe" -> subscriptionStore.removePattern("${response[1]}") "${response[0]}" == "message" -> messageHandler.handle(response) "${response[0]}" == "pmessage" -> messageHandler.handle(response) else -> logger.warn("Response / Message type from Redis not supported \"$response\"") } } } fun List<String>.addToCommandArgs(command: Request) = command.apply { forEach { command.arg(it) } }
2
Kotlin
0
1
158e21b9de1a03b5ac5f2c9ffe050b3d2aa55fc6
5,597
vertx-redis-client-heimdall
MIT License
net.akehurst.kotlinx/kotlinx-reflect/src/appleMain/kotlin/kotlinx/reflection.kt
dhakehurst
189,049,817
false
{"Kotlin": 177637}
/** * Copyright (C) 2019 Dr. <NAME> (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.kotlinx.reflect import kotlin.reflect.KCallable import kotlin.reflect.KClass import kotlin.reflect.KFunction actual fun KFunction<*>.isSuspend(): Boolean = TODO() //this.isSuspend actual fun <T : Any> proxyFor(forInterface: KClass<*>, invokeMethod: (handler: Any, proxy: Any?, callable: KCallable<*>, methodName: String, args: Array<out Any>) -> Any?): T { TODO() } actual fun Any.reflect() = ObjectReflection(this) actual fun KClass<*>.reflect() = ClassReflection(this) actual class ClassReflection<T : Any> actual constructor(val kclass: KClass<T>) { companion object { const val metadata = "\$metadata\$" } actual val isAbstract: Boolean get() { return this.kclass.simpleName!!.endsWith("Abstract") } actual val allPropertyNames: List<String> by lazy { TODO() } actual val allMemberFunctions: List<KFunction<*>> by lazy { TODO() } actual val qualifiedName: String get() = KotlinxReflect.qualifiedNameForClass(this.kclass) actual val isEnum: Boolean get() { TODO() } actual val isObject: Boolean get() { TODO() } actual fun construct(vararg constructorArgs: Any?): T { TODO() } actual fun <S : Any> isSupertypeOf(subtype: KClass<S>): Boolean { TODO() } actual fun allPropertyNamesFor(self: T): List<String> { TODO() } // actual fun allMemberFunctionsFor(self: T): List<KFunction<*>> { // TODO() // } actual fun isPropertyMutable(propertyName: String): Boolean { TODO() } actual fun getProperty(self: T, propertyName: String): Any? { TODO() } actual fun setProperty(self: T, propertyName: String, value: Any?) { TODO() } actual fun <E : Enum<E>> enumValues(): List<E> { return if (isEnum) { //val jsCls = this.kclass.js.asDynamic() //jsCls.values().unsafeCast<Array<E>>().asList() KotlinxReflect.enumValues(this.qualifiedName) as List<E> } else { emptyList() } } actual fun <E : Enum<E>> enumValueOf(name: String): E? { return this.enumValues().firstOrNull { it.name == name } as E? } actual fun call(self: T, methodName: String, vararg args: Any?): Any? { TODO() } } actual class ObjectReflection<T : Any> actual constructor(val self: T) { actual val kclass: KClass<T> = self::class as KClass<T> actual val isAbstract: Boolean get() { return this.kclass.simpleName!!.endsWith("Abstract") //TODO !! need something better than this } actual val isProxy: Boolean get() = TODO() actual val allPropertyNames: List<String> by lazy { TODO() } actual fun construct(vararg constructorArgs: Any?): T { TODO() } actual fun <S : Any> isSupertypeOf(subtype: KClass<S>): Boolean { TODO() } actual fun isPropertyMutable(propertyName: String): Boolean { TODO() } actual fun getProperty(propertyName: String): Any? { TODO() } actual fun setProperty(propertyName: String, value: Any?) { TODO() } actual fun call(methodName: String, vararg args: Any?): Any? { TODO() } actual suspend fun callSuspend(methodName: String, vararg args: Any?): Any? { TODO() } }
0
Kotlin
0
1
0f29e96aa48d84efb1cd41ec469a68040b31ecc3
4,084
net.akehurst.kotlinx
Apache License 2.0
app/src/main/java/com/example/android/roomwordssample/users/ListUsers.kt
JRivasL
463,733,407
false
null
package com.example.android.roomwordssample.users import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.roomwordssample.R import com.example.android.roomwordssample.databinding.ActivityListUsersBinding import com.example.android.roomwordssample.listener.NextListener import com.example.android.roomwordssample.listener.ShowDetail import com.example.android.roomwordssample.retrofit.RetrofitService import com.example.android.roomwordssample.retrofit.model.ResponseUsers import com.example.android.roomwordssample.retrofit.model.User import com.example.android.roomwordssample.user.UserDetail import com.example.android.roomwordssample.users.adapter.UsersAdapter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class ListUsers : AppCompatActivity(), NextListener, ShowDetail { private var page = 1 lateinit var usersAdapter: UsersAdapter private lateinit var _binding: ActivityListUsersBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityListUsersBinding.inflate(layoutInflater) setContentView(_binding.root) initList() getData() } private fun initList() { val layoutManager = LinearLayoutManager(this) _binding.rvUsers.layoutManager = layoutManager usersAdapter = UsersAdapter(ArrayList(), this, this) _binding.rvUsers.adapter = usersAdapter } private fun getData() { CoroutineScope(Dispatchers.IO).launch { val response = RetrofitService.getInstance().getUsers(page.toString()) withContext(Dispatchers.Main) { validateResponse(response) } } } private fun validateResponse(response: ResponseUsers) { if(response.data.isNotEmpty()){ usersAdapter.addData(response.data) } else{ Toast.makeText(this, getString(R.string.error), Toast.LENGTH_LONG).show() } } override fun onNext() { page++ getData() } override fun onTap(user: User) { val intent = Intent(this, UserDetail::class.java) intent.putExtra("user", user) startActivity(intent) } }
0
Kotlin
0
0
6e52e1c413cfc54f50eff8093c09a8a4a1418e50
2,457
test
Apache License 2.0
compose_material3/src/main/java/dev/vengateshm/compose_material3/ComposeMaterial3Activity.kt
vengateshm
670,054,614
false
{"Kotlin": 2044992, "Java": 55066}
package dev.vengateshm.compose_material3 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import dagger.hilt.android.AndroidEntryPoint import dev.vengateshm.compose_material3.theme.Material3AppTheme import dev.vengateshm.compose_material3.utils.requestCameraPermission import dev.vengateshm.compose_material3.utils.requestNotificationPermission import dev.vengateshm.compose_material3.utils.requestRecordAudioPermission @AndroidEntryPoint class ComposeMaterial3Activity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() requestPermissions() setContent { Material3AppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { } } } } private fun requestPermissions() { requestNotificationPermission() requestCameraPermission() requestRecordAudioPermission() } }
0
Kotlin
0
1
5c1898b8c48a5ceac6d6b78b4267e1bdce7f5e9a
1,365
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
kotlin/clock/src/test/kotlin/ClockEqualTest.kt
rhdeck
280,610,618
true
{"Kotlin": 253660, "Shell": 11713}
import org.junit.Ignore import org.junit.Test import kotlin.test.assertNotEquals import kotlin.test.assertEquals /* * version: 1.0.1 */ class ClockEqualTest { @Ignore @Test fun clocksWithSameTimeAreEqual() { assertEquals(Clock(15, 37), Clock(15, 37)) } @Ignore @Test fun clocksAMinuteApartAreNotEqual() { assertNotEquals(Clock(15, 36), Clock(15, 37)) } @Ignore @Test fun clocksAnHourApartAreNotEqual() { assertNotEquals(Clock(14, 37), Clock(15, 37)) } @Ignore @Test fun clocksWithHourOverflow() { assertEquals(Clock(10, 37), Clock(34, 37)) } @Ignore @Test fun clocksWithHourOverflowBySeveralDays() { assertEquals(Clock(3, 11), Clock(99, 11)) } @Ignore @Test fun clocksWithNegateHour() { assertEquals(Clock(22, 40), Clock(-2, 40)) } @Ignore @Test fun clocksWithNegativeHourThatWraps() { assertEquals(Clock(17, 3), Clock(-31, 3)) } @Ignore @Test fun clocksWithNegativeHourThatWrapsMultipleTimes() { assertEquals(Clock(13, 49), Clock(-83, 49)) } @Ignore @Test fun clocksWithMinuteOverflow() { assertEquals(Clock(0, 1), Clock(0, 1441)) } @Ignore @Test fun clocksWithMinuteOverflowBySeveralDays() { assertEquals(Clock(2, 2), Clock(2, 4322)) } @Ignore @Test fun clocksWithNegativeMinutes() { assertEquals(Clock(2, 40), Clock(3, -20)) } @Ignore @Test fun clocksWithNegativeMinutesThatWraps() { assertEquals(Clock(4, 10), Clock(5, -1490)) } @Ignore @Test fun clocksWithNegativeMinutesThatWrapsMultipleTimes() { assertEquals(Clock(6, 15), Clock(6, -4305)) } @Ignore @Test fun clocksWithNegativeHoursAndMinutes() { assertEquals(Clock(7, 32), Clock(-12, -268)) } @Ignore @Test fun clocksWithNegativeHoursAndMinutesThatWrap() { assertEquals(Clock(18, 7), Clock(-54, -11513)) } }
0
Kotlin
0
0
fc51245f547e83c80fe28a455d0daa1590c9e06a
2,045
kotlin
MIT License
notification-domain/src/test/kotlin/io/github/v1servicenotification/detail/DetailApiImplTest.kt
team-xquare
443,712,278
false
null
package io.github.v1servicenotification.detail import io.github.v1servicenotification.category.Category import io.github.v1servicenotification.category.exception.CategoryNotFoundException import io.github.v1servicenotification.detail.exception.NotificationDetailNotFoundException import io.github.v1servicenotification.detail.service.DetailApiImpl import io.github.v1servicenotification.stubs.* import org.junit.jupiter.api.Test import java.time.LocalDateTime import java.util.* import org.assertj.core.api.Assertions.* import org.assertj.core.api.AssertionsForClassTypes import org.junit.jupiter.api.assertThrows class DetailApiImplTest { private val detailSpi = InMemoryDetailRepository() private val settingSpi = InMemorySettingRepository() private val categorySpi = InMemoryCategoryRepository() private val fcmSpi = InMemoryFcm() private val userSpi = InMemoryUser() private val detailApi = DetailApiImpl(settingSpi, detailSpi, categorySpi, fcmSpi, userSpi, detailSpi) @Test fun checkNotification() { val userId = UUID.randomUUID() val detailId = UUID.randomUUID() val detail = Detail( id = detailId, title = "Test title", content = "Test Content", sentAt = LocalDateTime.now(), isRead = false, userId = userId, categoryId = UUID.randomUUID() ) detailSpi.save(detail) detailApi.checkNotification(userId, detailId) AssertionsForClassTypes.assertThat(detail.isRead).isEqualTo(true) } @Test fun detailNotFound() { val userId = UUID.randomUUID() val detailId = UUID.randomUUID() assertThrows<NotificationDetailNotFoundException> { detailApi.checkNotification(userId, detailId) } } @Test fun detailNotFoundUser() { val userId = UUID.randomUUID() val detailId = UUID.randomUUID() detailSpi.save( Detail( id = detailId, title = "Test title", content = "Test Content", sentAt = LocalDateTime.now(), isRead = false, userId = UUID.randomUUID(), categoryId = UUID.randomUUID() ) ) assertThrows<NotificationDetailNotFoundException> { detailApi.checkNotification(userId, detailId) } } @Test fun queryNotificationDetail() { val category = Category( UUID.randomUUID(), "Test category", "Test destination", true ) val userId = UUID.randomUUID() detailSpi.save(category) detailSpi.save( Detail(UUID.randomUUID(), "Test title", "Test content", LocalDateTime.now(), true, userId, category.id ) ) assertThat(detailApi.queryNotificationDetail(userId).notifications[0].userId) .isEqualTo(userId) } @Test fun 기본_알림_true_카테고리_전송() { val userId = UUID.randomUUID() userSpi.setUserId(userId) val title = "Test Title" val content = "Test Content" val destination = "/test" val categoryName = "Test Category" val category = Category( id = UUID.randomUUID(), name = categoryName, destination = destination, defaultActivated = true ) categorySpi.saveCategory(category) settingSpi.saveSetting(category, userId, true) detailSpi.save(category) detailApi.postGroupNotification(category.id, title, content) assertThat(detailSpi.findAllByUserId(userId).size).isEqualTo(1) detailSpi.findAllByUserId(userId) .forEach { assertThat(it.title).isEqualTo(title) assertThat(it.content).isEqualTo(content) assertThat(it.destination).isEqualTo(destination) assertThat(it.userId).isEqualTo(userId) assertThat(it.name).isEqualTo(categoryName) } } @Test fun 기본_알림_true_카테고리_비활성_전송() { val userId = UUID.randomUUID() val title = "Test Title" val content = "Test Content" val destination = "/test" val categoryName = "Test Category" val category = Category( id = UUID.randomUUID(), name = categoryName, destination = destination, defaultActivated = true ) categorySpi.saveCategory(category) settingSpi.saveSetting(category, userId, false) detailSpi.save(category) detailApi.postGroupNotification(category.id, title, content) detailSpi.findAllByUserId(userId) .forEach { assertThat(it.title).isEqualTo(title) assertThat(it.content).isEqualTo(content) assertThat(it.destination).isEqualTo(destination) assertThat(it.userId).isNotEqualTo(userId) assertThat(it.name).isEqualTo(categoryName) } } @Test fun 기본_알림_false_카테고리_전송() { val userId = UUID.randomUUID() userSpi.setUserId(userId) val title = "Test Title" val content = "Test Content" val destination = "/test" val categoryName = "Test Category" val category = Category( id = UUID.randomUUID(), name = categoryName, destination = destination, defaultActivated = false ) categorySpi.saveCategory(category) settingSpi.saveSetting(category, userId, true) detailSpi.save(category) detailApi.postGroupNotification(category.id, title, content) assertThat(detailSpi.findAllByUserId(userId).size).isEqualTo(1) detailSpi.findAllByUserId(userId) .forEach { assertThat(it.title).isEqualTo(title) assertThat(it.content).isEqualTo(content) assertThat(it.destination).isEqualTo(destination) assertThat(it.userId).isEqualTo(userId) assertThat(it.name).isEqualTo(categoryName) } } @Test fun groupCategoryNotFound() { val categoryId = UUID.randomUUID() val title = "Test Title" val content = "Test Content" assertThrows<CategoryNotFoundException> { detailApi.postGroupNotification(categoryId, title, content) } } @Test fun postNotification() { val userId = UUID.randomUUID() val title = "Test Title" val content = "Test Content" val destination = "/test" val categoryName = "Test Category" val category = Category( id = UUID.randomUUID(), name = categoryName, destination = destination, defaultActivated = true ) categorySpi.saveCategory(category) detailSpi.save(category) detailApi.postNotification(userId, category.id, title, content) detailSpi.findAllByUserId(userId) .forEach { assertThat(it.title).isEqualTo(title) assertThat(it.content).isEqualTo(content) assertThat(it.destination).isEqualTo(destination) assertThat(it.userId).isEqualTo(userId) assertThat(it.name).isEqualTo(categoryName) } } @Test fun singleCategoryNotFound() { val userId = UUID.randomUUID() val categoryId = UUID.randomUUID() val title = "Test Title" val content = "Test Content" assertThrows<CategoryNotFoundException> { detailApi.postNotification(categoryId, userId, title, content) } } }
2
Kotlin
0
5
466638e6da06f10d961715ff670198cadc330ea6
7,852
v1-service-notification
MIT License
src/commonMain/kotlin/org/tix/integrations/github/rest/issue/Issue.kt
ncipollo
336,920,234
false
{"Kotlin": 601503}
package org.tix.integrations.github.rest.issue import kotlinx.serialization.Serializable import org.tix.integrations.github.rest.label.Label import org.tix.integrations.github.rest.milestone.Milestone import org.tix.integrations.github.rest.user.User import org.tix.integrations.github.state.State @Serializable data class Issue( val id: Long = 0, val nodeId: String = "", val url: String? = null, val repositoryUrl: String? = null, val labelsUrl: String = "", val commentsUrl: String = "", val eventsUrl: String = "", val htmlUrl: String = "", val number: Long = 0, val state: State = State.OPEN, val title: String = "", val body: String? = "", val labels: List<Label> = emptyList(), val assignee: User? = null, val assignees: List<User>? = null, val milestone: Milestone? = null )
8
Kotlin
0
3
02f87c827c1159af055f5afc5481afd45c013703
849
tix-core
MIT License
src/test/kotlin/com/MatteV02/exercises/strings/RemoveFirstLastKtTest.kt
MatteV02
717,394,176
false
{"Kotlin": 55565}
package com.MatteV02.exercises.strings import io.kotest.core.spec.style.FunSpec import io.kotest.datatest.withData import io.kotest.matchers.shouldBe class RemoveFirstLastKtTest : FunSpec({ data class RemoveFirstLastInput(val string: String) context("removeFirstLast") { withData( RemoveFirstLastInput("google"), RemoveFirstLastInput("aenema"), RemoveFirstLastInput("FF"), RemoveFirstLastInput("F") ) { (string) -> run { val returned = removeFirstLast(string) returned shouldBe if (string.length <= 1 || string[0] != string[string.lastIndex]) { string } else { string.substring(1..<string.lastIndex) } } } } })
0
Kotlin
0
1
a246bf86805c321322a74d986b4ac450d597f846
882
kotlin-core
The Unlicense
twitter-tracking-data-evaluation/src/main/kotlin/de/alxgrk/data/plots/TimeSpentPerTweetPlot.kt
alxgrk
292,949,219
false
null
package de.alxgrk.data.plots import de.alxgrk.data.Analyse import de.alxgrk.data.Event import de.alxgrk.data.Session import de.alxgrk.data.UserId import kscience.plotly.Plot import kscience.plotly.Plotly import kscience.plotly.layout import kscience.plotly.models.AxisType import kscience.plotly.models.Box import kscience.plotly.models.BoxMean import kscience.plotly.models.BoxPoints import kotlin.math.absoluteValue typealias Millisecond = Long typealias PreviousEvent = Event? class TimeSpentPerTweetPlot : Chart { override fun Analyse.createPlot(sessionsPerUserId: Map<UserId, List<Session>>): Plot { val millisecondsSpentOnTweets = sessionsPerUserId.entries.flatMap { (_, sessions) -> sessions .map { session -> session.sessionEventsInChronologicalOrder .filter { it.action == "scroll" } .distinctBy { it.estimatedTweetsScrolled } .fold(mutableListOf<Millisecond>() to null as PreviousEvent) { (seconds, prevEvent), event -> prevEvent ?.durationInMilliseconds(event) ?.let { seconds.add(it / (event.estimatedTweetsScrolled!! - prevEvent.estimatedTweetsScrolled!!).absoluteValue) } seconds to event } } .flatMap { it.first } .filter { it < 120000 } // eliminate intervals, that last longer than 2 minutes } val millisecondsSpentOnTweetsOfAllUsers = Box { y.set(millisecondsSpentOnTweets) name = "All Users" marker { color("rgb(199, 174, 214)") } boxpoints = BoxPoints.`false` boxmean = BoxMean.sd } return Plotly.plot { traces(millisecondsSpentOnTweetsOfAllUsers) layout { title = "Milliseconds spent on Tweets (cut off at 2 minute)" xaxis { title = "Users" } yaxis { title = "Time spent on Tweets in Milliseconds" type = AxisType.log autorange = true } showlegend = false } } } }
0
Kotlin
0
1
2be0c0f2622dad12b4aa0bb502bbcb304242e3ea
2,429
twitter-tracking
Apache License 2.0
shared/src/commonMain/kotlin/ui/BirdsUiState.kt
alinbabu2010
677,614,271
false
null
package ui import data.model.BirdInfo data class BirdsUiState( val images: List<BirdInfo> = emptyList(), val selectedCategory : String? = null ){ val categories = images.map { it.category }.toSet() val selectedImages = images.filter { it.category == selectedCategory } }
0
Kotlin
0
0
362d444652cdb7f3e20f7aba18af621d874d323c
291
BirdsApp
Apache License 2.0
Android/feature-dreams-api/src/main/java/ru/iandreyshev/featureDreamsApi/api/IDreamsRepository.kt
iandreyshev
149,519,715
false
{"Markdown": 3, "Batchfile": 2, "Ignore List": 16, "Gradle": 14, "Java Properties": 2, "Shell": 1, "Proguard": 12, "Java": 19, "XML": 67, "Kotlin": 176, "JSON": 5, "YAML": 2, "Microsoft Visual Studio Solution": 1, "C#": 35, "Dockerfile": 1, "SQL": 1}
package ru.iandreyshev.featureDreamsApi.api import io.reactivex.Observable import ru.iandreyshev.featureDreamsApi.domain.Dream import ru.iandreyshev.featureDreamsApi.domain.DreamKey import ru.iandreyshev.featureDreamsApi.domain.LoadDreamResult interface IDreamsRepository { val dreamsObservable: Observable<List<Dream>> fun getDreamObservable(key: DreamKey): Observable<LoadDreamResult> }
0
Kotlin
0
1
5791228f3d7568883058f414a7cbafff561d58d5
399
Dreamland
MIT License
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Microgenetics.kt
DevSrSouza
311,134,756
false
null
package compose.icons.simpleicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.SimpleIcons public val SimpleIcons.Microgenetics: ImageVector get() { if (_microgenetics != null) { return _microgenetics!! } _microgenetics = Builder(name = "Microgenetics", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.008f, 6.0f) curveToRelative(2.595f, 0.0f, 4.31f, 1.263f, 5.583f, 2.726f) lineToRelative(0.248f, 0.293f) curveToRelative(0.082f, 0.101f, 0.164f, 0.2f, 0.242f, 0.3f) curveToRelative(0.434f, 0.569f, 0.809f, 1.146f, 1.17f, 1.674f) curveToRelative(0.24f, 0.356f, 0.465f, 0.693f, 0.689f, 1.008f) lineToRelative(0.227f, 0.32f) curveToRelative(0.074f, 0.105f, 0.148f, 0.211f, 0.24f, 0.31f) curveToRelative(0.928f, 1.171f, 1.889f, 1.9f, 3.283f, 1.991f) curveToRelative(0.195f, -0.845f, 0.301f, -1.721f, 0.301f, -2.621f) reflectiveCurveToRelative(-0.105f, -1.776f, -0.301f, -2.621f) curveToRelative(-1.395f, 0.091f, -2.355f, 0.819f, -3.301f, 1.991f) curveToRelative(-0.18f, -0.246f, -0.357f, -0.51f, -0.555f, -0.796f) curveToRelative(-0.375f, -0.566f, -0.809f, -1.208f, -1.32f, -1.845f) curveToRelative(1.006f, -1.169f, 2.25f, -2.175f, 3.932f, -2.557f) curveTo(20.453f, 2.49f, 16.523f, 0.0f, 12.008f, 0.0f) curveToRelative(-4.5f, 0.0f, -8.44f, 2.49f, -10.49f, 6.173f) curveToRelative(1.681f, 0.384f, 2.923f, 1.388f, 3.931f, 2.556f) curveToRelative(0.086f, 0.09f, 0.168f, 0.18f, 0.249f, 0.285f) lineToRelative(0.237f, 0.3f) curveToRelative(0.479f, 0.615f, 0.914f, 1.245f, 1.305f, 1.845f) lineToRelative(0.555f, 0.826f) lineToRelative(0.24f, 0.329f) curveToRelative(0.074f, 0.104f, 0.165f, 0.21f, 0.239f, 0.315f) curveToRelative(1.051f, 1.439f, 2.115f, 2.43f, 3.75f, 2.43f) curveToRelative(1.65f, 0.0f, 2.701f, -0.99f, 3.765f, -2.43f) lineToRelative(0.375f, 0.555f) curveToRelative(0.451f, 0.66f, 0.932f, 1.38f, 1.455f, 2.055f) curveToRelative(-1.273f, 1.471f, -3.0f, 2.73f, -5.595f, 2.73f) curveToRelative(-2.594f, 0.0f, -4.304f, -1.275f, -5.579f, -2.73f) lineToRelative(-0.24f, -0.3f) lineToRelative(-0.24f, -0.3f) curveToRelative(-0.435f, -0.57f, -0.81f, -1.154f, -1.17f, -1.68f) curveToRelative(-0.239f, -0.36f, -0.465f, -0.69f, -0.689f, -1.006f) lineToRelative(-0.226f, -0.33f) curveToRelative(-0.074f, -0.104f, -0.149f, -0.21f, -0.24f, -0.314f) curveTo(2.664f, 10.2f, 1.703f, 9.465f, 0.309f, 9.375f) curveToRelative(-0.195f, 0.849f, -0.3f, 1.725f, -0.3f, 2.625f) reflectiveCurveToRelative(0.102f, 1.776f, 0.29f, 2.621f) curveToRelative(1.398f, -0.091f, 2.355f, -0.819f, 3.295f, -1.991f) curveToRelative(0.172f, 0.246f, 0.354f, 0.51f, 0.544f, 0.796f) curveToRelative(0.375f, 0.566f, 0.806f, 1.208f, 1.313f, 1.845f) curveToRelative(-1.009f, 1.169f, -2.253f, 2.175f, -3.93f, 2.557f) curveTo(3.566f, 21.51f, 7.494f, 24.0f, 12.008f, 24.0f) curveToRelative(4.515f, 0.0f, 8.441f, -2.49f, 10.49f, -6.173f) curveToRelative(-1.68f, -0.384f, -2.922f, -1.388f, -3.93f, -2.556f) curveToRelative(-0.086f, -0.09f, -0.17f, -0.18f, -0.25f, -0.285f) lineToRelative(-0.236f, -0.3f) curveToRelative(-0.48f, -0.615f, -0.916f, -1.245f, -1.305f, -1.845f) lineTo(16.223f, 12.0f) curveToRelative(-0.074f, -0.111f, -0.154f, -0.225f, -0.23f, -0.33f) curveToRelative(-0.078f, -0.111f, -0.154f, -0.219f, -0.232f, -0.325f) curveToRelative(-1.051f, -1.44f, -2.1f, -2.431f, -3.75f, -2.431f) reflectiveCurveToRelative(-2.699f, 0.99f, -3.75f, 2.431f) lineToRelative(-0.375f, -0.56f) curveToRelative(-0.436f, -0.669f, -0.916f, -1.38f, -1.456f, -2.059f) curveTo(7.703f, 7.263f, 9.383f, 6.0f, 12.008f, 6.0f) } } .build() return _microgenetics!! } private var _microgenetics: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
5,318
compose-icons
MIT License
android/src/main/java/com/amplitude/android/utilities/AndroidStorage.kt
amplitude
448,411,338
false
null
package com.amplitude.android.utilities import android.content.Context import android.content.SharedPreferences import com.amplitude.common.Logger import com.amplitude.core.Amplitude import com.amplitude.core.Configuration import com.amplitude.core.EventCallBack import com.amplitude.core.Storage import com.amplitude.core.StorageProvider import com.amplitude.core.events.BaseEvent import com.amplitude.core.platform.EventPipeline import com.amplitude.core.utilities.Diagnostics import com.amplitude.core.utilities.EventsFileManager import com.amplitude.core.utilities.EventsFileStorage import com.amplitude.core.utilities.FileResponseHandler import com.amplitude.core.utilities.JSONUtil import com.amplitude.core.utilities.ResponseHandler import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import org.json.JSONArray import java.io.File class AndroidStorage( context: Context, val storageKey: String, private val logger: Logger, internal val prefix: String?, private val diagnostics: Diagnostics, ) : Storage, EventsFileStorage { companion object { const val STORAGE_PREFIX = "amplitude-android" } internal val sharedPreferences: SharedPreferences = context.getSharedPreferences("${getPrefix()}-$storageKey", Context.MODE_PRIVATE) private val storageDirectory: File = context.getDir(getDir(), Context.MODE_PRIVATE) private val eventsFile = EventsFileManager(storageDirectory, storageKey, AndroidKVS(sharedPreferences), logger, diagnostics) private val eventCallbacksMap = mutableMapOf<String, EventCallBack>() override suspend fun writeEvent(event: BaseEvent) { eventsFile.storeEvent(JSONUtil.eventToString(event)) event.callback?.let { callback -> event.insertId?.let { eventCallbacksMap.put(it, callback) } } } override suspend fun write( key: Storage.Constants, value: String, ) { sharedPreferences.edit().putString(key.rawVal, value).apply() } override suspend fun remove(key: Storage.Constants) { sharedPreferences.edit().remove(key.rawVal).apply() } override suspend fun rollover() { eventsFile.rollover() } override fun read(key: Storage.Constants): String? { return sharedPreferences.getString(key.rawVal, null) } override fun readEventsContent(): List<Any> { return eventsFile.read() } override fun releaseFile(filePath: String) { eventsFile.release(filePath) } override suspend fun getEventsString(content: Any): String { return eventsFile.getEventString(content as String) } override fun getResponseHandler( eventPipeline: EventPipeline, configuration: Configuration, scope: CoroutineScope, dispatcher: CoroutineDispatcher, ): ResponseHandler { return FileResponseHandler( this, eventPipeline, configuration, scope, dispatcher, logger, ) } override fun removeFile(filePath: String): Boolean { return eventsFile.remove(filePath) } override fun getEventCallback(insertId: String): EventCallBack? { return eventCallbacksMap[insertId] } override fun removeEventCallback(insertId: String) { eventCallbacksMap.remove(insertId) } override fun splitEventFile( filePath: String, events: JSONArray, ) { eventsFile.splitFile(filePath, events) } private fun getPrefix(): String { return prefix ?: STORAGE_PREFIX } private fun getDir(): String { if (prefix != null) { return "$prefix-disk-queue" } return "amplitude-disk-queue" } } class AndroidStorageProvider : StorageProvider { override fun getStorage( amplitude: Amplitude, prefix: String?, ): Storage { val configuration = amplitude.configuration as com.amplitude.android.Configuration return AndroidStorage( configuration.context, configuration.instanceName, configuration.loggerProvider.getLogger(amplitude), prefix, amplitude.diagnostics, ) } }
9
null
8
27
6a8491006c94d4f617cb392e3e82afa32330e451
4,316
Amplitude-Kotlin
MIT License
alchemy-core/src/commonMain/kotlin/com/alchemy/sdk/core/adapter/KHexStringSerializer.kt
tguerin
534,856,094
false
null
package com.alchemy.sdk.core.adapter import com.alchemy.sdk.util.HexString import com.alchemy.sdk.util.HexString.Companion.hexString import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder object KHexStringSerializer : KSerializer<HexString> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("HexString", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): HexString { return decoder.decodeString().hexString } override fun serialize(encoder: Encoder, value: HexString) { encoder.encodeString(value.data) } }
4
Kotlin
0
3
9768a7ab07d9955e3036c32b1f4497527f237b34
842
alchemy-sdk-kotlin
MIT License
app/src/main/java/org/miaowo/miaowo/handler/ChatHandler.kt
luiqn2007
91,064,384
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Java": 4, "XML": 53, "Kotlin": 66}
package org.miaowo.miaowo.handler import android.app.Activity import okhttp3.ResponseBody import org.json.JSONObject import org.miaowo.miaowo.API import org.miaowo.miaowo.data.model.ChatModel import org.miaowo.miaowo.other.ActivityHttpCallback import retrofit2.Call import retrofit2.Response class ChatHandler(activity: Activity) { private val mActivity: Activity = activity var roomId: Int? = null var chatWith: Int? = null var chatModel: ChatModel? = null fun sendMessage(message: String) { if (roomId != null && chatWith != null) { // chat room is existed API.Users.chat(chatWith!!, message, roomId!!).enqueue(object : ActivityHttpCallback<ResponseBody>(mActivity) { override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) { chatModel?.loadRoom(roomId) } }) } if (roomId == null && chatWith != null) { // chat room is not existed API.Users.chat(chatWith!!, message).enqueue(object : ActivityHttpCallback<ResponseBody>(mActivity) { override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) { val obj = JSONObject(response.body()?.string()) chatModel?.loadRooms() chatModel?.loadRoom(obj.getJSONObject("payload").getInt("roomId")) } }) } } fun changeRoom(room: Int?, chatWith: Int?) { if (room != roomId || (room == null && chatWith != this.chatWith)) { this.roomId = room this.chatWith = chatWith chatModel?.loadRoom(roomId) } } }
1
null
1
1
bea81deb7e755a47aa2dd7edd56fc17708231bee
1,725
miaowo
Apache License 2.0
src/uiTest/kotlin/com/github/gbrowser/fixture/IdeaFrame.kt
edgafner
294,787,892
false
null
@file:Suppress("JSUnresolvedReference", "BadExpressionStatementJS") package com.github.gbrowser.fixture import com.intellij.remoterobot.RemoteRobot import com.intellij.remoterobot.data.RemoteComponent import com.intellij.remoterobot.fixtures.* import com.intellij.remoterobot.search.locators.byXpath import com.intellij.remoterobot.stepsProcessing.step import com.intellij.remoterobot.utils.waitFor import java.awt.Point import java.time.Duration fun RemoteRobot.idea(function: IdeaFrame.() -> Unit) { find(IdeaFrame::class.java, timeout = Duration.ofSeconds(10)).apply(function) } @FixtureName("Idea frame") @DefaultXpath("IdeFrameImpl type", "//div[@class='IdeFrameImpl']") class IdeaFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) : CommonContainerFixture(remoteRobot, remoteComponent) { val projectViewTree get() = find<ContainerFixture>(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']")) val projectName get() = step("Get project name") { return@step callJs<String>("component.getProject().getName()") } fun waitForBackgroundTasks(timeout: Duration = Duration.ofMinutes(5)) { step("Wait for background tasks to finish") { waitFor(duration = timeout, interval = Duration.ofSeconds(5)) { // search for the progress bar find<ComponentFixture>(byXpath("//div[@class='InlineProgressPanel']")).findAllText().isEmpty() } } } fun isDumbMode(): Boolean { return callJs(""" const frameHelper = com.intellij.openapi.wm.impl.ProjectFrameHelper.getFrameHelper(component) if (frameHelper) { const project = frameHelper.getProject() project ? com.intellij.openapi.project.DumbService.isDumb(project) : true } else { true } """, true) } // Show GBrowser Tool window, or leave it open if it is already open fun showGBrowserToolWindow() { try { find<GBrowserToolWindowPanel>(byXpath("//div[@myaction.key='toolwindow.stripe.GBrowser']"), Duration.ofSeconds(8)).click() } catch (e: Exception) { find<GBrowserToolWindowPanel>(byXpath("//div[@myaction.key='toolwindow.stripe.GBrowser']"), Duration.ofSeconds(8)).click() } } fun showProjectToolWindow() { try { find<ContainerFixture>(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']")) } catch (e: Exception) { find(ComponentFixture::class.java, byXpath( "//div[contains(@myaction.key, 'title.project') or contains(@myaction.key,'toolwindow.title.project.view title.project select.in.project')]")).click() } } fun dragAndDrop(endPoint: Point) = step("Drag and Drop from to $endPoint") { remoteRobot.runJs(""" const pointEnd = new Point(${endPoint.x}, ${endPoint.y}) try { robot.pressMouse(MouseButton.LEFT_BUTTON) Thread.sleep(500) robot.moveMouse(pointEnd) } finally { Thread.sleep(500) robot.releaseMouse(MouseButton.LEFT_BUTTON) } """) } }
9
null
18
75
743b15830ac0dafbed6d4ce7180d34be9458cf9f
3,193
GBrowser
Apache License 2.0
app/src/main/java/id/android/movie/di/ViewModelFactory.kt
budioktaviyan
273,710,455
false
null
package id.android.movie.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Provider @Suppress("UNCHECKED_CAST") class ViewModelFactory(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T }
0
Kotlin
0
1
86aa19703b10632eb64f5b19859477b92756dd2a
402
movie-compose
MIT License
commons/src/commonMain/kotlin/org/jetbrains/letsPlot/commons/intern/typedGeometry/Transforms.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2021. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.base.typedGeometry object Transforms { private const val RESAMPLING_PRECISION = 0.001 fun <InT, OutT> transform( bbox: Rect<InT>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? = RESAMPLING_PRECISION ): Rect<OutT>? = transform(bbox.toPolygon(), transform, resamplingPrecision).bbox fun <InT, OutT> transform( multiPolygon: MultiPolygon<InT>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? = RESAMPLING_PRECISION ): MultiPolygon<OutT> = MultiPolygon(multiPolygon.map { transform(it, transform, resamplingPrecision) }) fun <InT, OutT> transform( polygon: Polygon<InT>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? ): Polygon<OutT> = Polygon(polygon.map { Ring(transformPoints(it, transform, resamplingPrecision)) }) fun <InT, OutT> transform( lineString: LineString<InT>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? ): LineString<OutT> = LineString(transformPoints(lineString, transform, resamplingPrecision)) fun <InT, OutT> transform( multiLineString: MultiLineString<InT>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? ): MultiLineString<OutT> = MultiLineString(multiLineString.map { transform(it, transform, resamplingPrecision) } ) fun <InT, OutT> transformPoints( path: List<Vec<InT>>, transform: (Vec<InT>) -> Vec<OutT>?, resamplingPrecision: Double? ): List<Vec<OutT>> = when(resamplingPrecision) { null -> path.mapNotNull(transform) else -> VecResampler(transform, resamplingPrecision).resample(path) } }
97
null
51
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
1,908
lets-plot
MIT License
app/src/main/java/com/example/mynote/MainActivity.kt
lmkha
833,570,456
false
{"Kotlin": 66242}
package com.example.mynote import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import com.example.mynote.ui.theme.MyNoteTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { MyNoteTheme { MyNoteApp() } } } }
0
Kotlin
0
0
0de484ed028a9fc6cf0ea9d81b13670f81e0c2fc
571
my-note
MIT License
app/src/main/java/br/com/salosoftwares/mobile/studentsituation/MainActivity.kt
sjbatista
388,260,104
false
null
package br.com.salosoftwares.mobile.studentsituation import android.annotation.SuppressLint import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import kotlinx.android.synthetic.main.activity_main.* import java.lang.Exception class MainActivity : AppCompatActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnCalculate = buttonCalculate val txtResult = result var testNumberOfClicks=0 btnCalculate.setOnClickListener { try { val list1 = listOf(123) val a=list1[6] }catch (e: IndexOutOfBoundsException){ val a=0 } val scoreOne = Integer.parseInt(scoreStudent1.text.toString()) val scoreTwo = Integer.parseInt(scoreStudent2.text.toString()) val media = (scoreOne+scoreTwo)/2 val subsences = Integer.parseInt(numberSubsences.text.toString()) if(subsences<=10 && media>=6){ txtResult.setTextColor(Color.GREEN) result.setText("Aprovado !"+"\n"+ "Foram $subsences faltas e media $media") }else{ txtResult.setTextColor(Color.RED) txtResult.setText("Reprovado !"+"\n"+ "Foram $subsences faltas e media $media") } } } }
0
Kotlin
0
0
dce2cc2ccd44ad550536b51e2fc67b2b0d05c9e5
1,560
StudentSituation
MIT License
src/app/src/main/java/heartRateMonitor/viewmodel/LogDataViewModel.kt
lukasmoers
773,583,661
false
{"Kotlin": 105910}
package heartRateMonitor.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import heartRateMonitor.data.entities.LogData import heartRateMonitor.data.repository.LogDataRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class LogDataViewModel @Inject constructor(private val repository: LogDataRepository) : ViewModel() { fun insertLogData(logData: LogData) { viewModelScope.launch(Dispatchers.IO) { repository.insertLogData(logData) } } suspend fun getAllLogData(): List<LogData> { return withContext(Dispatchers.IO) { repository.getLogData() } } }
0
Kotlin
0
0
bff5e1c9b1a1e2665007f17acb839a8ccb3c2106
829
HeartRateMonitor
MIT License
android/libraries/rib-base/src/main/java/com/badoo/ribs/core/routing/action/CompositeRoutingAction.kt
ramzesrodriguez
196,456,514
true
{"Swift": 402146, "Kotlin": 359452, "Java": 118312, "Shell": 2571, "Ruby": 1955, "Objective-C": 814}
package com.badoo.ribs.core.routing.action import com.badoo.ribs.core.routing.backstack.NodeDescriptor import com.badoo.ribs.core.view.RibView class CompositeRoutingAction< V : RibView>( private vararg val routingActions: RoutingAction<V> ) : RoutingAction<V> { constructor(routingActions: List<RoutingAction<V>>) : this(*routingActions.toTypedArray()) override fun buildNodes(): List<NodeDescriptor> = routingActions.flatMap { it.buildNodes() } override fun execute() { routingActions.forEach { it.execute() } } override fun cleanup() { routingActions.forEach { it.cleanup() } } companion object { fun < V : RibView> composite(vararg routingActions: RoutingAction<V>): RoutingAction<V> = CompositeRoutingAction(*routingActions) } }
0
Swift
0
0
f3361951f587a22e83cb20cdfcac0325efb9b5f5
880
RIBs
Apache License 2.0
compiler/fir/analysis-tests/testData/resolveWithStdlib/callableReferences/companions.kt
JetBrains
3,432,266
false
null
// FILE: JavaClass.java public class JavaClass { public static int bar(String x) { return 0; } public int bar(CharSequence x) { return 0; } } // FILE: main.kt class KotlinClass : JavaClass() { fun baz(x: CharSequence): Int = 1 companion object { fun baz(x: String): Int = 1 } } class KotlinClass2 : JavaClass() { override fun bar(x: CharSequence): Int = 1 companion object { fun bar(x: String): Int = 1 } } fun foo1(x: (String) -> Int) {} fun foo2(x: (KotlinClass, CharSequence) -> Int) {} fun foo3(x: (KotlinClass, CharSequence) -> Int) {} fun foo3(x: (String) -> Int) {} fun main() { foo1(KotlinClass::baz) foo2(KotlinClass::baz) <!AMBIGUITY!>foo3<!>(KotlinClass::baz) foo1(KotlinClass::bar) foo2(KotlinClass::bar) <!AMBIGUITY!>foo3<!>(KotlinClass::bar) foo1(KotlinClass2::bar) <!INAPPLICABLE_CANDIDATE!>foo2<!>(KotlinClass2::bar) foo3(KotlinClass2::bar) }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
953
kotlin
Apache License 2.0
app/src/main/java/com/assignment/plantix/adapter/UsersListAdapter.kt
anjandebnath
500,687,716
false
null
package com.assignment.plantix.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.assignment.plantix.databinding.ItemNamesBinding import com.assignment.plantix.domain.NamesModel class UsersListAdapter(): ListAdapter<NamesModel, UsersListAdapter.ViewHolder>(UsersListDiffCallback()) { override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent) } class ViewHolder private constructor(private val binding: ItemNamesBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: NamesModel) { var nameItem: NamesModel = item nameItem.name = capitalize(nameItem.name) binding.data = nameItem binding.executePendingBindings() } companion object { fun from(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = ItemNamesBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } } fun capitalize(str: String?): String? { return str!!.trim().split("\\s+".toRegex()) .joinToString(" ") { it.capitalize() } } class UsersListDiffCallback : DiffUtil.ItemCallback<NamesModel>() { override fun areItemsTheSame(oldItem: NamesModel, newItem: NamesModel): Boolean { return oldItem.name == newItem.name } override fun areContentsTheSame(oldItem: NamesModel, newItem: NamesModel): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
026b6187a3071e586035ca7c4d1fb54e415ebed8
1,884
Plantix
Apache License 2.0
src/main/kotlin/com/kreait/bots/agile/domain/common/actuator/Metrics.kt
kreait
316,613,408
false
null
package com.kreait.bots.agile.domain.common.actuator import com.fasterxml.jackson.annotation.JsonProperty data class Metrics(val workspaces: String, val members: String, val questions: String, val standups: String) data class ArrayCount( @JsonProperty("_id") val id: String = "", @JsonProperty("count") val count: Int = 0 )
3
Kotlin
2
8
0b56e5b82eda60ed76f31dbdf8f57719b2d30acd
344
olaph-slack-app
MIT License
src/main/kotlin/com/beust/kobalt/app/UpdateKobalt.kt
bmsantos
48,676,304
true
{"Markdown": 3, "Gradle": 4, "XML": 13, "Shell": 3, "Ignore List": 1, "Batchfile": 2, "Text": 1, "YAML": 1, "Kotlin": 165, "INI": 3, "Java Properties": 1, "Maven POM": 1, "Mustache": 1, "Java": 1}
package com.beust.kobalt.app import com.beust.kobalt.misc.GithubApi import com.beust.kobalt.misc.KobaltWrapperProperties import com.beust.kobalt.wrapper.Main import javax.inject.Inject /** * Update Kobalt to the latest version. */ public class UpdateKobalt @Inject constructor(val github: GithubApi, val wrapperProperties: KobaltWrapperProperties) { fun updateKobalt() { val newVersion = github.latestKobaltVersion wrapperProperties.create(newVersion.get()) Main.main(arrayOf()) } /** * Download from the URL found in the kobalt-wrapper.properties regardless of what the latest version is */ fun downloadKobalt() { Main.main(arrayOf("--download", "--no-launch")) } }
0
Kotlin
0
0
3d6f0e4efba3cb83b71bbef352a6bf96af2f7023
734
kobalt
Apache License 2.0
src/main/kotlin/com/pettcare/plugins/Cors.kt
antelukic
810,253,774
false
{"Kotlin": 75020, "Dockerfile": 300}
package com.pettcare.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.cors.routing.* fun Application.configureCors() { install(CORS) { anyHost() allowMethod(HttpMethod.Options) allowMethod(HttpMethod.Post) allowMethod(HttpMethod.Get) allowHeader(HttpHeaders.ContentType) allowHeader(HttpHeaders.AccessControlAllowOrigin) allowHeaders { true } } }
0
Kotlin
0
0
7a7f370d3607511fa4dceacfdfd70dbe55fc4841
460
PettCare-Server
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/performance/PerformanceResourceTiming.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.performance import js.array.ReadonlyArray import js.core.JsLong import web.time.DOMHighResTimeStamp /** * Enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, <SVG>, image, or script. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming) */ sealed external class PerformanceResourceTiming : PerformanceEntry { /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/connectEnd) */ val connectEnd: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/connectStart) */ val connectStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/decodedBodySize) */ val decodedBodySize: JsLong /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/domainLookupEnd) */ val domainLookupEnd: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/domainLookupStart) */ val domainLookupStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/encodedBodySize) */ val encodedBodySize: JsLong /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/fetchStart) */ val fetchStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/initiatorType) */ val initiatorType: String /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/nextHopProtocol) */ val nextHopProtocol: String /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/redirectEnd) */ val redirectEnd: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/redirectStart) */ val redirectStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/requestStart) */ val requestStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseEnd) */ val responseEnd: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStart) */ val responseStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStatus) */ val responseStatus: Short /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/secureConnectionStart) */ val secureConnectionStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/serverTiming) */ val serverTiming: ReadonlyArray<PerformanceServerTiming> /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/transferSize) */ val transferSize: JsLong /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/workerStart) */ val workerStart: DOMHighResTimeStamp /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/toJSON) */ override fun toJSON(): Any }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
3,902
types-kotlin
Apache License 2.0
node-kotlin/src/jsMain/kotlin/node/fs/mkdtemp.kt
karakum-team
393,199,102
false
{"Kotlin": 7083457}
// Automatically generated - do not modify! package node.fs import js.promise.await import node.buffer.Buffer suspend fun mkdtemp( prefix: String, ): String = mkdtempAsync( prefix = prefix, ).await() suspend fun mkdtemp( prefix: String, options: node.buffer.BufferEncoding?, /* ObjectEncodingOptions | BufferEncoding */ ): String = mkdtempAsync( prefix = prefix, options = options, ).await() suspend fun mkdtemp( prefix: String, options: BufferEncodingOption, ): Buffer = mkdtempAsync( prefix = prefix, options = options, ).await()
0
Kotlin
6
26
3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18
622
types-kotlin
Apache License 2.0
core/src/test/kotlin/in/specmatic/core/pattern/ConvertKtTest.kt
znsio
247,710,440
false
null
package `in`.specmatic.core.pattern import org.junit.jupiter.api.Test import `in`.specmatic.shouldMatch import `in`.specmatic.shouldNotMatch internal class ConvertKtTest { @Test fun `nullable number in string should be match either number in string or null`() { val pattern = parsedPattern("""{"number": "(number in string?)"}""") parsedValue("""{"number": "10"}""") shouldMatch pattern parsedValue("""{"number": 10}""") shouldNotMatch pattern } }
46
Kotlin
32
92
b3eb9b6e0f7d42bde35d95b83ea187cd1d6aa3bc
486
specmatic
MIT License
app/src/androidTest/java/com/duckduckgo/app/location/ui/LocationPermissionsViewModelTest.kt
cmonfortep
252,403,423
true
{"Gemfile.lock": 1, "Git Config": 1, "Gradle": 44, "Shell": 6, "JSON": 159, "Markdown": 20, "Java Properties": 4, "Text": 28, "Ignore List": 40, "Batchfile": 1, "EditorConfig": 3, "XML": 779, "Ruby": 2, "Kotlin": 1519, "YAML": 15, "CMake": 1, "Proguard": 1, "HTML": 276, "JavaScript": 239, "C++": 1, "INI": 1, "Java": 8, "Gradle Kotlin DSL": 1, "Makefile": 2, "Perl": 5, "CSS": 11, "JSON with Comments": 2, "Git Attributes": 2, "Swift": 2, "SVG": 9}
/* * Copyright (c) 2020 DuckDuckGo * * 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.duckduckgo.app.location.ui import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import androidx.room.Room import androidx.test.platform.app.InstrumentationRegistry import com.duckduckgo.app.CoroutineTestRule import com.duckduckgo.app.InstantSchedulersRule import com.duckduckgo.app.browser.favicon.FaviconManager import com.duckduckgo.app.global.db.AppDatabase import com.duckduckgo.app.location.GeoLocationPermissions import com.duckduckgo.app.location.data.LocationPermissionEntity import com.duckduckgo.app.location.data.LocationPermissionType import com.duckduckgo.app.location.data.LocationPermissionsDao import com.duckduckgo.app.location.data.LocationPermissionsRepository import com.duckduckgo.app.pixels.AppPixelName import com.duckduckgo.app.runBlocking import com.duckduckgo.app.settings.db.SettingsDataStore import com.duckduckgo.app.statistics.pixels.Pixel import com.nhaarman.mockitokotlin2.atLeastOnce import com.nhaarman.mockitokotlin2.lastValue import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import dagger.Lazy import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.ArgumentCaptor import org.mockito.Mockito import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue @ExperimentalCoroutinesApi class LocationPermissionsViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule val schedulers = InstantSchedulersRule() @ExperimentalCoroutinesApi @get:Rule var coroutineRule = CoroutineTestRule() private lateinit var locationPermissionsDao: LocationPermissionsDao private lateinit var viewModel: LocationPermissionsViewModel private lateinit var db: AppDatabase private val commandCaptor = ArgumentCaptor.forClass(LocationPermissionsViewModel.Command::class.java) private val viewStateCaptor = ArgumentCaptor.forClass(LocationPermissionsViewModel.ViewState::class.java) private val mockCommandObserver: Observer<LocationPermissionsViewModel.Command> = mock() private val mockViewStateObserver: Observer<LocationPermissionsViewModel.ViewState> = mock() private val settingsDataStore: SettingsDataStore = mock() private val mockGeoLocationPermissions: GeoLocationPermissions = mock() private val mockPixel: Pixel = mock() private val mockFaviconManager: FaviconManager = mock() private val lazyFaviconManager = Lazy { mockFaviconManager } @Before fun before() { db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getInstrumentation().targetContext, AppDatabase::class.java) .allowMainThreadQueries() .build() locationPermissionsDao = db.locationPermissionsDao() viewModel = LocationPermissionsViewModel( LocationPermissionsRepository(locationPermissionsDao, lazyFaviconManager, coroutineRule.testDispatcherProvider), mockGeoLocationPermissions, coroutineRule.testDispatcherProvider, settingsDataStore, mockPixel ) viewModel.command.observeForever(mockCommandObserver) viewModel.viewState.observeForever(mockViewStateObserver) } @After fun after() { db.close() viewModel.command.removeObserver(mockCommandObserver) viewModel.viewState.removeObserver(mockViewStateObserver) } @Test fun whenSystemLocationPermissionsAreEnabledAndViewModelIsLoadedThenInitialisedWithProperViewState() { val defaultViewState = LocationPermissionsViewModel.ViewState(false, false, true, emptyList()) viewModel.loadLocationPermissions(true) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertEquals(defaultViewState, viewStateCaptor.value) } @Test fun whenSystemLocationPermissionsAreDisabledAndViewModelIsLoadedThenInitialisedWithProperViewState() { val defaultViewState = LocationPermissionsViewModel.ViewState(false, false, false, emptyList()) viewModel.loadLocationPermissions(false) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertEquals(defaultViewState, viewStateCaptor.value) } @Test fun whenViewModelInitialisedThenViewStateShowsCurrentLocationPermissions() { givenLocationPermission(LocationPermissionType.ALLOW_ONCE, "domain.com") viewModel.loadLocationPermissions(true) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertTrue(viewStateCaptor.value.locationPermissionEntities.size == 1) } @Test fun whenUserDeletesLocationPermissionThenConfirmDeleteCommandIssued() { val locationPermissionEntity = LocationPermissionEntity("domain.com", LocationPermissionType.ALLOW_ONCE) viewModel.onDeleteRequested(locationPermissionEntity) assertCommandIssued<LocationPermissionsViewModel.Command.ConfirmDeleteLocationPermission> { assertEquals(locationPermissionEntity, this.entity) } } @Test fun whenUserDeletesLocationPermissionThenViewStateIsUpdated() = coroutineRule.runBlocking { givenLocationPermission(LocationPermissionType.ALLOW_ONCE, "domain.com") viewModel.loadLocationPermissions(true) val locationPermissionEntity = LocationPermissionEntity("domain.com", LocationPermissionType.ALLOW_ONCE) viewModel.delete(locationPermissionEntity) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertTrue(viewStateCaptor.lastValue.locationPermissionEntities.isEmpty()) } @Test fun whenUserDeletesLocationPermissionThenGeoLocationPermissionDeletesDomain() = coroutineRule.runBlocking { val domain = "domain.com" givenLocationPermission(LocationPermissionType.ALLOW_ONCE, domain) val locationPermissionEntity = LocationPermissionEntity(domain, LocationPermissionType.ALLOW_ONCE) viewModel.delete(locationPermissionEntity) assertNull(locationPermissionsDao.getPermission(domain)) Mockito.verify(mockGeoLocationPermissions).clear(domain) } @Test fun whenUseEditsLocationPermissionThenEditCommandIssued() { val locationPermissionEntity = LocationPermissionEntity("domain.com", LocationPermissionType.ALLOW_ONCE) viewModel.onEditRequested(locationPermissionEntity) assertCommandIssued<LocationPermissionsViewModel.Command.EditLocationPermissions> { assertEquals(locationPermissionEntity, this.entity) } } @Test fun whenUserTogglesLocationPermissionsThenViewStateUpdated() = coroutineRule.runBlocking { viewModel.loadLocationPermissions(true) viewModel.onLocationPermissionToggled(true) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertTrue(viewStateCaptor.value.locationPermissionEnabled) } @Test fun whenUserTogglesLocationPermissionThenUpdateSettingsDataStore() { viewModel.onLocationPermissionToggled(true) Mockito.verify(settingsDataStore).appLocationPermission = true } @Test fun whenUserDisablesLocationPermissionThenAllPermissionsAreCleared() = coroutineRule.runBlocking { viewModel.onLocationPermissionToggled(false) Mockito.verify(mockGeoLocationPermissions).clearAll() } @Test fun whenUserEnablesLocationPermissionThenPermissionsAreNotModified() = coroutineRule.runBlocking { viewModel.onLocationPermissionToggled(true) Mockito.verifyNoMoreInteractions(mockGeoLocationPermissions) } @Test fun whenUserEditsLocationPermissionThenViewStateIsUpdated() = coroutineRule.runBlocking { givenLocationPermission(LocationPermissionType.ALLOW_ONCE, "domain.com") viewModel.loadLocationPermissions(true) viewModel.onSiteLocationPermissionSelected("domain.com", LocationPermissionType.DENY_ALWAYS) verify(mockPixel).fire(AppPixelName.PRECISE_LOCATION_SITE_DIALOG_DENY_ALWAYS) Mockito.verify(mockViewStateObserver, atLeastOnce()).onChanged(viewStateCaptor.capture()) assertTrue(viewStateCaptor.lastValue.locationPermissionEntities.size == 1) val newPermission = viewStateCaptor.lastValue.locationPermissionEntities[0].permission assertTrue(newPermission == LocationPermissionType.DENY_ALWAYS) } @Test fun whenAllowAlwaysPermissionsIsGrantedThenGeoLocationPermissionIsAllowed() = coroutineRule.runBlocking { val domain = "example.com" viewModel.onSiteLocationPermissionSelected(domain, LocationPermissionType.ALLOW_ALWAYS) verify(mockPixel).fire(AppPixelName.PRECISE_LOCATION_SITE_DIALOG_ALLOW_ALWAYS) verify(mockGeoLocationPermissions).allow(domain) assertEquals(locationPermissionsDao.getPermission(domain)!!.permission, LocationPermissionType.ALLOW_ALWAYS) } @Test fun whenAllowOncePermissionsIsGrantedThenGeoLocationPermissionIsClearedAndRemovedFromDb() = coroutineRule.runBlocking { val domain = "example.com" viewModel.onSiteLocationPermissionSelected(domain, LocationPermissionType.ALLOW_ONCE) verify(mockGeoLocationPermissions).clear(domain) assertNull(locationPermissionsDao.getPermission(domain)) } @Test fun whenDenyOncePermissionsIsGrantedThenGeoLocationPermissionIsClearedAndRemovedFromDb() = coroutineRule.runBlocking { val domain = "example.com" viewModel.onSiteLocationPermissionSelected(domain, LocationPermissionType.DENY_ONCE) verify(mockGeoLocationPermissions).clear(domain) assertNull(locationPermissionsDao.getPermission(domain)) } @Test fun whenDenyAlwaysPermissionsIsGrantedThenGeoLocationPermissionIsAllowed() = coroutineRule.runBlocking { val domain = "example.com" viewModel.onSiteLocationPermissionSelected(domain, LocationPermissionType.DENY_ALWAYS) verify(mockGeoLocationPermissions).clear(domain) assertEquals(locationPermissionsDao.getPermission(domain)!!.permission, LocationPermissionType.DENY_ALWAYS) } private fun givenLocationPermission(permission: LocationPermissionType = LocationPermissionType.ALLOW_ONCE, vararg domain: String) { domain.forEach { locationPermissionsDao.insert(LocationPermissionEntity(domain = it, permission = permission)) } } private inline fun <reified T : LocationPermissionsViewModel.Command> assertCommandIssued(instanceAssertions: T.() -> Unit = {}) { Mockito.verify(mockCommandObserver, atLeastOnce()).onChanged(commandCaptor.capture()) val issuedCommand = commandCaptor.allValues.find { it is T } Assert.assertNotNull(issuedCommand) (issuedCommand as T).apply { instanceAssertions() } } }
5
Kotlin
649
3
c03633f7faee192948e68c3897c526c323ee0f2e
11,724
Android
Apache License 2.0
app/src/main/java/me/qcuncle/nowinnews/domain/usecases/news/GetHotArticles.kt
QCuncle
768,718,477
false
{"Kotlin": 313407}
package me.qcuncle.nowinnews.domain.usecases.news import kotlinx.coroutines.flow.Flow import me.qcuncle.nowinnews.domain.model.SiteEntity import me.qcuncle.nowinnews.domain.repository.NewsRepository import javax.inject.Inject class GetHotArticles @Inject constructor( private val newsRepository: NewsRepository ) { operator fun invoke(): Flow<List<SiteEntity>> { return newsRepository.getHotSubscriptionArticles() } }
0
Kotlin
0
7
2105632328876c3c23349470c05a0b7cde226931
439
nowinnews
Apache License 2.0
wear/wear-watchface/src/main/java/androidx/wear/watchface/WatchFaceHostApi.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Handler import android.support.wearable.complications.ComplicationData import androidx.annotation.RestrictTo import androidx.annotation.UiThread import androidx.wear.watchface.complications.SystemDataSources.DataSourceId import androidx.wear.watchface.style.data.UserStyleWireFormat import kotlinx.coroutines.CoroutineScope /** * The API [WatchFaceImpl] uses to communicate with the system. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public interface WatchFaceHostApi { /** Returns the watch face's [Context]. */ public fun getContext(): Context /** Returns the UI thread [Handler]. */ public fun getUiThreadHandler(): Handler /** Returns the UI thread [CoroutineScope]. */ public fun getUiThreadCoroutineScope(): CoroutineScope /** Returns the Worker thread [Handler]. */ public fun getBackgroundThreadHandler(): Handler /** Returns the initial user style stored by the system if there is one or null otherwise. */ public fun getInitialUserStyle(): UserStyleWireFormat? /** * Creates/updates ContentDescriptionLabels for text-to-speech screen readers to make your * [ComplicationSlot]s, buttons, and any other text on your watchface accessible. * * Each label is a region of the screen in absolute pixel coordinates, along with * time-dependent text, the labels are generated from data in [ComplicationSlotsManager], * [Renderer.additionalContentDescriptionLabels], [Renderer.screenBounds] and * [Renderer.getMainClockElementBounds]. * * This is a fairly expensive operation so use it sparingly (e.g. do not call it in * `onDraw()`). */ public fun updateContentDescriptionLabels() /** * Sets the complicationSlots which are active in the watchface. ComplicationSlot data will be * received for these ids. This is to support the pre-android R flow. * * Any ids not in the provided [complicationSlotIds] will be considered inactive. * * If complication data sources and complication data types have been configured, the data * received will match the type chosen by the user. If no complication data source has been * configured, data of type [ComplicationData.TYPE_NOT_CONFIGURED] will be received. * * Ids here are chosen by the watch face to represent each complication and can be any * integer. */ public fun setActiveComplicationSlots(complicationSlotIds: IntArray) /** * For WSL flow, not used in androidx flow. * * Accepts a list of custom complication data sources to attempt to set as the default * complication data source for the specified watch face [ComplicationSlot] id. The custom * complication data sources are tried in turn, if the first doesn't exist then the next one * is tried and so on. If none of them exist then the specified system complication data * source is set as the default instead. * * This will do nothing if the complication data sources are not installed, or if the specified * type is not supported by the complication data sources, or if the user has already selected a * complication data source for the [ComplicationSlot]. * * Note that if the watch face has not yet been granted the `RECEIVE_COMPLICATION_DATA` * permission, it will not be able to receive data from the complication data source unless the * complication data source is from the same app package as the watch face, or the complication * data source lists the watch face as a safe watch face. For system complication data sources * that may be used before your watch face has the permission, use a safe complication data * source instead. * * A complication data source not satisfying the above conditions may still be set as a default * using this method, but the watch face will receive placeholder data of type * [ComplicationData.TYPE_NO_PERMISSION] until the permission has been granted. * * @param complicationSlotId The [ComplicationSlot] id. * @param dataSources data sources The list of non-system complication data sources to try in * order before falling back to * fallbackSystemProvider. This list may be null. * @param fallbackSystemProvider The system complication data source to use if none of the * complication data sources could be used. * @param type The type of complication data that should be provided. Must be one of the types * defined in [ComplicationData]. */ public fun setDefaultComplicationDataSourceWithFallbacks( complicationSlotId: Int, dataSources: List<ComponentName>?, @DataSourceId fallbackSystemProvider: Int, type: Int ) /** Schedules a call to [Renderer.renderInternal] to draw the next frame. */ @UiThread public fun invalidate() /** Intent to launch the complication permission denied activity. */ public fun getComplicationDeniedIntent(): Intent? /** Intent to launch the complication permission rationale activity. */ public fun getComplicationRationaleIntent(): Intent? }
6
null
784
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
5,917
androidx
Apache License 2.0
beslider/src/main/java/app/beslider/com/utils/SliderType.kt
tunaiku
130,059,557
false
null
package app.beslider.com.utils enum class SliderType (val type: Int) { IMAGE(0); fun value(): Int { return type } }
0
Kotlin
2
4
15fd83c1da2793f3e9b08efa83059aa436dcc3e7
136
beslider
Apache License 2.0
src/main/kotlin/nu/peg/mobilion/mobilionapi/config/MobilionProperties.kt
jmesserli
127,414,573
false
null
package nu.peg.mobilion.mobilionapi.config import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(prefix = "mobilion") class MobilionProperties { var value: Double = 0.0 }
0
Kotlin
0
0
2ccae2715a35e61a31d97278c6bbe138f4bac09d
222
mobilion-api
MIT License
java/org/brotli/dec/kt/BrotliInputStream.kt
google
24,993,138
false
null
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ package org.brotli.dec.kt import java.io.IOException import java.io.InputStream /** * [InputStream] decorator that decompresses brotli data. * * Not thread-safe. */ class BrotliInputStream @JvmOverloads constructor(source: InputStream, byteReadBufferSize: Int = DEFAULT_INTERNAL_BUFFER_SIZE) : InputStream() { /** Internal buffer used for efficient byte-by-byte reading. */ private val buffer: ByteArray /** Number of decoded but still unused bytes in internal buffer. */ private var remainingBufferBytes: Int /** Next unused byte offset. */ private var bufferOffset: Int /** Decoder state. */ private val state: State = State() /** * Creates a [InputStream] wrapper that decompresses brotli data. * * For byte-by-byte reading ([.read]) internal buffer with [.DEFAULT_INTERNAL_BUFFER_SIZE] size is * allocated and used. * * Will block the thread until first [BitReader.CAPACITY] bytes of data of source are available. * * @param source underlying data source * @throws IOException in case of corrupted data or source stream problems */ init { require(byteReadBufferSize > 0) { "Bad buffer size:$byteReadBufferSize" } buffer = ByteArray(byteReadBufferSize) remainingBufferBytes = 0 bufferOffset = 0 try { state.input = source initState(state) } catch (ex: BrotliRuntimeException) { throw IOException("Brotli decoder initialization failed", ex) } } fun attachDictionaryChunk(data: ByteArray) { attachDictionaryChunk(state, data) } fun enableEagerOutput() { enableEagerOutput(state) } fun enableLargeWindow() { enableLargeWindow(state) } /** {@inheritDoc} */ @Throws(IOException::class) override fun close() { close(state) } /** {@inheritDoc} */ @Throws(IOException::class) override fun read(): Int { if (bufferOffset >= remainingBufferBytes) { remainingBufferBytes = read(buffer, 0, buffer.size) bufferOffset = 0 if (remainingBufferBytes == END_OF_STREAM_MARKER) { // Both Java and C# return the same value for EOF on single-byte read. return -1 } } return buffer[bufferOffset++].toInt() and 0xFF } /** {@inheritDoc} */ @Throws(IOException::class) override fun read(destBuffer: ByteArray, destOffset: Int, destLen: Int): Int { require(destOffset >= 0) { "Bad offset: $destOffset" } require(destLen >= 0) { "Bad length: $destLen" } require(destOffset + destLen <= destBuffer.size) { "Buffer overflow: " + (destOffset + destLen) + " > " + destBuffer.size } if (destLen == 0) { return 0 } var copyLen = Math.max(remainingBufferBytes - bufferOffset, 0) var offset = destOffset var len = destLen if (copyLen != 0) { copyLen = Math.min(copyLen, len) System.arraycopy(buffer, bufferOffset, destBuffer, offset, copyLen) bufferOffset += copyLen offset += copyLen len -= copyLen if (len == 0) { return copyLen } } return try { state.output = destBuffer state.outputOffset = offset state.outputLength = len state.outputUsed = 0 decompress(state) copyLen += state.outputUsed copyLen = if (copyLen > 0) copyLen else END_OF_STREAM_MARKER copyLen } catch (ex: BrotliRuntimeException) { throw IOException("Brotli stream decoding failed", ex) } } companion object { const val DEFAULT_INTERNAL_BUFFER_SIZE = 256 /** * Value expected by InputStream contract when stream is over. * * In Java it is -1. In C# it is 0 (should be patched during transpilation). */ private const val END_OF_STREAM_MARKER = -1 } }
81
null
1239
13,546
664952333f675eb189b9d8dfefb1d33538cc41f6
3,886
brotli
MIT License
analyzer/src/main/kotlin/managers/Unmanaged.kt
enterstudio
128,504,116
true
{"Kotlin": 489933, "Shell": 1064}
/* * Copyright (c) 2017-2018 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package com.here.ort.analyzer.managers import com.here.ort.analyzer.Main import com.here.ort.analyzer.PackageManager import com.here.ort.analyzer.PackageManagerFactory import com.here.ort.model.AnalyzerResult import com.here.ort.model.Identifier import com.here.ort.model.Project import com.here.ort.model.VcsInfo import java.io.File /** * A fake [PackageManager] for projects that do not use any of the known package managers. */ class Unmanaged : PackageManager() { companion object : PackageManagerFactory<Unmanaged>("", "", emptyList()) { override fun create() = Unmanaged() } override fun command(workingDir: File) = throw NotImplementedError() /** * Returns an [AnalyzerResult] containing a [Project] for the passed [definitionFile], but does not perform any * dependency resolution. * * @param definitionFile The directory to create the project for. */ override fun resolveDependencies(definitionFile: File): AnalyzerResult? { val project = Project( id = Identifier( provider = "Unmanaged", namespace = "", name = definitionFile.name, version = "" ), declaredLicenses = sortedSetOf(), aliases = emptyList(), vcs = VcsInfo.EMPTY, vcsProcessed = processProjectVcs(definitionFile), homepageUrl = "", scopes = sortedSetOf() ) return AnalyzerResult(Main.allowDynamicVersions, project, sortedSetOf()) } }
0
Kotlin
1
0
5b0ea0c292d1abfcef00b02250ae109cdebc6389
2,300
oss-review-toolkit
Apache License 2.0
sample/src/main/java/com/fraggjkee/databindingadapter/User.kt
fraggjkee
266,400,263
false
null
package com.fraggjkee.databindingadapter data class User( val id: Long, val firstName: String, val lastName: String ) val DEMO_USERS: List<User> = listOf( User( 1, "Pyotr", "Tchaikovsky" ), User(2, "Richard", "Wagner"), User( 3, "Johannes", "Brahms" ), User(4, "Franz", "Schubert"), User(5, "Giuseppe", "Verdi") )
0
Kotlin
7
47
de5cff33010925c8949fe14800de70bdba6f2696
463
databinding-recycler-adapter
Apache License 2.0
kotlin-moment/moment-samples/src/main/kotlin/samples/MultipleLocale.kt
PCasafont
284,043,514
true
{"Kotlin": 1197947, "CSS": 29526, "HTML": 6470, "JavaScript": 980}
package samples import moment.moment import react.RBuilder import react.dom.div import react.dom.h2 import react.dom.span fun RBuilder.multipleLocale() { div("app-content") { h2 { +"Multiple Locale Support" } div("app-code-box") { div("app-code") { +"moment().locale()" span { +moment().locale() } } div("app-code") { +"moment().format('LT')" span { +moment().format("LT") } } div("app-code") { +"moment().format('LTS')" span { +moment().format("LTS") } } div("app-code") { +"moment().format('L') " span { +moment().format("L") } } div("app-code") { +"moment().format('l')" span { +moment().format("l") } } div("app-code") { +"moment().format('LL')" span { +moment().format("LL") } } div("app-code") { +"moment().format('ll')" span { +moment().format("ll") } } div("app-code") { +"moment().format('LLL')" span { +moment().format("LLL") } } div("app-code") { +"moment().format('lll')" span { +moment().format("lll") } } div("app-code") { +"moment().format('LLLL')" span { +moment().format("LLLL") } } div("app-code") { +"moment().format('llll')" span { +moment().format("llll") } } } } }
0
null
0
0
29d81bd5e8d27b239550aaa9725d912a9a5768f4
1,738
kotlin-js-wrappers
Apache License 2.0
buildSrc/src/main/kotlin/Configurations.kt
superhyp
416,638,804
true
{"Kotlin": 479483}
@file:Suppress("ClassName", "SpellCheckingInspection", "MemberVisibilityCanBePrivate", "SimpleDateFormat") import java.text.SimpleDateFormat import java.util.Date object appConfig { const val applicationId = "com.hoc.comicapp" const val versionCode = 1 val versionName by lazy { val x = versionCode / 10_000 val y = (versionCode % 10_000) / 100 val z = versionCode % 100 val date = SimpleDateFormat("yyyy-MM-dd").format(Date()) "$x.$y.$z $date" } val supportedLocales = listOf("en") } object versions { const val ktLint = "0.39.0" object sdk { const val buildTools = "30.0.2" const val compile = 30 const val min = 21 const val target = 30 } object kotlin { const val core = "1.4.20" const val coroutines = "1.4.1" } object androidX { const val activity = "1.2.0-beta01" const val appCompat = "1.3.0-alpha02" const val core = "1.5.0-alpha05" const val fragment = "1.3.0-beta01" const val startUp = "1.0.0" object view { const val constraintLayout = "2.1.0-alpha1" const val material = "1.3.0-alpha04" const val recyclerView = "1.2.0-alpha06" } const val navigation = "2.3.1" const val lifecycle = "2.3.0-beta01" const val room = "2.3.0-alpha03" const val work = "2.5.0-beta01" } const val koin = "2.2.0-beta-1" const val moshiKotlin = "1.11.0" const val retrofit = "2.9.0" const val okHttpLoggingInterceptor = "4.10.0-RC1" const val leakCanaryAndroid = "2.5" const val rxRelay = "3.0.0" const val rxBinding = "4.0.0" const val timber = "4.7.1" object reactiveX { const val kotlin = "3.0.1" const val java = "3.0.7" const val android = "3.0.0" } const val glide = "4.11.0" object customView { const val materialSearchView = "1.4.0" const val expandableTextView = "0.1.4" const val materialSpinner = "1.3.1" const val circularProgressIndicator = "1.3.0" const val photoView = "2.3.0" const val swipeRevealLayout = "1.4.1" const val circleImageView = "3.1.0" const val textDrawable = "1.0.1" } object firebase { const val auth = "20.0.1" const val storage = "19.2.0" const val firestore = "22.0.0" const val analytics = "18.0.0" const val crashlytics = "17.3.0" } const val viewBindingDelegate = "1.0.0-alpha02" } object deps { object module { const val baseUi = ":base-ui" const val utils = ":utils" } object kotlin { const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${versions.kotlin.coroutines}" const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${versions.kotlin.coroutines}" const val coroutinesPlayServices = "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:${versions.kotlin.coroutines}" const val coroutinesRx3 = "org.jetbrains.kotlinx:kotlinx-coroutines-rx3:${versions.kotlin.coroutines}" const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${versions.kotlin.core}" } object androidX { const val activity = "androidx.activity:activity-ktx:${versions.androidX.activity}" const val appCompat = "androidx.appcompat:appcompat:${versions.androidX.appCompat}" const val core = "androidx.core:core-ktx:${versions.androidX.core}" const val fragment = "androidx.fragment:fragment-ktx:${versions.androidX.fragment}" const val startUp = "androidx.startup:startup-runtime:${versions.androidX.startUp}" object view { const val constraintLayout = "androidx.constraintlayout:constraintlayout:${versions.androidX.view.constraintLayout}" const val material = "com.google.android.material:material:${versions.androidX.view.material}" const val recyclerView = "androidx.recyclerview:recyclerview:${versions.androidX.view.recyclerView}" } object navigation { const val fragment = "androidx.navigation:navigation-fragment-ktx:${versions.androidX.navigation}" const val ui = "androidx.navigation:navigation-ui-ktx:${versions.androidX.navigation}" } object lifecycle { const val viewModel = "androidx.lifecycle:lifecycle-viewmodel-ktx:${versions.androidX.lifecycle}" const val liveData = "androidx.lifecycle:lifecycle-livedata-ktx:${versions.androidX.lifecycle}" const val reactiveStreams = "androidx.lifecycle:lifecycle-reactivestreams-ktx:${versions.androidX.lifecycle}" const val common = "androidx.lifecycle:lifecycle-common-java8:${versions.androidX.lifecycle}" } object room { const val runtime = "androidx.room:room-runtime:${versions.androidX.room}" const val ktx = "androidx.room:room-ktx:${versions.androidX.room}" const val rxJava3 = "androidx.room:room-rxjava3:${versions.androidX.room}" const val compiler = "androidx.room:room-compiler:${versions.androidX.room}" } object work { const val runtimeKtx = "androidx.work:work-runtime-ktx:${versions.androidX.work}" // Kotlin + coroutines } } object koin { const val androidXViewModel = "org.koin:koin-androidx-viewmodel:${versions.koin}" const val androidXScope = "org.koin:koin-androidx-scope:${versions.koin}" } const val moshiKotlin = "com.squareup.moshi:moshi-kotlin:${versions.moshiKotlin}" object retrofit { const val retrofit = "com.squareup.retrofit2:retrofit:${versions.retrofit}" const val converterMoshi = "com.squareup.retrofit2:converter-moshi:${versions.retrofit}" } const val okHttpLoggingInterceptor = "com.squareup.okhttp3:logging-interceptor:${versions.okHttpLoggingInterceptor}" const val leakCanaryAndroid = "com.squareup.leakcanary:leakcanary-android:${versions.leakCanaryAndroid}" const val rxRelay = "com.jakewharton.rxrelay3:rxrelay:${versions.rxRelay}" object rxBinding { const val platform = "com.jakewharton.rxbinding4:rxbinding:${versions.rxBinding}" const val core = "com.jakewharton.rxbinding4:rxbinding-core:${versions.rxBinding}" const val material = "com.jakewharton.rxbinding4:rxbinding-material:${versions.rxBinding}" const val swipeRefreshLayout = "com.jakewharton.rxbinding4:rxbinding-swiperefreshlayout:${versions.rxBinding}" const val recyclerView = "com.jakewharton.rxbinding4:rxbinding-recyclerview:${versions.rxBinding}" } const val timber = "com.jakewharton.timber:timber:${versions.timber}" object reactiveX { const val kotlin = "io.reactivex.rxjava3:rxkotlin:${versions.reactiveX.kotlin}" const val java = "io.reactivex.rxjava3:rxjava:${versions.reactiveX.java}" const val android = "io.reactivex.rxjava3:rxandroid:${versions.reactiveX.android}" } object glide { const val glide = "com.github.bumptech.glide:glide:${versions.glide}" const val compiler = "com.github.bumptech.glide:compiler:${versions.glide}" const val integration = "com.github.bumptech.glide:okhttp3-integration:${versions.glide}" } object customView { const val materialSearchView = "com.miguelcatalan:materialsearchview:${versions.customView.materialSearchView}" const val expandableTextView = "com.ms-square:expandableTextView:${versions.customView.expandableTextView}" const val materialSpinner = "com.jaredrummler:material-spinner:${versions.customView.materialSpinner}" const val circularProgressIndicator = "com.github.antonKozyriatskyi:CircularProgressIndicator:${versions.customView.circularProgressIndicator}" const val photoView = "com.github.chrisbanes:PhotoView:${versions.customView.photoView}" const val swipeRevealLayout = "com.chauthai.swipereveallayout:swipe-reveal-layout:${versions.customView.swipeRevealLayout}" const val circleImageView = "de.hdodenhof:circleimageview:${versions.customView.circleImageView}" const val textDrawable = "com.amulyakhare:com.amulyakhare.textdrawable:${versions.customView.textDrawable}" } object firebase { const val auth = "com.google.firebase:firebase-auth:${versions.firebase.auth}" const val storage = "com.google.firebase:firebase-storage:${versions.firebase.storage}" const val firestore = "com.google.firebase:firebase-firestore:${versions.firebase.firestore}" const val analytics = "com.google.firebase:firebase-analytics:${versions.firebase.analytics}" const val crashlytics = "com.google.firebase:firebase-crashlytics:${versions.firebase.crashlytics}" } const val listenableFuture = "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava" const val viewBindingDelegate = "com.github.hoc081098:ViewBindingDelegate:${versions.viewBindingDelegate}" }
0
null
0
0
4bec424b0db82cb0649564d9b4fb63b5c69b251d
8,561
ComicReaderApp_MVI_Coroutine_RxKotlin_Jetpack
MIT License
kotlin-antd/src/main/kotlin/antd/select/SelectTypes.kt
xlj44400
248,655,590
true
{"Kotlin": 1516065, "HTML": 1503}
package antd.select import org.w3c.dom.* typealias SelectValue = Any /* RawValue | Array<RawValue> | LabeledValue | Array<LabeledValue> */ typealias RenderDOMFunc = (props: Any) -> HTMLElement typealias RenderNode = Any /* String | ReactElement | (props: Any) -> ReactElement */ typealias Mode = String /* "multiple" | "tags" | "combobox" */ typealias OptionsType = Array<Any /* OptionData | OptionGroupData */> typealias SelectSource = String /* "option" | "selection" | "input" */ typealias Key = Any /* String | Number */ typealias RawValueType = Any /* String | Number */ typealias DefaultValueType = Any /* RawValueType | Array<RawValueType> | LabelValueType | Array<LabelValueType> */ typealias OnClear = () -> Unit typealias OnActiveValue = (active: RawValueType, index: Number, info: dynamic) -> Unit typealias FilterFunc<OptionsType> = (inputValue: String, option: OptionsType) -> Boolean
0
Kotlin
0
0
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
902
kotlin-js-wrappers
Apache License 2.0
search-service/src/test/kotlin/com/egm/stellio/search/web/EntityAccessControlHandlerTests.kt
stellio-hub
257,818,724
false
{"Kotlin": 1680632, "Dockerfile": 2088, "Shell": 1825}
package com.egm.stellio.search.web import arrow.core.left import arrow.core.right import com.egm.stellio.search.authorization.AuthorizationService import com.egm.stellio.search.authorization.EntityAccessRights import com.egm.stellio.search.authorization.EntityAccessRightsService import com.egm.stellio.search.model.* import com.egm.stellio.search.service.EntityPayloadService import com.egm.stellio.shared.config.ApplicationProperties import com.egm.stellio.shared.model.* import com.egm.stellio.shared.util.* import com.egm.stellio.shared.util.AuthContextModel.AUTHORIZATION_CONTEXT import com.egm.stellio.shared.util.AuthContextModel.AUTH_PROP_SAP import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_CAN_READ import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_KIND import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_RIGHT import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_SAP import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_SUBJECT_INFO import com.egm.stellio.shared.util.AuthContextModel.AUTH_TERM_USERNAME import com.egm.stellio.shared.util.AuthContextModel.GROUP_COMPACT_TYPE import com.egm.stellio.shared.util.AuthContextModel.GROUP_TYPE import com.egm.stellio.shared.util.AuthContextModel.SpecificAccessPolicy.AUTH_READ import com.egm.stellio.shared.util.AuthContextModel.USER_COMPACT_TYPE import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_CORE_CONTEXT import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_NAME_PROPERTY import com.egm.stellio.shared.util.MOCK_USER_SUB import com.egm.stellio.shared.util.sub import com.ninjasquad.springmockk.MockkBean import io.mockk.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockJwt import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.reactive.server.WebTestClient import java.net.URI import java.time.Duration @OptIn(ExperimentalCoroutinesApi::class) @ActiveProfiles("test") @WebFluxTest(EntityAccessControlHandler::class) @EnableConfigurationProperties(ApplicationProperties::class) class EntityAccessControlHandlerTests { private val authzHeaderLink = buildContextLinkHeader(AUTHORIZATION_CONTEXT) @Autowired private lateinit var webClient: WebTestClient @MockkBean(relaxed = true) private lateinit var entityAccessRightsService: EntityAccessRightsService @MockkBean(relaxed = true) private lateinit var entityPayloadService: EntityPayloadService @MockkBean(relaxed = true) private lateinit var authorizationService: AuthorizationService private val otherUserSub = "D8916880-D0DC-4469-82F7-F294AEF7292D" private val subjectId = "urn:ngsi-ld:User:0123".toUri() private val entityUri1 = "urn:ngsi-ld:Entity:entityId1".toUri() private val entityUri2 = "urn:ngsi-ld:Entity:entityId2".toUri() @BeforeAll fun configureWebClientDefaults() { webClient = webClient.mutate() .apply(mockJwt().jwt { it.subject(MOCK_USER_SUB) }) .apply(csrf()) .defaultHeaders { it.accept = listOf(JSON_LD_MEDIA_TYPE) it.contentType = JSON_LD_MEDIA_TYPE } .responseTimeout(Duration.ofMinutes(5)) .build() } @Test fun `it should allow an authorized user to give access to an entity`() { val requestPayload = """ { "rCanRead": { "type": "Relationship", "object": "$entityUri1" }, "@context": ["$AUTHORIZATION_CONTEXT", "$NGSILD_CORE_CONTEXT"] } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityAccessRightsService.setRoleOnEntity(any(), any(), any()) } returns Unit.right() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs") .bodyValue(requestPayload) .exchange() .expectStatus().isNoContent coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) entityAccessRightsService.setRoleOnEntity( eq(otherUserSub), eq(entityUri1), eq(AccessRight.R_CAN_READ) ) } } @Test fun `it should allow an authorized user to give access to a set of entities`() { val entityUri3 = "urn:ngsi-ld:Entity:entityId3".toUri() val requestPayload = """ { "rCanRead": [{ "type": "Relationship", "object": "$entityUri1", "datasetId": "$entityUri1" }, { "type": "Relationship", "object": "$entityUri2", "datasetId": "$entityUri2" }], "rCanWrite": { "type": "Relationship", "object": "$entityUri3" }, "@context": ["$AUTHORIZATION_CONTEXT", "$NGSILD_CORE_CONTEXT"] } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityAccessRightsService.setRoleOnEntity(any(), any(), any()) } returns Unit.right() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs") .bodyValue(requestPayload) .exchange() .expectStatus().isNoContent coVerify(exactly = 3) { authorizationService.userCanAdminEntity( match { listOf(entityUri1, entityUri2, entityUri3).contains(it) }, eq(sub) ) } coVerify { entityAccessRightsService.setRoleOnEntity( eq(otherUserSub), eq(entityUri1), eq(AccessRight.R_CAN_READ) ) entityAccessRightsService.setRoleOnEntity( eq(otherUserSub), eq(entityUri2), eq(AccessRight.R_CAN_READ) ) entityAccessRightsService.setRoleOnEntity( eq(otherUserSub), eq(entityUri3), eq(AccessRight.R_CAN_WRITE) ) } } @Test fun `it should only allow to give access to authorized entities`() { val requestPayload = """ { "rCanRead": [{ "type": "Relationship", "object": "$entityUri1", "datasetId": "$entityUri1" }, { "type": "Relationship", "object": "$entityUri2", "datasetId": "$entityUri2" }], "@context": ["$AUTHORIZATION_CONTEXT", "$NGSILD_CORE_CONTEXT"] } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(eq(entityUri1), any()) } returns Unit.right() coEvery { authorizationService.userCanAdminEntity(eq(entityUri2), any()) } returns AccessDeniedException("Access denied").left() coEvery { entityAccessRightsService.setRoleOnEntity(any(), any(), any()) } returns Unit.right() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs") .bodyValue(requestPayload) .exchange() .expectStatus().isEqualTo(HttpStatus.MULTI_STATUS) .expectBody().json( """ { "updated":["https://ontology.eglobalmark.com/authorization#rCanRead"], "notUpdated":[ { "attributeName":"https://ontology.eglobalmark.com/authorization#rCanRead", "reason":"User is not authorized to manage rights on entity urn:ngsi-ld:Entity:entityId2" } ] } """ ) coVerify(exactly = 1) { entityAccessRightsService.setRoleOnEntity( eq(otherUserSub), eq(entityUri1), eq(AccessRight.R_CAN_READ) ) } } @Test fun `it should filter out invalid attributes when adding rights on entities`() { val requestPayload = """ { "invalidRelationshipName": [{ "type": "Relationship", "object": "$entityUri1", "datasetId": "$entityUri1" }], "aProperty": { "type": "Property", "value": "$entityUri2" }, "@context": ["$AUTHORIZATION_CONTEXT", "$NGSILD_CORE_CONTEXT"] } """.trimIndent() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs") .bodyValue(requestPayload) .exchange() .expectStatus().isEqualTo(HttpStatus.MULTI_STATUS) .expectBody().json( """ { "updated":[], "notUpdated":[ { "attributeName":"https://uri.etsi.org/ngsi-ld/default-context/invalidRelationshipName", "reason":"Not a relationship or not an authorized relationship name" }, { "attributeName":"https://uri.etsi.org/ngsi-ld/default-context/aProperty", "reason":"Not a relationship or not an authorized relationship name" } ] } """ ) coVerify { entityAccessRightsService.setRoleOnEntity(any(), any(), any()) wasNot Called } } @Test fun `it should not do anything if authorization context is missing when adding rights on entities`() { val requestPayload = """ { "rCanRead": { "type": "Relationship", "object": "$entityUri1" }, "@context": ["$APIC_COMPOUND_CONTEXT"] } """.trimIndent() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs") .bodyValue(requestPayload) .exchange() .expectStatus().isEqualTo(HttpStatus.MULTI_STATUS) .expectBody().json( """ { "notUpdated":[ { "attributeName":"https://uri.etsi.org/ngsi-ld/default-context/rCanRead", "reason":"Not a relationship or not an authorized relationship name" } ] } """ ) coVerify { entityAccessRightsService.setRoleOnEntity(any(), any(), any()) wasNot Called } } @Test fun `it should allow an authorized user to remove access to an entity`() { coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityAccessRightsService.removeRoleOnEntity(any(), any()) } returns Unit.right() webClient.delete() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs/$entityUri1") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .exchange() .expectStatus().isNoContent coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) entityAccessRightsService.removeRoleOnEntity(eq(otherUserSub), eq(entityUri1)) } } @Test fun `it should not allow an unauthorized user to remove access to an entity`() { coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns AccessDeniedException("Access denied").left() webClient.delete() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs/$entityUri1") .exchange() .expectStatus().isForbidden coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) } } @Test fun `it should return a 404 if the subject has no right on the target entity`() { coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityAccessRightsService.removeRoleOnEntity(any(), any()) } returns ResourceNotFoundException("No right found for $subjectId on $entityUri1").left() webClient.delete() .uri("/ngsi-ld/v1/entityAccessControl/$otherUserSub/attrs/$entityUri1") .exchange() .expectStatus().isNotFound .expectBody().json( """ { "detail": "No right found for urn:ngsi-ld:User:0123 on urn:ngsi-ld:Entity:entityId1", "type": "https://uri.etsi.org/ngsi-ld/errors/ResourceNotFound", "title": "The referred resource has not been found" } """.trimIndent() ) } @Test fun `it should allow an authorized user to set the specific access policy on an entity`() { val requestPayload = """ { "type": "Property", "value": "AUTH_READ" } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.updateSpecificAccessPolicy(any(), any()) } returns Unit.right() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .bodyValue(requestPayload) .exchange() .expectStatus().isNoContent coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) entityPayloadService.updateSpecificAccessPolicy( eq(entityUri1), match { it.getAttributeInstances().size == 1 && it.name == AUTH_PROP_SAP && it.getAttributeInstances()[0] is NgsiLdPropertyInstance && (it.getAttributeInstances()[0] as NgsiLdPropertyInstance).value.toString() == "AUTH_READ" } ) } } @Test fun `it should allow an authorized user to set the specific access policy on an entity with context in payload`() { val requestPayload = """ { "type": "Property", "value": "AUTH_READ", "@context": ["$AUTHORIZATION_CONTEXT"] } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.updateSpecificAccessPolicy(any(), any()) } returns Unit.right() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .bodyValue(requestPayload) .exchange() .expectStatus().isNoContent coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) entityPayloadService.updateSpecificAccessPolicy( eq(entityUri1), match { it.getAttributeInstances().size == 1 && it.name == AUTH_PROP_SAP && it.getAttributeInstances()[0] is NgsiLdPropertyInstance && (it.getAttributeInstances()[0] as NgsiLdPropertyInstance).value.toString() == "AUTH_READ" } ) } } @Test fun `it should not do anything if authz context is missing when setting the specific access policy on an entity`() { val requestPayload = """ { "type": "Property", "value": "AUTH_READ", "@context": ["$APIC_COMPOUND_CONTEXT"] } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.updateSpecificAccessPolicy(any(), any()) } returns Unit.right() val expectedAttr = "https://uri.etsi.org/ngsi-ld/default-context/specificAccessPolicy" webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .bodyValue(requestPayload) .exchange() .expectStatus().isBadRequest .expectBody().json( """ { "detail": "$expectedAttr is not authorized property name", "type":"https://uri.etsi.org/ngsi-ld/errors/BadRequestData", "title":"The request includes input data which does not meet the requirements of the operation" } """.trimIndent() ) } @Test fun `it should return a 400 if the payload to set specific access policy is not correct`() { val requestPayload = """ { "type": "Property", "value": "someValue" } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.updateSpecificAccessPolicy(any(), any()) } returns BadRequestDataException("Bad request").left() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .bodyValue(requestPayload) .exchange() .expectStatus().isBadRequest .expectBody().jsonPath("$.detail", "Bad request") } @Test fun `it should return a 500 if the specific access policy could not be persisted`() { val requestPayload = """ { "type": "Property", "value": "AUTH_READ" } """.trimIndent() coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.updateSpecificAccessPolicy(any(), any()) } throws RuntimeException() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .bodyValue(requestPayload) .exchange() .expectStatus().is5xxServerError } @Test fun `it should not allow an unauthorized user to set the specific access policy on an entity`() { coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns AccessDeniedException("User is not admin of the target entity").left() webClient.post() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .bodyValue("{}") .exchange() .expectStatus().isForbidden } @Test fun `it should allow an authorized user to delete the specific access policy on an entity`() { coEvery { authorizationService.userCanAdminEntity(any(), any()) } returns Unit.right() coEvery { entityPayloadService.removeSpecificAccessPolicy(any()) } returns Unit.right() webClient.delete() .uri("/ngsi-ld/v1/entityAccessControl/$entityUri1/attrs/specificAccessPolicy") .header(HttpHeaders.LINK, buildContextLinkHeader(AUTHORIZATION_CONTEXT)) .exchange() .expectStatus().isNoContent coVerify { authorizationService.userCanAdminEntity(eq(entityUri1), eq(sub)) entityPayloadService.removeSpecificAccessPolicy(eq(entityUri1)) } } @Test fun `get authorized entities should return 200 and the number of results if requested limit is 0`() { coEvery { authorizationService.getAuthorizedEntities(any(), any(), any()) } returns Pair(3, emptyList<JsonLdEntity>()).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/entities?&limit=0&offset=1&count=true") .exchange() .expectStatus().isOk .expectHeader().valueEquals(RESULTS_COUNT_HEADER, "3") .expectBody().json("[]") } @Test fun `get authorized entities should return 200 and empty response if requested offset does not exist`() { coEvery { authorizationService.getAuthorizedEntities(any(), any(), any()) } returns Pair(0, emptyList<JsonLdEntity>()).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/entities?limit=1&offset=9") .exchange() .expectStatus().isOk .expectBody().json("[]") } @Test fun `get authorized entities should return entities I have a right on`() = runTest { coEvery { authorizationService.getAuthorizedEntities(any(), any(), any()) } returns Pair( 2, listOf( createJsonLdEntity( createEntityAccessRight( "urn:ngsi-ld:Beehive:TESTC".toUri(), BEEHIVE_TYPE, AccessRight.R_CAN_READ ) ), createJsonLdEntity( createEntityAccessRight( "urn:ngsi-ld:Beehive:TESTD".toUri(), BEEHIVE_TYPE, AccessRight.R_CAN_ADMIN, AUTH_READ, createSubjectRightInfo(subjectId) ) ) ) ).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/entities?limit=1&offset=1&count=true") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .exchange() .expectStatus().isOk .expectHeader().valueEquals(RESULTS_COUNT_HEADER, "2") .expectBody().json( """ [{ "id": "urn:ngsi-ld:Beehive:TESTC", "type": "$BEEHIVE_TYPE", "$AUTH_TERM_RIGHT": {"type":"Property", "value": "rCanRead"}, "@context": ["${AuthContextModel.AUTHORIZATION_COMPOUND_CONTEXT}"] }, { "id": "urn:ngsi-ld:Beehive:TESTD", "type": "$BEEHIVE_TYPE", "$AUTH_TERM_RIGHT": {"type":"Property", "value": "rCanAdmin"}, "$AUTH_TERM_SAP": {"type":"Property", "value": "$AUTH_READ"}, "$AUTH_TERM_CAN_READ": { "type":"Relationship", "datasetId": "urn:ngsi-ld:Dataset:0123", "object": "$subjectId", "$AUTH_TERM_SUBJECT_INFO": { "type":"Property", "value": {"$AUTH_TERM_KIND": "User", "$AUTH_TERM_USERNAME": "stellio-user"} } }, "@context": ["${AuthContextModel.AUTHORIZATION_COMPOUND_CONTEXT}"] }] """.trimMargin() ) .jsonPath("[0].createdAt").doesNotExist() .jsonPath("[0].modifiedAt").doesNotExist() } @Test fun `get authorized entities should return 400 if attrs parameter is not valid`() { webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/entities?attrs=rcanwrite") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .exchange() .expectStatus().isBadRequest .expectBody() .jsonPath( "$.detail", "The parameter q only accepts as a value one or more of ${AuthContextModel.ALL_IAM_RIGHTS_TERMS}" ) } @Test fun `get authorized entities should return 204 if authentication is not enabled`() { coEvery { authorizationService.getAuthorizedEntities(any(), any(), any()) } returns Pair(-1, emptyList<JsonLdEntity>()).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/entities") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .exchange() .expectStatus().isNoContent } @Test fun `get groups memberships should return 200 and the number of results if requested limit is 0`() { coEvery { authorizationService.getGroupsMemberships(any(), any(), any()) } returns Pair(3, emptyList<JsonLdEntity>()).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/groups?&limit=0&offset=1&count=true") .exchange() .expectStatus().isOk .expectHeader().valueEquals(RESULTS_COUNT_HEADER, "3") .expectBody().json("[]") } @Test fun `get groups memberships should return groups I am member of`() { coEvery { authorizationService.getGroupsMemberships(any(), any(), any()) } returns Pair( 1, listOf( JsonLdEntity( mapOf( "@id" to "urn:ngsi-ld:group:1", "@type" to listOf(GROUP_TYPE), NGSILD_NAME_PROPERTY to JsonLdUtils.buildExpandedProperty("egm") ), listOf(NGSILD_CORE_CONTEXT) ) ) ).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/groups?count=true") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .exchange() .expectStatus().isOk .expectHeader().valueEquals(RESULTS_COUNT_HEADER, "1") .expectBody().json( """ [ { "id": "urn:ngsi-ld:group:1", "type": "$GROUP_COMPACT_TYPE", "name" : {"type":"Property", "value": "egm"}, "@context": ["${AuthContextModel.AUTHORIZATION_COMPOUND_CONTEXT}"] } ] """.trimMargin() ) .jsonPath("[0].createdAt").doesNotExist() .jsonPath("[0].modifiedAt").doesNotExist() } @Test fun `get groups memberships should return groups I am member of with authorization context`() { coEvery { authorizationService.getGroupsMemberships(any(), any(), any()) } returns Pair( 1, listOf( JsonLdEntity( mapOf( "@id" to "urn:ngsi-ld:group:01", "@type" to listOf(GROUP_TYPE), NGSILD_NAME_PROPERTY to JsonLdUtils.buildExpandedProperty("egm"), AuthContextModel.AUTH_REL_IS_MEMBER_OF to JsonLdUtils.buildExpandedProperty("true") ), listOf(AUTHORIZATION_CONTEXT) ) ) ).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/groups?count=true") .header(HttpHeaders.LINK, authzHeaderLink) .exchange() .expectStatus().isOk .expectHeader().valueEquals(RESULTS_COUNT_HEADER, "1") .expectBody().json( """ [ { "id": "urn:ngsi-ld:group:01", "type": "Group", "name": {"type":"Property", "value": "egm"}, "isMemberOf": {"type":"Property", "value": "true"}, "@context": ["$AUTHORIZATION_CONTEXT", "$NGSILD_CORE_CONTEXT"] } ] """.trimMargin() ) .jsonPath("[0].createdAt").doesNotExist() .jsonPath("[0].modifiedAt").doesNotExist() } @Test fun `get groups memberships should return 204 if authentication is not enabled`() { coEvery { authorizationService.getGroupsMemberships(any(), any(), any()) } returns Pair(-1, emptyList<JsonLdEntity>()).right() webClient.get() .uri("/ngsi-ld/v1/entityAccessControl/groups") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .exchange() .expectStatus().isNoContent } private suspend fun createJsonLdEntity( entityAccessRights: EntityAccessRights, context: String = NGSILD_CORE_CONTEXT ): JsonLdEntity { val earSerialized = entityAccessRights.serializeProperties() return JsonLdEntity(earSerialized, listOf(context)) } private fun createEntityAccessRight( id: URI, type: ExpandedTerm, accessRight: AccessRight, specificAccessPolicy: AuthContextModel.SpecificAccessPolicy? = null, rCanReadUsers: List<EntityAccessRights.SubjectRightInfo>? = null ): EntityAccessRights = EntityAccessRights( id = id, types = listOf(type), right = accessRight, specificAccessPolicy = specificAccessPolicy, rCanReadUsers = rCanReadUsers ) private fun createSubjectRightInfo(subjectId: URI): List<EntityAccessRights.SubjectRightInfo> { val subjectInfo = mapOf( AUTH_TERM_KIND to USER_COMPACT_TYPE, AUTH_TERM_USERNAME to "stellio-user" ) return listOf(EntityAccessRights.SubjectRightInfo(subjectId, subjectInfo)) } }
48
Kotlin
9
27
a740e148f22e05c0add8b841fe976dccdb98cf59
31,537
stellio-context-broker
Apache License 2.0
app/src/main/java/com/frogobox/appsdk/news/NewsViewHolder.kt
frogobox
463,917,159
false
null
package com.frogobox.appsdk.news import androidx.recyclerview.widget.RecyclerView import com.frogobox.appsdk.databinding.ItemNewsBinding import com.frogobox.appsdk.model.Article import com.frogobox.sdk.ext.glideLoad import com.frogobox.sdk.ext.startActivityExt /* * Created by faisalamir on 11/04/22 * FrogoSDK * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2022 Frogobox Media Inc. * All rights reserved * */ class NewsViewHolder(private val binding: ItemNewsBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Article) { binding.apply { ivNewsImage.glideLoad(data.urlToImage) tvNewsTitle.text = data.title tvNewsDescription.text = data.description root.setOnClickListener { it.context.startActivityExt<NewsDetailActivity, Article>( "EXTRA_NEWS_DETAIL", data ) } } } }
0
null
5
17
ce491ce972f14e3f97267f01e7768e1f0b7b6766
1,095
frogo-sdk
Apache License 2.0
src/main/kotlin/com/kh/api/KakaoSkillHandler.kt
veluxer62
233,727,474
false
null
package com.kh.api import com.kh.api.request.ReservationParams import com.kh.api.request.SearchTrainParams import com.kh.api.request.SkillPayload import com.kh.api.response.OutPuts import com.kh.api.response.SkillResponse import com.kh.api.response.basicCard.BasicCardTemplate import com.kh.api.response.carousel.CarouselTemplate import com.kh.api.response.simpleText.SimpleTextTemplate import com.kh.deprecatedOccupying.Korail import com.kh.deprecatedOccupying.dto.response.SearchResponse import com.kh.service.AlarmSender import com.kh.service.BackgroundExecutor import com.kh.util.mapTo import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import reactor.core.publisher.Mono @Component class KakaoSkillHandler( private val korail: Korail, private val alarmSender: AlarmSender, private val backgroundExecutor: BackgroundExecutor ) { fun findTrains(req: ServerRequest): Mono<ServerResponse> { return req.bodyToMono(SkillPayload::class.java) .flatMap { val payload = it.action.params .mapTo<SearchTrainParams>() .getSearchParams() korail.search(payload) }.flatMap { require(it is SearchResponse) { it.responseMessage } response(CarouselTemplate.fromResponse(it)) }.onErrorResume { response(BasicCardTemplate.fromThrowable(it)) } } fun reserveTrain(req: ServerRequest): Mono<ServerResponse> { return req.bodyToMono(SkillPayload::class.java) .doOnNext { it.action.params.mapTo<ReservationParams>() } .doOnNext { val ( searchPayload, trainNo, reservationPayload ) = getReservationPayloads(it) backgroundExecutor.reserveTrain( searchPayload.getSearchParams(), trainNo, reservationPayload) } .flatMap { val ( searchPayload, trainNo, reservationPayload ) = getReservationPayloads(it) response(BasicCardTemplate.fromReserveSkillPayload( searchPayload, trainNo, reservationPayload)) }.onErrorResume { response(SimpleTextTemplate.fromThrowable(it) { message -> """ $message 예약 신청을 다시 해주시기 바랍니다. """.trimIndent() }) } } private fun getReservationPayloads(it: SkillPayload): Triple<SearchTrainParams, String, ReservationParams> { val clientExtra = it.action.clientExtra.orEmpty() val searchPayload = clientExtra .mapTo<SearchTrainParams>() val trainNo = clientExtra["train-no"].toString() val reservationPayload = it.action.params .mapTo<ReservationParams>() return Triple(searchPayload, trainNo, reservationPayload) } fun retryTrainReservation(req: ServerRequest): Mono<ServerResponse> { return req.bodyToMono(SkillPayload::class.java) .doOnNext { val ( searchPayload, trainNo, reservationPayload ) = retryReservationPayloads(it) backgroundExecutor.reserveTrain( searchPayload.getSearchParams(), trainNo, reservationPayload) } .flatMap { val ( searchPayload, trainNo, reservationPayload ) = retryReservationPayloads(it) response(BasicCardTemplate.fromReserveSkillPayload( searchPayload, trainNo, reservationPayload)) }.onErrorResume { response(SimpleTextTemplate.fromThrowable(it) { message -> """ $message 예약 신청을 다시 해주시기 바랍니다. """.trimIndent() }) } } private fun retryReservationPayloads(it: SkillPayload): Triple<SearchTrainParams, String, ReservationParams> { val clientExtra = it.action.clientExtra.orEmpty() val searchPayload = clientExtra .mapTo<SearchTrainParams>() val trainNo = clientExtra["train-no"].toString() val reservationPayload = clientExtra.mapTo<ReservationParams>() return Triple(searchPayload, trainNo, reservationPayload) } private fun <T> response(template: T): Mono<ServerResponse> { val body = SkillResponse( version = "2.0", template = OutPuts(listOf(template)) ) return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON_UTF8) .syncBody(body) } }
10
Kotlin
0
1
3bd1ac68b6a6dbf985a58712e067b77413a790c8
5,552
occupying
Apache License 2.0
covpass-sdk/src/test/java/de/rki/covpass/sdk/cert/models/GroupedCertificateListTest.kt
Digitaler-Impfnachweis
376,239,258
false
null
/* * (C) Copyright IBM Deutschland GmbH 2021 * (C) Copyright IBM Corp. 2021 */ package de.rki.covpass.sdk.cert.models import com.ensody.reactivestate.test.CoroutineTest import de.rki.covpass.sdk.cert.BlacklistedEntityException import de.rki.covpass.sdk.cert.QRCoder import io.mockk.every import io.mockk.mockk import java.time.Instant import kotlin.test.* internal class GroupedCertificateListTest : CoroutineTest() { private val qrCoder: QRCoder = mockk(relaxed = true) private val mapper = CertificateListMapper(qrCoder) private val givenName1 = "Hans" private val givenName2 = "Franz" private val givenName3 = "Silke" private val familyName1 = "Mustermann" private val familyName2 = "Neuer" private val familyName3 = "Bauer" private val date1 = "2021-01-01" private val date2 = "2021-02-02" private val date3 = "2021-03-03" private val idComplete1 = "certComplete1" private val idComplete2 = "certComplete2" private val idComplete3 = "certComplete3" private val idIncomplete1 = "certIncomplete1" private val idIncomplete2 = "certIncomplete2" private val idIncomplete3 = "certIncomplete3" private val vaccinationsIncomplete1 = listOf(Vaccination(doseNumber = 1, totalSerialDoses = 2, id = idIncomplete1)) private val vaccinationsComplete1 = listOf(Vaccination(doseNumber = 2, totalSerialDoses = 2, id = idComplete1)) private val vaccinationsIncomplete2 = listOf(Vaccination(doseNumber = 1, totalSerialDoses = 2, id = idIncomplete2)) private val vaccinationsComplete2 = listOf(Vaccination(doseNumber = 2, totalSerialDoses = 2, id = idComplete2)) private val vaccinationsIncomplete3 = listOf(Vaccination(doseNumber = 1, totalSerialDoses = 2, id = idIncomplete3)) private val vaccinationsComplete3 = listOf(Vaccination(doseNumber = 2, totalSerialDoses = 2, id = idComplete3)) private val certIncomplete1 = CovCertificate( name = Name(familyNameTransliterated = familyName1, givenNameTransliterated = givenName1), birthDate = date1, vaccinations = vaccinationsIncomplete1, validUntil = Instant.now() ) private val certComplete1 = CovCertificate( name = Name(familyNameTransliterated = familyName1, givenNameTransliterated = givenName1), birthDate = date1, vaccinations = vaccinationsComplete1, validUntil = Instant.now() ) private val certIncomplete2 = CovCertificate( name = Name(familyNameTransliterated = familyName2, givenNameTransliterated = givenName2), birthDate = date2, vaccinations = vaccinationsIncomplete2, validUntil = Instant.now() ) private val certComplete2 = CovCertificate( name = Name(familyNameTransliterated = familyName2, givenNameTransliterated = givenName2), birthDate = date2, vaccinations = vaccinationsComplete2, validUntil = Instant.now() ) private val certIncomplete3 = CovCertificate( name = Name(familyNameTransliterated = familyName3, givenNameTransliterated = givenName3), birthDate = date3, vaccinations = vaccinationsIncomplete3, validUntil = Instant.now() ) private val certComplete3 = CovCertificate( name = Name(familyNameTransliterated = familyName3, givenNameTransliterated = givenName3), birthDate = date3, vaccinations = vaccinationsComplete3, validUntil = Instant.now() ) @Test fun `Empty CovCertificateList transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList() val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(0, groupedCertificatesList.certificates.size) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `One element CovCertificateList transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList(mutableListOf(certComplete1.toCombinedCertLocal())) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(1, groupedCertificatesList.certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.name.familyNameTransliterated ) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `Three single elements CovCertificateList transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certComplete1.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(3, groupedCertificatesList.certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0] .getMainCertificate().covCertificate.name.familyNameTransliterated ) assertEquals( familyName2, groupedCertificatesList.certificates[1] .getMainCertificate().covCertificate.name.familyNameTransliterated ) assertEquals( familyName3, groupedCertificatesList.certificates[2] .getMainCertificate().covCertificate.name.familyNameTransliterated ) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `Two matching element CovCertificateList transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf(certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal()) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(1, groupedCertificatesList.certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[1].covCertificate.name.familyNameTransliterated ) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `Six matching element CovCertificateList transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(3, groupedCertificatesList.certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[1].covCertificate.name.familyNameTransliterated ) assertEquals( familyName2, groupedCertificatesList.certificates[1].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName2, groupedCertificatesList.certificates[1].certificates[1].covCertificate.name.familyNameTransliterated ) assertEquals( familyName3, groupedCertificatesList.certificates[2].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName3, groupedCertificatesList.certificates[2].certificates[1].covCertificate.name.familyNameTransliterated ) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `Two matching and two single elements transformed to GroupedCertificatesList and backwards`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(3, groupedCertificatesList.certificates.size) assertEquals(1, groupedCertificatesList.certificates[0].certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals(2, groupedCertificatesList.certificates[1].certificates.size) assertEquals( familyName2, groupedCertificatesList.certificates[1].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName2, groupedCertificatesList.certificates[1].certificates[1].covCertificate.name.familyNameTransliterated ) assertEquals(1, groupedCertificatesList.certificates[2].certificates.size) assertEquals( familyName3, groupedCertificatesList.certificates[2].certificates[0].covCertificate.name.familyNameTransliterated ) assertNull(groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList, covCertificateList) } @Test fun `Ensure favoriteId is set to main certificate after transformation`() = runBlockingTest { val testId = GroupedCertificatesId(Name(givenName1), birthDate = "2011-11-11") val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal() ), testId ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals(1, groupedCertificatesList.certificates.size) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.name.familyNameTransliterated ) assertEquals( familyName1, groupedCertificatesList.certificates[0].certificates[1].covCertificate.name.familyNameTransliterated ) assertEquals(testId, groupedCertificatesList.favoriteCertId) val covCertificateList = mapper.toCovCertificateList(groupedCertificatesList) assertEquals(originalList.certificates, covCertificateList.certificates) assertEquals(testId, covCertificateList.favoriteCertId) } @Test fun `getCombinedCertificate on empty list returns null`() { val emptyList = GroupedCertificatesList() assertNull(emptyList.getCombinedCertificate(idComplete1)) } @Test fun `getCombinedCertificate on full list returns correct results`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals( certIncomplete1.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idIncomplete1) ) assertEquals( certComplete1.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idComplete1) ) assertEquals( certIncomplete2.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idIncomplete2) ) assertEquals( certComplete2.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idComplete2) ) assertEquals( certIncomplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idIncomplete3) ) assertEquals( certComplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idComplete3) ) } @Test fun `getCombinedCertificate on half filled list returns correct results`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals( certIncomplete1.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idIncomplete1) ) assertNull(groupedCertificatesList.getCombinedCertificate(idComplete1)) assertNull(groupedCertificatesList.getCombinedCertificate(idIncomplete2)) assertEquals( certComplete2.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idComplete2) ) assertEquals( certIncomplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idIncomplete3) ) assertEquals( certComplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), groupedCertificatesList.getCombinedCertificate(idComplete3) ) } @Test fun `deleteCovCertificate on empty list returns false`() { val emptyList = GroupedCertificatesList() assertFalse(emptyList.deleteCovCertificate(idComplete1)) } @Test fun `deleteCovCertificate with non-existent id returns false`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertFalse(groupedCertificatesList.deleteCovCertificate(idComplete1)) } @Test fun `deleteCovCertificate for all elements results in empty list`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertFalse(groupedCertificatesList.deleteCovCertificate(idIncomplete1)) assertTrue(groupedCertificatesList.deleteCovCertificate(idComplete1)) assertFalse(groupedCertificatesList.deleteCovCertificate(idComplete2)) assertTrue(groupedCertificatesList.deleteCovCertificate(idIncomplete2)) assertFalse(groupedCertificatesList.deleteCovCertificate(idIncomplete3)) assertTrue(groupedCertificatesList.deleteCovCertificate(idComplete3)) assertEquals(GroupedCertificatesList(), groupedCertificatesList) } @Test fun `deleteCovCertificate for some elements results in partial list`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertFalse(groupedCertificatesList.deleteCovCertificate(idIncomplete1)) assertFalse(groupedCertificatesList.deleteCovCertificate(idComplete2)) assertTrue(groupedCertificatesList.deleteCovCertificate(idIncomplete2)) assertEquals(2, groupedCertificatesList.certificates.size) val certificatesIncomplete1 = groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certIncomplete1.name, certIncomplete1.birthDate) ) val certificatesComplete1 = groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certComplete1.name, certComplete1.birthDate) ) assertEquals(certificatesComplete1, certificatesIncomplete1) assertEquals(1, certificatesComplete1?.certificates?.size) assertEquals( certComplete1.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), certificatesComplete1?.certificates?.get(0) ) assertNull( groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certIncomplete2.name, certIncomplete2.birthDate) ) ) assertNull( groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certComplete2.name, certComplete2.birthDate) ) ) val certificatesIncomplete3 = groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certIncomplete3.name, certIncomplete3.birthDate) ) val certificatesComplete3 = groupedCertificatesList.getGroupedCertificates( GroupedCertificatesId(certComplete3.name, certComplete3.birthDate) ) assertEquals(certificatesComplete3, certificatesIncomplete3) assertEquals(2, certificatesComplete3?.certificates?.size) assertEquals( certIncomplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), certificatesComplete3?.certificates?.get(0) ) assertEquals( certComplete3.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Expired), certificatesComplete3?.certificates?.get(1) ) } @Test fun `addNewCertificate to empty list and check favoriteCertId`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf() ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertNull(groupedCertificatesList.favoriteCertId) groupedCertificatesList.addNewCertificate( certIncomplete1.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Valid) ) assertEquals( GroupedCertificatesId(certIncomplete1.name, certIncomplete1.birthDate), groupedCertificatesList.favoriteCertId ) groupedCertificatesList.addNewCertificate( certIncomplete2.toCombinedCertLocal() .toCombinedCovCertificate(CertValidationResult.Valid) ) assertEquals(idIncomplete1, groupedCertificatesList.certificates[0].certificates[0].covCertificate.dgcEntry.id) assertEquals(idIncomplete2, groupedCertificatesList.certificates[1].certificates[0].covCertificate.dgcEntry.id) } @Test fun `getValidCertificates on full list of valid certificates`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals( groupedCertificatesList.certificates.size, groupedCertificatesList.getValidCertificates().size ) } @Test fun `getValidCertificates on full list of invalid certificates`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certIncomplete1.toCombinedCertLocal(), certComplete1.toCombinedCertLocal(), certIncomplete2.toCombinedCertLocal(), certComplete2.toCombinedCertLocal(), certIncomplete3.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) every { qrCoder.decodeCovCert(any()) } throws BlacklistedEntityException() val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals( groupedCertificatesList.certificates.size, groupedCertificatesList.getValidCertificates().size ) } @Test fun `getValidCertificates on one invalid certificate`() = runBlockingTest { val originalList = CovCertificateList( mutableListOf( certComplete1.toCombinedCertLocal("certComplete1"), certComplete2.toCombinedCertLocal(), certComplete3.toCombinedCertLocal() ) ) every { qrCoder.decodeCovCert("certComplete1") } throws BlacklistedEntityException() val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertEquals( groupedCertificatesList.certificates.size, groupedCertificatesList.getValidCertificates().size ) } @Test fun `getValidCertificates on empty list`() = runBlockingTest { val originalList = CovCertificateList(emptyList()) val groupedCertificatesList = mapper.toGroupedCertificatesList(originalList) assertTrue(groupedCertificatesList.getValidCertificates().isEmpty()) } private fun CovCertificate.toCombinedCertLocal(qrContent: String = "") = CombinedCovCertificateLocal(this, qrContent) }
49
null
67
185
7301f1500dab4a686aa40341500667cf4cc54d1e
24,990
covpass-android
Apache License 2.0
lib_lesson_schedule/src/main/java/com/jaygee/lessonschedule/drawer/base/BreakDrawer.kt
kazarf007
607,975,760
false
null
package com.jaygee.lessonschedule.drawer.base import android.graphics.Canvas import com.jaygee.lessonschedule.drawer.base.TableDrawer import com.jaygee.lessonschedule.model.BreakLessonCell /** * create on 24/2/2023 **/ interface BreakDrawer : TableDrawer { /** * @param bl key 第几节课 value : 课间数组 最大size = 2 ,课前 ,课后 */ fun drawBreak( canvas: Canvas?, cells: Map<Pair<Int, Boolean>, Map<Int, List<BreakLessonCell>>> ) /** * 最小高度 */ fun minHeight () : Float }
0
Kotlin
0
3
53944c1183083f4faf3a6f3a296ef5eb6a4c3735
518
LessonSchedulePro
Apache License 2.0
android/src/main/java/com/reactnativeuserinterface/UserInterfaceModule.kt
a-eid
446,807,589
false
null
package com.reactnativeuserinterface import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.Promise import androidx.appcompat.app.AppCompatDelegate import android.os.Handler import android.os.Looper class UserInterfaceModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "UserInterface" } @ReactMethod fun setUserInterface(style: String) { Handler(Looper.getMainLooper()).post { if(style == "light"){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) }else if(style == "dark"){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) }else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) } } } }
0
Kotlin
0
0
b490e960f0b9c21df3c25c092b8dc8fe7d9ad400
995
react-native-user-interface
MIT License
idea/tests/testData/mppCreationOfModulesAndServices/linuxX64/linuxX64.kt
JetBrains
278,369,660
false
null
class X64 actual typealias Shared = X64 fun test() { takeCommon(X64()) }
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
79
intellij-kotlin
Apache License 2.0
app/src/test/java/com/shopapp/ui/custom/CreditCardFormatTextWatcherTest.kt
rubygarage
105,554,295
false
null
package com.shopapp.ui.custom import android.widget.EditText import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class CreditCardFormatTextWatcherTest { @Test fun shouldAddSpacesToText() { val padding = 5 val formatter = CreditCardFormatTextWatcher(padding) val cardNumberText = "4242424242424242" val textView = EditText(RuntimeEnvironment.application.baseContext) textView.setText(cardNumberText) val spans = textView.text.getSpans(0, cardNumberText.length, CreditCardFormatTextWatcher.PaddingRightSpan::class.java) assertEquals(0, spans.size) formatter.formatCardNumber(textView) val formattedSpans = textView.text.getSpans(0, cardNumberText.length, CreditCardFormatTextWatcher.PaddingRightSpan::class.java) assertEquals(3, formattedSpans.size) assertEquals(padding, formattedSpans.first().mPadding) } }
6
Kotlin
100
148
133b0060626a064b437683c3f0182d2bb3066bdb
1,150
shopapp-android
Apache License 2.0
app/src/main/java/com/example/c323_jada_mcdaniel_project1/MainActivity.kt
jadamcda
689,007,966
false
{"Kotlin": 5550}
package com.example.c323_jada_mcdaniel_project1 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { private var canAddOperation = false private var canAddDecimal = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } //I was following a tutorial for most of this and the plugin they used is no longer supported. //I don't know how to work around that issue. val workingTV = findViewById<TextView>(R.id.workingTV) val resultsTV = findViewById<TextView>(R.id.resultsTV) fun allClearAction(view: View) { workingTV.text = "" resultsTV.text = "" } fun equalsAction(view: View) { resultsTV.text = calculateResults() } fun numberAction(view: View){ if(view is Button){ if(view.text == "."){ if(canAddDecimal){ workingTV.append(view.text) canAddDecimal = false } else{ workingTV.append(view.text) canAddOperation = true } } } } fun operationAction(view: View){ if(view is Button){ workingTV.append(view.text) canAddOperation = false canAddDecimal = true } } private fun calculateResults(): String { val digitsOperators = digitsOperators() if(digitsOperators.isEmpty()){ return "" } val timesDivision = timesDivisionCalculate(digitsOperators) if(timesDivision.isEmpty()){ return "" } val result = addSubtractCalculate(timesDivision) return result.toString() } private fun addSubtractCalculate(passedList: MutableList<Any>): Float { var result = passedList[0] as Float for (i in passedList.indices){ if(passedList[i] is Char && i != passedList.lastIndex){ val operator = passedList[i] val nextDigit = passedList[i + 1] as Float if(operator == '+'){ result += nextDigit } if(operator == '-'){ result -= nextDigit } } } return result } private fun timesDivisionCalculate(passedList: MutableList<Any>): MutableList<Any> { var list = passedList while(list.contains('X') || list.contains ('/')){ list = calcTimesDiv(list) } return list } private fun calcTimesDiv(passedList: MutableList<Any>): MutableList<Any> { val newList = mutableListOf<Any>() var restartIndex = passedList.size for(i in passedList.indices){ if(passedList[i] is Char && i != passedList.lastIndex && i < restartIndex){ val operator = passedList[i] val prevDigit = passedList[i - 1] as Float val nextDigit = passedList[i + 1] as Float when(operator){ 'X' -> { newList.add(prevDigit * nextDigit) restartIndex = i + 1 } '/' -> { newList.add(prevDigit / nextDigit) restartIndex = i + 1 } else -> { newList.add(prevDigit) newList.add(operator) } } } if(i > restartIndex){ newList.add(passedList[i]) } } return newList } private fun digitsOperators(): MutableList<Any>{ val list = mutableListOf<Any>() var currentDigit = "" for (character in workingTV.text){ if(character.isDigit() || character == '.'){ currentDigit += character } else{ list.add(currentDigit.toFloat()) currentDigit = "" list.add(character) } } if(currentDigit != ""){ list.add(currentDigit.toFloat()) } return list } }
0
Kotlin
0
0
676504bfb1e7ecd1e9695a60e4a9492479c8d708
4,482
C323_Jada_McDaniel_Project1
Apache License 2.0
crypto/src/main/kotlin/jetbrains/exodus/crypto/streamciphers/ChaChaStreamCipherProvider.kt
JetBrains
19,271,154
false
null
/** * Copyright 2010 - 2019 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.crypto.streamciphers import jetbrains.exodus.crypto.StreamCipher import jetbrains.exodus.crypto.toByteArray import org.bouncycastle.crypto.engines.ChaCha7539Engine import org.bouncycastle.crypto.params.ParametersWithIV const val CHACHA_CIPHER_ID = "jetbrains.exodus.crypto.streamciphers.ChaChaStreamCipherProvider" // ChaCha initialization vector is 12 bytes private const val CHACHA_IV_SIZE = 12 /** * ChaCha stream cipher with 20 rounds. Respects [RFC-7539](https://tools.ietf.org/html/rfc7539 RFC-7539). */ @Suppress("unused") class ChaChaStreamCipherProvider : KeyAwareStreamCipherProvider() { override fun getId() = CHACHA_CIPHER_ID override fun newCipher(): StreamCipher = ChaChaStreamCipher(this) private class ChaChaStreamCipher(provider: ChaChaStreamCipherProvider) : KeyAwareStreamCipher(provider) { private lateinit var engine: ChaCha7539Engine override fun init(key: ByteArray, iv: Long) { this.engine = ChaCha7539Engine().apply { init(true, ParametersWithIV(getKeyParameter(key), iv.toByteArray(CHACHA_IV_SIZE))) } } override fun crypt(b: Byte): Byte { return engine.returnByte(b) } } }
1
null
98
968
d5e06113824493412b1a253474cef4c98b6cb213
1,848
xodus
Apache License 2.0
base/base-common-android/src/main/java/dev/dexsr/klio/android/base/systeminsets/compose/WindowInsetsPadding.kt
flammky
462,795,948
false
{"Kotlin": 5222947}
package dev.dexsr.klio.android.base.systeminsets.compose import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.ui.Modifier fun Modifier.systemNavigationBarsPadding(): Modifier = navigationBarsPadding()
0
Kotlin
6
56
2b8b4affab4306e351cfc8721c15a5bc7ecba908
239
Music-Player
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/TrafficLightGo.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.TrafficLightGo: ImageVector get() { if (_trafficLightGo != null) { return _trafficLightGo!! } _trafficLightGo = Builder(name = "TrafficLightGo", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 12.0f) curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f) reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f) reflectiveCurveToRelative(0.449f, -1.0f, 1.0f, -1.0f) reflectiveCurveToRelative(1.0f, 0.449f, 1.0f, 1.0f) close() moveTo(12.0f, 4.0f) curveToRelative(-0.551f, 0.0f, -1.0f, 0.449f, -1.0f, 1.0f) reflectiveCurveToRelative(0.449f, 1.0f, 1.0f, 1.0f) reflectiveCurveToRelative(1.0f, -0.449f, 1.0f, -1.0f) reflectiveCurveToRelative(-0.449f, -1.0f, -1.0f, -1.0f) close() moveTo(20.0f, 5.0f) verticalLineToRelative(14.0f) curveToRelative(0.0f, 2.757f, -2.243f, 5.0f, -5.0f, 5.0f) horizontalLineToRelative(-6.0f) curveToRelative(-2.757f, 0.0f, -5.0f, -2.243f, -5.0f, -5.0f) lineTo(4.0f, 5.0f) curveTo(4.0f, 2.243f, 6.243f, 0.0f, 9.0f, 0.0f) horizontalLineToRelative(6.0f) curveToRelative(2.757f, 0.0f, 5.0f, 2.243f, 5.0f, 5.0f) close() moveTo(15.0f, 19.0f) curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f) reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f) reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f) reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f) close() moveTo(15.0f, 12.0f) curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f) reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f) reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f) reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f) close() moveTo(15.0f, 5.0f) curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f) reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f) reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f) reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f) close() } } .build() return _trafficLightGo!! } private var _trafficLightGo: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,500
icons
MIT License
src/main/kotlin/com/deanveloper/slak/User.kt
deanveloper
52,887,481
false
null
package com.deanveloper.slak import com.deanveloper.slak.util.Cacher import com.deanveloper.slak.util.ErrorHandler import com.google.gson.JsonObject import java.awt.Color import java.net.URL import java.util.* import javax.imageio.ImageIO /** * Represents a slack user * * @author <NAME> */ class User private constructor( id: String, name: String, deleted: Boolean, color: Color, profile: Profile, timezone: TimeZone, isAdmin: Boolean, isOwner: Boolean, has2FA: Boolean, hasFiles: Boolean ) { val id: String var name: String internal set var deleted: Boolean internal set var color: Color internal set val profile: Profile var timezone: TimeZone internal set var isAdmin: Boolean internal set var isOwner: Boolean internal set var has2FA: Boolean internal set var hasFiles: Boolean internal set init { this.id = id this.name = name this.deleted = deleted this.color = color this.profile = profile this.timezone = timezone this.isAdmin = isAdmin this.isOwner = isOwner this.has2FA = has2FA this.hasFiles = hasFiles UserManager.put(if (name.startsWith('@')) name else "@$name", this) UserManager.put(id, this) } constructor(json: JsonObject) : this( json["id"].asString, json["name"].asString, json["deleted"]?.asBoolean ?: false, Color(Integer.parseInt(json["color"].nullSafe?.asString ?: "0", 16)), Profile(json["profile"].asJsonObject), SimpleTimeZone((json["tz_offset"].nullSafe?.asInt ?: 0) * 1000, json["tz_label"].nullSafe?.asString ?: "null"), json["is_admin"]?.asBoolean ?: false, json["is_owner"]?.asBoolean ?: false, json["has_2fa"]?.asBoolean ?: false, json["has_files"]?.asBoolean ?: false ) companion object UserManager : Cacher<User>() { inline fun start(crossinline cb: () -> Unit): ErrorHandler { return runMethod("users.list", "token" to TOKEN) { for (json in it["members"].asJsonArray) { try { User(json.asJsonObject) } catch (e: Exception) { e.printStackTrace() } } cb() } } protected fun fromJson(json: JsonObject): User { if (json["is_user"]?.asBoolean ?: false) { throw IllegalArgumentException("json does not represent a User") } return User( json["id"].asString, json["name"].asString, json["deleted"]?.asBoolean ?: false, Color(Integer.parseInt(json["color"].nullSafe?.asString ?: "0", 16)), Profile(json["profile"].asJsonObject), SimpleTimeZone((json["tz_offset"].nullSafe?.asInt ?: 0) * 1000, json["tz_label"].nullSafe?.asString ?: "null"), json["is_admin"]?.asBoolean ?: false, json["is_owner"]?.asBoolean ?: false, json["has_2fa"]?.asBoolean ?: false, json["has_files"]?.asBoolean ?: false ) } val list: Set<User> get() = this.values.toSet() } data class Profile(val firstName: String?, val lastName: String?, val realName: String?, val email: String?, val skype: String?, val phone: String?, val imageSmallUrl: String, val imageLargeUrl: String) { val imageSmall by lazy { ImageIO.read(URL(imageSmallUrl)) } val imageLarge by lazy { ImageIO.read(URL(imageLargeUrl)) } constructor(json: JsonObject) : this(json["first_name"].nullSafe?.asString, json["last_name"].nullSafe?.asString, json["real_name"].nullSafe?.asString, json["email"].nullSafe?.asString, json["skype"].nullSafe?.asString, json["phone"].nullSafe?.asString, json["image_32"].asString, json["image_192"].asString) } override fun toString() = "User[$id|@$name]" override fun hashCode() = id.hashCode() override fun equals(other: Any?): Boolean { if (this === other) return true return id == (other as? User)?.id } }
23
Kotlin
0
8
256284d9b8fad4f236d63864d178b51984f12ae8
4,548
SlaK
MIT License
library/src/main/java/cloud/pace/sdk/poikit/utils/OSMKeys.kt
pace
303,641,261
false
null
package cloud.pace.sdk.poikit.utils object OSMKeys { // Keys to interpret values from OSRM. const val OSM_ID = "id" const val OSM_ORIGINAL_ID = "oi" const val OSM_HOUSENUMBER = "hn" const val OSM_STREET = "st" const val OSM_ROAD1 = "r1" const val OSM_ROAD2 = "r2" const val OSM_ROAD3 = "r3" const val OSM_ROAD4 = "r4" const val OSM_POI = "pois" const val OSM_TYPE_NAME = "hw" const val OSM_NAME = "nm" const val OSM_REF = "rf" const val OSM_SPEEDLIMIT = "ms" const val OSM_SPEED_WALK = "walk" const val OSM_SPEEDLIMIT_UNKNOWN = "none" const val OSM_OVERTAKING = "ot" const val OSM_ONEWAY = "ow" const val OSM_LANES = "ln" const val OSM_CONDITIONAL_SPEEDLIMIT = "msc" const val OSM_FALSE = "no" // Gas station const val OSM_GAS_STATION = "gasStation" const val OSM_POI_NAME = "n" const val OSM_BRAND = "b" const val OSM_CURRENCY = "pc" const val OSM_PRICE_FORMAT = "pf" const val OSM_VALID_FROM = "vf" const val OSM_OPENING_HOURS = "oh" const val OSM_PRICE_LIST = "pl" const val OSM_PAYMENT_METHODS = "pm" const val OSM_PACE_CONNECTED_FUELING = "cf" const val OSM_AMENITIES = "am" const val OSM_FOODS = "fd" const val OSM_LOYALTY_PROGRAMS = "lp" const val OSM_POSTAL_SERVICES = "ps" const val OSM_SERVICES = "sv" const val OSM_SHOP_GOODS = "sg" const val OSM_PACE_RESOURCE_NAME_LIST = "prn" const val OSM_PRICE_COMPARISON_OPT_OUT = "po" const val OSM_TYPE = "t" const val OSM_ADDRESS = "a" const val OSM_SPEED_LIMIT = "sl" const val OSM_CAMERA_DIRECTION = "cd" const val OSM_SUBTYPE = "st" const val OSM_TRAFFIC_ENFORCEMENT = "trafficEnforcement" const val OSM_ROAD_HAZARD = "roadHazard" const val OSM_CONSTRUCTION = "construction" const val OSM_TEMPORARY = "tp" }
0
Kotlin
1
5
c459c30690f3c2c480986312a3d837698ce028bc
1,863
cloud-sdk-android
MIT License
waltid-libraries/auth/waltid-ktor-authnz/src/main/kotlin/id/walt/ktorauthnz/methods/config/OidcAuthConfiguration.kt
walt-id
701,058,624
false
{"Kotlin": 3448224, "Vue": 474904, "TypeScript": 129086, "Swift": 40383, "JavaScript": 18819, "Ruby": 15159, "Dockerfile": 13118, "Python": 3114, "Shell": 1783, "Objective-C": 388, "CSS": 345, "C": 104}
package id.walt.ktorauthnz.methods.config import id.walt.ktorauthnz.methods.OIDC import id.walt.ktorauthnz.methods.OIDC.resolveConfiguration import kotlinx.coroutines.runBlocking import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("oidc-config") data class OidcAuthConfiguration( val openIdConfigurationUrl: String? = null, var openIdConfiguration: OIDC.OpenIdConfiguration = OIDC.OpenIdConfiguration.INVALID, val clientId: String, val clientSecret: String, val accountIdentifierClaim: String = "sub", ) : AuthMethodConfiguration { fun check() { require(openIdConfiguration != OIDC.OpenIdConfiguration.INVALID || openIdConfigurationUrl != null) { "Either openIdConfiguration or openIdConfigurationUrl have to be provided!" } } suspend fun init() { check() if (openIdConfiguration == OIDC.OpenIdConfiguration.INVALID) { // TODO: move to cache openIdConfiguration = resolveConfiguration(openIdConfigurationUrl!!) } } init { runBlocking { init() } } override fun authMethod() = OIDC }
20
Kotlin
46
121
48c6b8cfef532e7e837db0bdb39ba64def985568
1,158
waltid-identity
Apache License 2.0
apps/etterlatte-utbetaling/src/test/kotlin/no/nav/etterlatte/utbetaling/common/UtilsTest.kt
navikt
417,041,535
false
{"Kotlin": 5493385, "TypeScript": 1306859, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "Dockerfile": 718, "CSS": 598}
package no.nav.etterlatte.utbetaling.common import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import java.time.Clock import java.time.Instant import java.time.Month import java.time.YearMonth import java.time.ZoneId import java.util.* internal class UtilsTest { @Test fun `skal returnere Tidspunkt-objekt for midnatt i dag for norsk vintertid`() { val statiskKlokke = Clock.fixed(Instant.parse("2022-01-01T21:14:29.4839104Z"), ZoneId.of("Europe/Oslo")) val midnatt = tidspunktMidnattIdag(statiskKlokke) assertEquals("2021-12-31T23:00:00Z", midnatt.instant.toString()) } @Test fun `skal returnere Tidspunkt-objekt for midnatt i dag for norsk sommertid`() { val statiskKlokke = Clock.fixed(Instant.parse("2022-06-01T21:14:29.4839104Z"), ZoneId.of("Europe/Oslo")) val midnatt = tidspunktMidnattIdag(statiskKlokke) assertEquals("2022-05-31T22:00:00Z", midnatt.instant.toString()) } @Test fun `skal returnere foerste dag i maaneden`() { val jan2022 = YearMonth.of(2022, Month.JANUARY) val foersteJanuar2022 = forsteDagIMaaneden(jan2022) assertAll( "skal finne foerste dag i maaneden", { assertEquals(jan2022.year, foersteJanuar2022.year) }, { assertEquals(jan2022.month, foersteJanuar2022.month) }, { assertEquals(1, foersteJanuar2022.dayOfMonth) } ) } @Test fun `skal returnere siste dag i maaneden`() { val jan2022 = YearMonth.of(2022, Month.JANUARY) val sisteDagJanuar = sisteDagIMaaneden(jan2022) val feb2022 = YearMonth.of(2022, Month.FEBRUARY) val sisteDagFebruar = sisteDagIMaaneden(feb2022) val april2022 = YearMonth.of(2022, Month.APRIL) val sisteDagApril = sisteDagIMaaneden(april2022) assertAll( "Skal returnere siste dag i maaneden for januar, februar og april", { assertEquals(jan2022.year, sisteDagJanuar.year) }, { assertEquals(jan2022.month, sisteDagJanuar.month) }, { assertEquals(31, sisteDagJanuar.dayOfMonth) }, { assertEquals(feb2022.year, sisteDagFebruar.year) }, { assertEquals(feb2022.month, sisteDagFebruar.month) }, { assertEquals(28, sisteDagFebruar.dayOfMonth) }, { assertEquals(april2022.year, sisteDagApril.year) }, { assertEquals(april2022.month, sisteDagApril.month) }, { assertEquals(30, sisteDagApril.dayOfMonth) } ) } @Test fun `uuid30 skal ikke inneholde bindestreker`() { val uuid30 = UUID.randomUUID().toUUID30() assertFalse(uuid30.toString().contains("-")) } @Test fun `uuid30 skal besta av uuids foerste 30 tegn med unntak av bindestrekene`() { val uuid = UUID.randomUUID() val uuidUtenBindestrek = uuid.toString().replace("-", "") val uuidUFoerste30Tegn = uuidUtenBindestrek.substring(0, 30) val uuid30 = uuid.toUUID30() assertAll( "uuid30 skal besta av uuids foerste 30 tegn med unntak av bindestrekene", { assertEquals(30, uuid30.value.length) }, { assertEquals(uuidUFoerste30Tegn, uuid30.value) } ) } }
8
Kotlin
0
6
cb2f66b3d6bef0ab72b82ca34a7f2e371ff4269c
3,368
pensjon-etterlatte-saksbehandling
MIT License
2016/main/day_20/Main.kt
Bluesy1
572,214,020
false
{"Kotlin": 94178, "Rust": 3942, "Shell": 999}
package day_20_2016 import java.io.File fun part1(input: List<UIntRange>) { var inputs = input.sortedBy { it.first } var index: UInt = 0u while (index < inputs.maxBy { it.last }.last) { index = inputs[0].last + 1u inputs = inputs.filter { it.last > index } if (index < inputs[0].first) { println(index) break } } } fun part2(input: List<UIntRange>) { input.sortedBy { it.first } .map { it.first to it.last } .fold(emptyList<Pair<UInt, UInt>>()) { ranges, range -> if (ranges.isEmpty() || (ranges.last().second < (range.first - 1u))) { ranges + range } else { ranges.last().let { last -> ranges.dropLast(1) + (last.first to maxOf(range.second, last.second)) } } }.sumOf { it.second - it.first + 1u } .let { print("The number of valid IPs is ${4294967296u - it}") } // too high // 4279991501 // 4206688754 // 102 // 100 wrong (not too high, so close?) } private operator fun UIntRange.component2(): UInt { return last } private operator fun UIntRange.component1(): UInt { return first } fun main(){ val inputFile = File("2016/inputs/Day_20.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines().map { it.split('-')[0].toUInt()..it.split('-')[1].toUInt() }) print("\n----- Part 2 -----\n") part2(inputFile.readLines().map { it.split('-')[0].toUInt()..it.split('-')[1].toUInt() }) }
0
Kotlin
0
0
bf8afb46a67526894f84f572c61bfadd8d1c9f1d
1,556
AdventofCode
MIT License
tools/explorer/src/main/kotlin/net/corda/explorer/formatters/PartyNameFormatter.kt
sighttviewliu
100,442,020
false
null
package net.corda.explorer.formatters import net.corda.core.crypto.commonName import org.bouncycastle.asn1.x500.X500Name object PartyNameFormatter { val short = object : Formatter<X500Name> { override fun format(value: X500Name) = value.commonName } val full = object : Formatter<X500Name> { override fun format(value: X500Name): String = value.toString() } }
4
null
0
1
b76d0368437b0a7e180b443f6243f5bdd6fd446b
395
corda
Apache License 2.0
kukot/src/main/java/com/abohomol/kukot/language/RetrofitLanguageRepository.kt
abohomol
138,405,695
false
null
package com.abohomol.kukot.language import com.abohomol.kukot.network.BaseRepository import com.abohomol.kukot.network.LanguageCode import io.reactivex.Completable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers class RetrofitLanguageRepository( private val languageService: LanguageService, secret: String ) : BaseRepository(secret) { fun getLanguages(): Single<List<UserLanguage>> { return languageService.getLanguages() .doOnSuccess { onResponse(it) } .map { it.languages() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun changeLanguage(language: LanguageCode): Completable { val headers = getHeaders(ENDPOINT, "lang=$language") return languageService.changeLanguage(headers, ENDPOINT, language) .doOnSuccess { onResponse(it) } .toCompletable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } companion object { private const val ENDPOINT = "/v1/user/change-lang" } }
0
Kotlin
2
11
73576cd218506ee8bde52cae65a6a727470c5f0a
1,213
kukot
Apache License 2.0
sdk/cameraz/src/main/java/com/ahahahq/cameraz/core/Camera2Proxy.kt
hello-cqq
601,641,839
false
null
/* * Copyright 2023 AhahahQ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * Version: 1.0 * Date : 2023/2/16 * Author: hey.cqq@gmail.com * * ---------------------Revision History: --------------------- * <author> <data> <version > <desc> * AhahahQ 2023/2/16 1.0 build this module */ package com.ahahahq.cameraz.core import android.annotation.SuppressLint import android.content.Context import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.* import android.hardware.camera2.CameraManager import android.hardware.camera2.params.OutputConfiguration import android.hardware.camera2.params.SessionConfiguration import android.media.ImageReader import android.media.MediaActionSound import android.os.Build import android.os.Handler import android.util.Size import android.view.Surface import android.view.SurfaceHolder import androidx.annotation.RequiresApi import com.ahahahq.cameraz.callback.PictureCallback import com.ahahahq.cameraz.callback.PreviewCallback import com.ahahahq.cameraz.controller.Camera2ControllerCompat import com.ahahahq.cameraz.controller.CompatFactory import com.ahahahq.cameraz.model.* import com.ahahahq.cameraz.util.Camera2ConfigUtil import com.ahahahq.cameraz.util.ImageUtil import com.ahahahq.cameraz.util.Util import com.ahahahq.cameraz.util.CameraLog import java.util.concurrent.BlockingQueue import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingDeque @RequiresApi(Build.VERSION_CODES.P) internal class Camera2Proxy(context: Context, handler: Handler) : CameraProxy(context, handler) { companion object { private const val TAG = "Camera2Proxy" } private val cameraManager: CameraManager by lazy { context.getSystemService(Context.CAMERA_SERVICE) as CameraManager } private var cameraCharacteristics: CameraCharacteristics? = null private var cameraDevice: CameraDevice? = null private var captureSession: CameraCaptureSession? = null private var previewBuilder: CaptureRequest.Builder? = null private val sessionMap: ConcurrentHashMap<String, Camera2Session> = ConcurrentHashMap() private val captureResults: BlockingQueue<CaptureResult?> = LinkedBlockingDeque() private val executor = Executors.newFixedThreadPool(3) private var controller: Camera2ControllerCompat = CompatFactory.getCamera2Controller() private val mediaActionSound: MediaActionSound = MediaActionSound() @SuppressLint("MissingPermission") override fun open(cameraId: String, stateCallback: CameraProxyStateCallback) { var cId = cameraId val cameraIdList = cameraManager.cameraIdList if (cameraIdList.isEmpty()) { throw CameraException(CameraException.ERR_DEVICE, "No cameras in current device!") } val characteristics = cameraManager.getCameraCharacteristics(cId) if (!Camera2ConfigUtil.isHardwareLevelSupported(characteristics, CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)) { throw CameraException( CameraException.ERR_DEVICE, "Current device level not support camera2 #INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY when cameraId = $cId." ) } if ((cameraDevice != null) && (cameraDevice!!.id == cId)) { CameraLog.i(TAG, "camera #$cId has opened.") return } cameraStateCallback = stateCallback cameraManager.openCamera(cId, StateCallback(), handler) } override fun getId(): String { return cameraDevice!!.id } override fun setState(state: Int) { CameraLog.i(TAG, "setState pre: $previewState current: $state") when (state) { STATE_DESTROY -> stopPreview() STATE_PREVIEWING -> { if (captureSession == null) { CameraLog.e(TAG, "current session has not created, please execute preview first!") return } if (previewState != STATE_PREVIEWING) { requestPreview() } } STATE_STOP -> { if (previewState == STATE_PREVIEWING) { previewState = STATE_STOP captureSession?.stopRepeating() } } STATE_PICTURE -> { previewState = STATE_PICTURE } } } override fun setParams(params: CameraParams) { val characteristics = cameraCharacteristics params.isCamera2AutoReadImage?.let { controller.params.isCamera2AutoReadImage = it } if (characteristics != null) { params.zoomRatio?.let { controller.setZoom(characteristics, it) } params.rotation?.let { controller.params.rotation = it } var previewSize = Size(params.previewSize.width, params.previewSize.height) if ((previewSize.width > 0) && (previewSize.height > 0)) { controller.params.previewSize = Camera2ConfigUtil.getBestCameraResolution( cameraCharacteristics!!, ImageFormat.YUV_420_888, Util.isRightAngle(controller.params.rotation!!), previewSize, false ) } requestPreview() } } override fun getParams(): CameraParams { return controller.params.clone() } private fun initParams() { controller.initParams(cameraCharacteristics!!) controller.params.apply { rotation = Camera2ConfigUtil.getRotationFromDisplayToCamera(context, cameraCharacteristics!!) previewSize = Camera2ConfigUtil.getBestFullScreenCameraResolution( context, cameraCharacteristics!!, ImageFormat.YUV_420_888, Util.isRightAngle(rotation!!) ) pictureSize = Size(previewSize.width, previewSize.height) } } private fun stopPreview() { if (previewState == STATE_DESTROY) { CameraLog.w(TAG, "preview has already destroyed") return } captureSession?.stopRepeating() captureSession?.close() previewState = STATE_DESTROY captureSession = null } @Synchronized override fun picture(previewId: String, callback: PictureCallback) { cameraDevice?.let { if (previewState != STATE_DESTROY && previewState != STATE_PICTURE) { CameraLog.i(TAG, "picture") val captureBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, controller.getFocusMode()) captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, controller.params.rotation) captureBuilder.set(CaptureRequest.JPEG_QUALITY, 100.toByte()) sessionMap[previewId] ?: throw RuntimeException("current id is not in previewing!") val imageReader = sessionMap[previewId]!!.imageReader val listener = sessionMap[previewId]!!.imageReaderListener sessionMap[previewId]!!.viewSurface?.let { it1 -> captureBuilder.addTarget(it1) } imageReader?.surface?.let { it1 -> captureBuilder.addTarget(it1) } val captureRequest = captureBuilder.build() captureSession?.let { captureSession?.stopRepeating() it.captureSingleRequest(captureRequest, executor, object : CameraCaptureSession.CaptureCallback() { override fun onCaptureStarted(session: CameraCaptureSession, request: CaptureRequest, timestamp: Long, frameNumber: Long) { super.onCaptureStarted(session, request, timestamp, frameNumber) CameraLog.d(TAG, "onCaptureStarted") listener?.pictureCallback = callback handler.post { mediaActionSound.play(MediaActionSound.SHUTTER_CLICK) } } override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) { CameraLog.d(TAG, "onCaptureCompleted") captureResults.put(result) setState(STATE_PREVIEWING) } override fun onCaptureFailed(session: CameraCaptureSession, request: CaptureRequest, failure: CaptureFailure) { super.onCaptureFailed(session, request, failure) CameraLog.d(TAG, "onCaptureFailed") captureResults.put(null) setState(STATE_PREVIEWING) } }) } setState(STATE_PICTURE) } } } override fun close() { CameraLog.i(TAG, "close") if (cameraDevice == null) { return } for ((_, value) in sessionMap.entries) { value.release() } sessionMap.clear() stopPreview() cameraDevice?.close() cameraDevice = null } @RequiresApi(Build.VERSION_CODES.P) override fun preview(preview: Preview) { val previewList = arrayListOf<Preview>() previewList.add(preview) preview(previewList) } override fun preview(previewList: List<Preview>) { cameraDevice?.let { if (previewState == STATE_PREVIEWING) { return } previewBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) val outputs = mutableListOf<OutputConfiguration>() for (preview in previewList) { val camera2Session = Camera2Session() val surfaceList = mutableListOf<Surface>() val imageReader = createImageReader(ImageFormat.YUV_420_888, controller.params.previewSize) val listener = InnerImageAvailableListener() listener.previewCallback = preview.callback imageReader.setOnImageAvailableListener(listener, handler) val imageSurface = imageReader.surface surfaceList.add(imageSurface) camera2Session.imageReader = imageReader camera2Session.imageReaderListener = listener val viewSurface = when (preview.surface) { is SurfaceHolder -> preview.surface.surface is SurfaceTexture -> Surface(preview.surface) else -> throw CameraException(CameraException.ERR_ARG, "T must SurfaceHolder or SurfaceTexture!") } surfaceList.add(viewSurface) camera2Session.viewSurface = viewSurface for (surface in surfaceList) { val outputConfiguration = OutputConfiguration(surface) if (preview.physicalId != null) { outputConfiguration.setPhysicalCameraId(preview.physicalId) } outputs.add(outputConfiguration) previewBuilder?.addTarget(surface) } sessionMap[preview.id] = camera2Session } preview(outputs) } } private fun createImageReader(imageFormat: Int, size: Size): ImageReader { val streamConfigurationMap = cameraCharacteristics!![CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP] return if (streamConfigurationMap?.isOutputSupportedFor(imageFormat) == true) { ImageReader.newInstance(size.width, size.height, imageFormat, 2) } else { throw CameraException(CameraException.ERR_RUNTIME, "Current device doesn't support YUV_420_888!") } } private fun preview(outputs: MutableList<OutputConfiguration>) { val callback = object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { CameraLog.d(TAG, "onConfigured") captureSession = session requestPreview() } override fun onConfigureFailed(session: CameraCaptureSession) { session.close() previewState = STATE_DESTROY captureSession = null } } cameraDevice!!.createCaptureSession( SessionConfiguration( SessionConfiguration.SESSION_REGULAR, outputs, executor, callback ) ) } private fun requestPreview() { previewBuilder?.let { previewBuilder?.set(CaptureRequest.JPEG_ORIENTATION, controller.params.rotation) val supportedFocus = cameraCharacteristics!!.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE) if ((supportedFocus != null) && (supportedFocus > 0)) { previewBuilder?.set(CaptureRequest.CONTROL_AF_MODE, controller.getFocusMode()) } controller.applyZoom(cameraCharacteristics!!, previewBuilder!!) val previewRequest = previewBuilder?.build() val session = captureSession if ((previewRequest != null) && (session != null)) { previewState = STATE_PREVIEWING session.setRepeatingRequest(previewRequest, null, handler) } } } private inner class Camera2Session { var imageReader: ImageReader? = null var imageReaderListener: InnerImageAvailableListener? = null var viewSurface: Surface? = null fun release() { imageReader?.close() imageReaderListener = null imageReader = null } } private inner class StateCallback : CameraDevice.StateCallback() { @RequiresApi(Build.VERSION_CODES.P) override fun onOpened(camera: CameraDevice) { cameraDevice = camera cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraDevice!!.id) initParams() cameraStateCallback?.onOpened(this@Camera2Proxy) } override fun onDisconnected(camera: CameraDevice) { cameraStateCallback?.onDisconnected() } override fun onError(camera: CameraDevice, error: Int) { cameraStateCallback?.onError(error) } override fun onClosed(camera: CameraDevice) { cameraStateCallback?.onClosed() } } private inner class InnerImageAvailableListener : ImageReader.OnImageAvailableListener { var previewCallback: PreviewCallback? = null var pictureCallback: PictureCallback? = null override fun onImageAvailable(reader: ImageReader) { val isAutoRead = controller.params.isCamera2AutoReadImage if (isAutoRead != false) { val image = reader.acquireLatestImage() image?.let { val size = Size(it.width, it.height) var format = it.format val data: ByteArray? = try { when (format) { ImageFormat.JPEG -> { CameraLog.d(TAG, "onImageAvailable JPEG") val byteBuffer = image.planes[0].buffer val d = ByteArray(byteBuffer.remaining()) byteBuffer.get(d) d } ImageFormat.YUV_420_888 -> { format = ImageFormat.NV21 ImageUtil.getDataFromYUVImage(image, ImageUtil.COLOR_FORMAT_NV21) } else -> null } } catch (e: Exception) { CameraLog.e(TAG, "onImageAvailable transcoding failed!") null } finally { try { it.close() } catch (e: Exception) { CameraLog.w(TAG, "onImageAvailable image close exception. ${e.message}") } } if (previewState == STATE_PICTURE) { if (pictureCallback != null) { pictureCallback?.onPictureTaken(data, size, format) pictureCallback = null } else { } } else { previewCallback?.onPreviewFrame(data, size, format) } } } else { if (previewState == STATE_PICTURE) { if (pictureCallback != null) { pictureCallback?.onPictureTaken(reader) pictureCallback = null } } else { previewCallback?.onPreviewFrame(reader) } } } } }
0
Kotlin
0
2
d2e6f5ec33868afedab877d617505741c0986036
18,239
CameraZ
Apache License 2.0
redwood-tooling-lint/src/main/kotlin/app/cash/redwood/tooling/lint/main.kt
cashapp
305,409,146
false
{"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129}
/* * Copyright (C) 2023 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("Main") package app.cash.redwood.tooling.lint import com.github.ajalt.clikt.core.NoOpCliktCommand import com.github.ajalt.clikt.core.main import com.github.ajalt.clikt.core.subcommands import java.nio.file.FileSystems public fun main(vararg args: String) { NoOpCliktCommand(name = "redwood-lint") .subcommands( ApiMergeCommand(FileSystems.getDefault()), LintCommand(), ) .main(args) }
126
Kotlin
73
1,648
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
1,029
redwood
Apache License 2.0
sqlite-embedder-graalvm/src/jvmMain/kotlin/ru/pixnews/wasm/sqlite/open/helper/graalvm/host/emscripten/func/SyscallGetcwd.kt
illarionov
769,429,996
false
null
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.graalvm.host.emscripten.func import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary import com.oracle.truffle.api.frame.VirtualFrame import org.graalvm.wasm.WasmContext import org.graalvm.wasm.WasmInstance import org.graalvm.wasm.WasmLanguage import org.graalvm.wasm.WasmModule import org.graalvm.wasm.memory.WasmMemory import ru.pixnews.wasm.sqlite.open.helper.common.api.Logger import ru.pixnews.wasm.sqlite.open.helper.common.api.WasmPtr import ru.pixnews.wasm.sqlite.open.helper.graalvm.SqliteEmbedderHost import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.getArgAsInt import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.getArgAsWasmPtr import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.BaseWasmNode import ru.pixnews.wasm.sqlite.open.helper.host.memory.encodeToNullTerminatedByteArray import ru.pixnews.wasm.sqlite.open.helper.host.wasi.preview1.type.Errno internal class SyscallGetcwd( language: WasmLanguage, module: WasmModule, private val host: SqliteEmbedderHost, functionName: String = "__syscall_getcwd", ) : BaseWasmNode(language, module, functionName) { private val logger: Logger = host.rootLogger.withTag(SyscallGetcwd::class.qualifiedName!!) override fun executeWithContext(frame: VirtualFrame, context: WasmContext, wasmInstance: WasmInstance): Int { val args = frame.arguments return syscallGetcwd( memory(frame), args.getArgAsWasmPtr(0), args.getArgAsInt(1), ) } @TruffleBoundary @Suppress("MemberNameEqualsClassName") private fun syscallGetcwd( memory: WasmMemory, dst: WasmPtr<Byte>, size: Int, ): Int { logger.v { "getCwd(dst: $dst size: $size)" } if (size == 0) { return -Errno.INVAL.code } val path = host.fileSystem.getCwd() val pathBytes: ByteArray = path.encodeToNullTerminatedByteArray() if (size < pathBytes.size) { return -Errno.RANGE.code } memory.initialize(pathBytes, 0, dst.addr.toLong(), pathBytes.size) return pathBytes.size } }
0
null
0
1
c3928d1985a78ddb67ff90525f4e2be33058d8b8
2,437
wasm-sqlite-open-helper
Apache License 2.0
app/src/main/java/com/roxana/recipeapp/ui/theme/Color.kt
roxanapirlea
383,507,335
false
null
package com.roxana.recipeapp.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF9D3F4C) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFDADB) val md_theme_light_onPrimaryContainer = Color(0xFF40000F) val md_theme_light_secondary = Color(0xFF765658) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFDADB) val md_theme_light_onSecondaryContainer = Color(0xFF2C1517) val md_theme_light_tertiary = Color(0xFF775930) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFDDB5) val md_theme_light_onTertiaryContainer = Color(0xFF2A1800) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF201A1A) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF201A1A) val md_theme_light_surfaceVariant = Color(0xFFF4DDDE) val md_theme_light_onSurfaceVariant = Color(0xFF524344) val md_theme_light_outline = Color(0xFF857374) val md_theme_light_inverseOnSurface = Color(0xFFFBEEEE) val md_theme_light_inverseSurface = Color(0xFF362F2F) val md_theme_light_inversePrimary = Color(0xFFFFB2B8) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF9D3F4C) val md_theme_dark_primary = Color(0xFFFFB2B8) val md_theme_dark_onPrimary = Color(0xFF601121) val md_theme_dark_primaryContainer = Color(0xFF7E2836) val md_theme_dark_onPrimaryContainer = Color(0xFFFFDADB) val md_theme_dark_secondary = Color(0xFFE5BDBF) val md_theme_dark_onSecondary = Color(0xFF44292B) val md_theme_dark_secondaryContainer = Color(0xFF5C3F41) val md_theme_dark_onSecondaryContainer = Color(0xFFFFDADB) val md_theme_dark_tertiary = Color(0xFFE8C08E) val md_theme_dark_onTertiary = Color(0xFF442B06) val md_theme_dark_tertiaryContainer = Color(0xFF5D421B) val md_theme_dark_onTertiaryContainer = Color(0xFFFFDDB5) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF201A1A) val md_theme_dark_onBackground = Color(0xFFECE0DF) val md_theme_dark_surface = Color(0xFF201A1A) val md_theme_dark_onSurface = Color(0xFFECE0DF) val md_theme_dark_surfaceVariant = Color(0xFF524344) val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C2) val md_theme_dark_outline = Color(0xFF9F8C8D) val md_theme_dark_inverseOnSurface = Color(0xFF201A1A) val md_theme_dark_inverseSurface = Color(0xFFECE0DF) val md_theme_dark_inversePrimary = Color(0xFF9D3F4C) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFFFB2B8) val seed = Color(0xFF8B323F)
0
Kotlin
0
1
8dc3e7040d806893dddd4538e15dd3a40faa80a4
3,005
RecipeApp
Apache License 2.0
app/src/main/java/com/example/barcodescanner/feature/tabs/create/qr/CreateQrCodePhoneFragment.kt
wewewe718
271,136,908
false
null
package com.example.barcodescanner.feature.tabs.create.qr import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.widget.addTextChangedListener import com.example.barcodescanner.R import com.example.barcodescanner.extension.isNotBlank import com.example.barcodescanner.extension.textString import com.example.barcodescanner.feature.tabs.create.BaseCreateBarcodeFragment import com.example.barcodescanner.model.schema.Phone import com.example.barcodescanner.model.schema.Schema import kotlinx.android.synthetic.main.fragment_create_qr_code_phone.* class CreateQrCodePhoneFragment : BaseCreateBarcodeFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_create_qr_code_phone, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initEditText() handleTextChanged() } override fun showPhone(phone: String) { edit_text.apply { setText(phone) setSelection(phone.length) } } override fun getBarcodeSchema(): Schema { return Phone(edit_text.textString) } private fun initEditText() { edit_text.requestFocus() } private fun handleTextChanged() { edit_text.addTextChangedListener { parentActivity.isCreateBarcodeButtonEnabled = edit_text.isNotBlank() } } }
83
null
124
651
da922e7b96906ec55a7437733378e850ca9262f7
1,595
QrAndBarcodeScanner
The Unlicense
app/src/main/java/com/mizukikk/mltd/main/idol/model/IdolStatus.kt
mizukikk
268,541,057
false
null
package com.mizukikk.mltd.main.idol.model data class IdolStatus( val vo: String, val vi: String, val da: String, val total: String, val level: String )
0
Kotlin
0
0
10e765109df9d0aa68557e78720851eae51622f1
172
MLTD
MIT License
src/main/kotlin/model/portarrivalevents/OfferShipUpgradeEvent.kt
ephemeral-laboratories
476,077,698
false
null
package garden.ephemeral.games.taipan.model.portarrivalevents import garden.ephemeral.games.taipan.Strings import garden.ephemeral.games.taipan.model.GameLogic import garden.ephemeral.games.taipan.model.GameState import garden.ephemeral.games.taipan.model.Money import garden.ephemeral.games.taipan.model.YesNo import garden.ephemeral.games.taipan.view.View import java.text.MessageFormat class OfferShipUpgradeEvent : PortArrivalEvent { override fun run(state: GameState, view: View) { if (state.random.nextInt(4) != 0) return if (state.random.nextInt(2) == 0) { newShip(state, view) } else if (state.ship.guns < 1000) { newGun(state, view) } } private fun newShip(state: GameState, view: View) { val time = state.calendar.monthsSinceStart val amount = Money((state.random.nextInt(1000 * (time + 5) / 6) * (state.ship.capacity / 50) + 1000).toLong()) if (state.cash < amount) { return } view.showTitle(Strings.CompradorsReport) // TODO: Should invert the text if damaged. view.showDetail( MessageFormat.format( if (state.ship.damage > 0) { Strings.DoYouWishToTradeInYourShip_Damaged } else { Strings.DoYouWishToTradeInYourShip_Fine }, amount.fancyNumbers() ) ) val choice = view.askYesNo() if (choice == YesNo.Yes) { state.cash -= amount state.ship.expandHoldBy(50) state.ship.resetDamage() } if (state.random.nextInt(2) == 0 && state.ship.guns < 1000) { GameLogic.updatePortStatistics(state) newGun(state, view) } GameLogic.updatePortStatistics(state) } private fun newGun(state: GameState, view: View) { val time = state.calendar.monthsSinceStart val amount = Money((state.random.nextInt(1000 * (time + 5) / 6) + 500).toLong()) if (state.cash < amount || state.ship.available < 10) { return } view.showTitle(Strings.CompradorsReport) view.showDetail(MessageFormat.format(Strings.DoYouWishToBuyAGun, amount.fancyNumbers())) val choice = view.askYesNo() if (choice == YesNo.Yes) { state.cash -= amount state.ship.addGun() } GameLogic.updatePortStatistics(state) } }
0
Kotlin
0
1
a692a008265872783bdc3f401f193dd5ebb1fd2f
2,490
TaipanKt
The Unlicense
meistercharts-canvas/src/jsMain/kotlin/com/meistercharts/js/debug/FontMetricsCacheDebugLayer.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meistercharts.js.debug import com.meistercharts.algorithms.layers.AbstractLayer import com.meistercharts.algorithms.layers.LayerPaintingContext import com.meistercharts.algorithms.layers.LayerType import com.meistercharts.algorithms.layers.Layers import com.meistercharts.algorithms.layers.toggleShortcut import com.meistercharts.algorithms.layers.visible import com.meistercharts.canvas.ConfigurationDsl import com.meistercharts.color.Color import com.meistercharts.font.FontDescriptorFragment import com.meistercharts.canvas.Image import com.meistercharts.canvas.saved import com.meistercharts.canvas.size import it.neckar.events.KeyCode import it.neckar.events.KeyStroke import it.neckar.events.ModifierCombination import com.meistercharts.js.FontMetricsCacheJS import it.neckar.geometry.Direction import it.neckar.open.unit.other.px /** * This layer paints the canvas of the [com.meistercharts.js.FontMetricsCacheJS] */ class FontMetricsCacheDebugLayer( val configuration: Configuration = Configuration(), additionalConfiguration: Configuration.() -> Unit = {} ) : AbstractLayer() { init { configuration.additionalConfiguration() } override val type: LayerType get() = LayerType.Content override fun paint(paintingContext: LayerPaintingContext) { val gc = paintingContext.gc val canvas = FontMetricsCacheJS.fontMetricsCalculator.canvas.canvasElement gc.stroke(Color.orangered) gc.lineWidth = 5.0 gc.strokeRect(0.0, 0.0, canvas.width.toDouble(), canvas.height.toDouble()) gc.saved { gc.scale(1.0, 1.0 / FontMetricsCacheJS.fontMetricsCalculator.scaleFactorY) val image = Image(canvas, canvas.size) paintingContext.gc.saved { image.paintInBoundingBox(paintingContext, 0.0, 0.0, Direction.TopLeft) } @px val baseLineY = FontMetricsCacheJS.fontMetricsCalculator.anchorY.toDouble() gc.lineWidth = 1.0 gc.stroke(Color.blueviolet) gc.strokeLine(0.0, baseLineY, canvas.width.toDouble(), baseLineY) } val font = configuration.font.withDefaultValues() val fontMetrics = FontMetricsCacheJS.get(font) gc.fill(Color.darkgray) gc.fillText("Font metrics Content", 10.0, 10.0, Direction.TopLeft) gc.fillText("Cache size: ${FontMetricsCacheJS.cacheSize}", 10.0, 40.0, Direction.TopLeft) gc.fillText("font: $font", 10.0, 70.0, Direction.TopLeft) gc.fillText("ascent: ${fontMetrics.accentLine}", 10.0, 100.0, Direction.TopLeft) gc.fillText("ascentPercentage: ${fontMetrics.ascentPercentage}", 10.0, 130.0, Direction.TopLeft) gc.fillText("descent: ${fontMetrics.pLine}", 10.0, 160.0, Direction.TopLeft) gc.fillText("totalHeight: ${fontMetrics.totalHeight}", 10.0, 190.0, Direction.TopLeft) } @ConfigurationDsl class Configuration { /** * The font to retrieve font metrics for */ var font: FontDescriptorFragment = FontDescriptorFragment.DefaultSize } } /** * Adds the debug panel */ fun Layers.addFontMetricsDebugLayer() { addLayer( FontMetricsCacheDebugLayer() .visible(true) .toggleShortcut(KeyStroke(KeyCode('F'), ModifierCombination.CtrlShiftAlt)) ) }
3
null
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
3,776
meistercharts
Apache License 2.0
app/src/main/java/com/example/components/dynamic_components/components/radiobuttonslist/RadioButtonListContent.kt
gemaxd
457,775,392
false
{"Kotlin": 109878}
package com.example.components.dynamic_components.components.radiobuttonslist import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.components.dynamic_components.components.base.DefaultComponentHeader import com.example.components.dynamic_components.components.dropdown.emptyOption import com.example.components.dynamic_components.components.radiobutton.RadioButtonOption import com.example.components.dynamic_components.components.utils.DEFAULT_OPTION_HEIGHT import com.example.components.feature.dynamic_form.domain.model.Option @Composable fun RadioButtonListContent( title: String, description: String?, items: List<Option>, onItemSelected: (Option) -> Unit ){ val currentHeight = (items.size * DEFAULT_OPTION_HEIGHT).dp var selectedOption by remember { mutableStateOf(emptyOption()) } LaunchedEffect(Unit){ selectedOption = items.firstOrNull { it.optionChecked } ?: emptyOption() } Column { DefaultComponentHeader( modifier = Modifier.fillMaxWidth(), title = title, description = description ) LazyColumn( modifier = Modifier.heightIn( max = currentHeight, min = currentHeight ), content = { this.items(items.size){ val currentOption = items[it] RadioButtonOption( selected = selectedOption == currentOption, option = currentOption, onClick = { option -> selectedOption = option onItemSelected(option) } ) } } ) } }
0
Kotlin
0
0
78734952d09e76b140ffdd86c9e74cd2b97cf7e9
2,267
compose_components
MIT License
app/src/main/java/com/revolgenx/anilib/app/setting/dialog/HomePageOrderDialog.kt
AniLibApp
244,410,204
false
{"Kotlin": 1593083, "Shell": 52}
package com.revolgenx.anilib.app.setting.dialog import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import com.pranavpandey.android.dynamic.support.dialog.DynamicDialog import com.revolgenx.anilib.R import com.revolgenx.anilib.common.preference.getHomePageOrderFromType import com.revolgenx.anilib.common.preference.setHomePageOrderFromType import com.revolgenx.anilib.common.ui.dialog.BaseDialogFragment import com.revolgenx.anilib.home.data.meta.HomePageOrderType import com.revolgenx.anilib.app.setting.data.meta.HomePageOrderAdapterItem import com.revolgenx.anilib.databinding.HomePageOrderAdapterDialogLayoutBinding import com.revolgenx.anilib.databinding.HomePageOrderDialogLayoutBinding import com.woxthebox.draglistview.DragItemAdapter class HomePageOrderDialog : BaseDialogFragment<HomePageOrderDialogLayoutBinding>() { override var positiveText: Int? = R.string.done override var negativeText: Int? = R.string.cancel override var titleRes: Int? = R.string.home_order_drag_message private val homePageListOrder by lazy { requireContext().resources.getStringArray(R.array.home_page_list_order) } override fun bindView(): HomePageOrderDialogLayoutBinding { return HomePageOrderDialogLayoutBinding.inflate(provideLayoutInflater) } private lateinit var adapterPage: HomePageOrderRecyclerAdapter override fun onShowListener(alertDialog: DynamicDialog, savedInstanceState: Bundle?) { super.onShowListener(alertDialog, savedInstanceState) with(binding) { mDragListView.setCanDragHorizontally(false) mDragListView.setLayoutManager(LinearLayoutManager(requireContext())) val homePageOrderTypes = HomePageOrderType.values(); val orderList = homePageListOrder.mapIndexed { index, s -> Pair( index.toLong(), HomePageOrderAdapterItem( s, getHomePageOrderFromType(homePageOrderTypes[index]), homePageOrderTypes[index] ) ) }.sortedBy { it.second.order }.toMutableList() adapterPage = HomePageOrderRecyclerAdapter(orderList); mDragListView.setAdapter(adapterPage, true) } } override fun onPositiveClicked(dialogInterface: DialogInterface, which: Int) { adapterPage.itemList.forEachIndexed { index, pair -> setHomePageOrderFromType(pair.second.orderType, index) } dismiss() } internal class HomePageOrderRecyclerAdapter( list: MutableList<Pair<Long, HomePageOrderAdapterItem>> ) : DragItemAdapter<Pair<Long, HomePageOrderAdapterItem>, HomePageOrderRecyclerAdapter.ViewHolder>() { init { itemList = list } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = HomePageOrderAdapterDialogLayoutBinding.inflate( LayoutInflater.from(parent.context), parent, false ) binding.homeOrderAdapterItemLayout.corner = 20f return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { super.onBindViewHolder(holder, position) holder.bind(itemList[position]) } override fun getUniqueItemId(position: Int): Long { return mItemList[position].first } inner class ViewHolder(itemView: HomePageOrderAdapterDialogLayoutBinding) : DragItemAdapter.ViewHolder(itemView.root, R.id.homeOrderDragIcon, false) { private var mText: TextView = itemView.homeOrderName fun bind(item: Pair<Long, HomePageOrderAdapterItem>) { mText.text = item.second.name } } } }
36
Kotlin
3
76
b3caec5c00779c878e4cf22fb7d2034aefbeee54
4,060
AniLib
Apache License 2.0
kuery-client-spring-data-r2dbc/src/test/kotlin/dev/hsbrysk/kuery/spring/r2dbc/StringWrapperConversionTest.kt
be-hase
806,354,598
false
{"Kotlin": 164266}
package dev.hsbrysk.kuery.spring.jdbc import assertk.assertThat import assertk.assertions.isEqualTo import dev.hsbrysk.kuery.core.single import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.core.convert.converter.Converter class StringWrapperConversionTest { private val kueryClient = mysql.kueryClient( listOf( StringWrapperToStringConverter(), StringToStringWrapperConverter(), ), ) data class StringWrapper(val value: String) data class Record(val text: StringWrapper) class StringWrapperToStringConverter : Converter<StringWrapper, String> { override fun convert(source: StringWrapper): String = source.value } class StringToStringWrapperConverter : Converter<String, StringWrapper> { override fun convert(source: String): StringWrapper = StringWrapper(source) } @BeforeEach fun beforeEach() { mysql.setUpForConverterTest() } @AfterEach fun afterEach() { mysql.tearDownForConverterTest() } @Test fun test() { kueryClient.sql { +"INSERT INTO converter (text) VALUES (${StringWrapper("hoge")})" }.rowsUpdated() val record: Record = kueryClient.sql { +"SELECT * FROM converter" }.single() assertThat(record.text).isEqualTo(StringWrapper("hoge")) } companion object { private val mysql = MySqlTestContainer() @AfterAll @JvmStatic fun afterAll() { mysql.close() } } }
3
Kotlin
0
7
f87ae4527f05a0814cfc08450fa40f042c90402f
1,669
kuery-client
MIT License
compiler/testData/codegen/bytecodeText/inlineFromOtherModule.kt
danmichaels
42,903,228
true
{"Java": 15618011, "Kotlin": 10206314, "JavaScript": 176060, "Protocol Buffer": 41295, "HTML": 24250, "Lex": 17327, "ANTLR": 9689, "CSS": 9358, "Groovy": 5104, "Shell": 4638, "Batchfile": 3703, "IDL": 3186}
fun foo() { assert(1 == 1) { "Hahaha" } } // 1 INVOKESTATIC kotlin\/KotlinPackage\.getASSERTIONS_ENABLED // 0 INVOKESTATIC kotlin\/AssertionsJVMKt\.getASSERTIONS_ENABLED
0
Java
0
0
b4efe33efa4fc1d3f84ffe4ecc82b0a5e3852d0d
175
kotlin
Apache License 2.0
src/commonMain/kotlin/com/soywiz/kpspemu/format/PspFileFormat.kt
kpspemu
108,654,928
false
{"Gradle": 1, "Gradle Kotlin DSL": 1, "JSON": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "JavaScript": 3, "Markdown": 1, "Kotlin": 275, "INI": 2, "HTML": 3, "XML": 3, "SVG": 2, "Java": 30, "YAML": 2, "C": 61, "Unix Assembly": 3, "Makefile": 12, "Motorola 68K Assembly": 3, "C++": 8}
package com.soywiz.kpspemu.format import com.soywiz.korio.file.* import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* enum class PspFileFormat(val fileContainer: Boolean = false) { ELF, ENCRYPTED_ELF, PBP, CSO(fileContainer = true), ISO(fileContainer = true), ZIP(fileContainer = true), ; companion object { suspend fun detect(file: VfsFile): PspFileFormat? = detect(file.open(), file.basename) suspend fun detect(stream: AsyncStream, name: String = "unknown.bin"): PspFileFormat? = detect(stream.duplicate().readBytesExact(4).openSync(), name) fun detect(header: ByteArray, name: String = "unknown.bin"): PspFileFormat? = detect(header.openSync(), name) fun detect(stream: SyncStream, name: String = "unknown.bin"): PspFileFormat? { val magicId = stream.clone().readString(4, ASCII) val file = PathInfo(name) //println("magicId == '$magicId'") return when { magicId == "\u007fELF" -> ELF magicId == "\u007ePSP" -> ENCRYPTED_ELF magicId == "\u0000PBP" -> PBP magicId == "PK\u0003\u0004" -> ZIP magicId == "CISO" -> CSO file.extensionLC == "iso" -> ISO magicId == "\u0000\u0000\u0000\u0000" -> ISO // CD001 at sector 0x10 else -> null } } } } fun ByteArray.detectPspFormat() = PspFileFormat.detect(this) suspend fun VfsFile.detectPspFormat() = PspFileFormat.detect(this) suspend fun AsyncStream.detectPspFormat(name: String = "unknown.bin") = PspFileFormat.detect(this, name)
16
Kotlin
9
72
5ad15d161bef8baa40961ee508643306d933a50a
1,659
kpspemu
MIT License
app/src/main/java/com/maurya/dtxloopplayer/fragments/FolderFragment.kt
notrealmaurya
734,074,868
false
{"Kotlin": 139063, "Assembly": 24}
package com.maurya.dtxloopplayer.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.core.view.GravityCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import com.maurya.dtxloopplayer.MainActivity import com.maurya.dtxloopplayer.adapter.AdapterFolder import com.maurya.dtxloopplayer.database.FolderDataClass import com.maurya.dtxloopplayer.databinding.FragmentFolderBinding import com.maurya.dtxloopplayer.utils.showToast import com.maurya.dtxloopplayer.utils.updateTextViewWithFolderCount import com.maurya.dtxloopplayer.utils.updateTextViewWithItemCount import com.maurya.dtxloopplayer.viewModelsObserver.ModelResult import com.maurya.dtxloopplayer.viewModelsObserver.ViewModelObserver import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class FolderFragment : Fragment() { private lateinit var fragmentFolderBinding: FragmentFolderBinding private val viewModel: ViewModelObserver by viewModels() private lateinit var adapterFolder: AdapterFolder private lateinit var folderAdapter: AdapterFolder companion object { var folderList: ArrayList<FolderDataClass> = arrayListOf() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { fragmentFolderBinding = FragmentFolderBinding.inflate(inflater, container, false) val view = fragmentFolderBinding.root return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragmentFolderBinding.recyclerViewFolderActivity.apply { setHasFixedSize(true) setItemViewCacheSize(13) layoutManager = LinearLayoutManager( requireContext(), LinearLayoutManager.VERTICAL, false ) adapterFolder = AdapterFolder( requireContext(), folderList, requireActivity().supportFragmentManager ) adapter = adapterFolder } fragmentFolderBinding.totalFoldersFolderActivity.text = "${adapterFolder.itemCount} folders" fetchFolderUsingViewModel() } private fun fetchFolderUsingViewModel() { viewModel.fetchFolders(requireContext()) viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.foldersStateFLow.collect { when (it) { is ModelResult.Success -> { fragmentFolderBinding.progressBar.visibility = View.GONE folderList.addAll(it.data!!) fragmentFolderBinding.totalFoldersFolderActivity.text = updateTextViewWithFolderCount(folderList.size) } is ModelResult.Error -> { showToast( requireContext(), it.message.toString() ) } is ModelResult.Loading -> { folderList.clear() fragmentFolderBinding.progressBar.visibility = View.VISIBLE adapterFolder.notifyDataSetChanged() } else -> {} } } } } } }
0
Kotlin
0
0
8dbec64f8561029e36d76d5404691bf5a68a3124
3,862
TuneTribe
MIT License
src/main/kotlin/no/nav/pensjon/simulator/core/knekkpunkt/KnekkpunktFinder.kt
navikt
753,551,695
false
{"Kotlin": 1452773, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.knekkpunkt import no.nav.pensjon.simulator.core.SimuleringSpec import no.nav.pensjon.simulator.core.domain.GrunnlagRolle import no.nav.pensjon.simulator.core.krav.KravlinjeTypePlus import no.nav.pensjon.simulator.core.domain.regler.Trygdetid import no.nav.pensjon.simulator.core.domain.regler.grunnlag.Opptjeningsgrunnlag import no.nav.pensjon.simulator.core.domain.regler.grunnlag.Persongrunnlag import no.nav.pensjon.simulator.core.domain.regler.grunnlag.Uttaksgrad import no.nav.pensjon.simulator.core.domain.regler.kode.RegelverkTypeCti import no.nav.pensjon.simulator.core.domain.regler.krav.Kravhode import no.nav.pensjon.simulator.core.domain.regler.to.TrygdetidRequest import no.nav.pensjon.simulator.core.krav.KravUtil import no.nav.pensjon.simulator.core.legacy.util.DateUtil.createDate import no.nav.pensjon.simulator.core.legacy.util.DateUtil.findLatestDateByDay import no.nav.pensjon.simulator.core.legacy.util.DateUtil.fromLocalDate import no.nav.pensjon.simulator.core.legacy.util.DateUtil.getRelativeDateByDays import no.nav.pensjon.simulator.core.legacy.util.DateUtil.getRelativeDateByYear import no.nav.pensjon.simulator.core.legacy.util.DateUtil.getYear import no.nav.pensjon.simulator.core.legacy.util.DateUtil.isAfterByDay import no.nav.pensjon.simulator.core.legacy.util.DateUtil.yearUserTurnsGivenAge import no.nav.pensjon.simulator.core.util.DateNoonExtension.noon import no.nav.pensjon.simulator.core.util.PensjonTidUtil.OPPTJENING_ETTERSLEP_ANTALL_AAR import no.nav.pensjon.simulator.core.util.PensjonTidUtil.ubetingetPensjoneringDato import no.nav.pensjon.simulator.core.util.toLocalDate import java.time.LocalDate import java.util.* // Corresponds to FinnKnekkpunkterHelper + FastsettTrygdetidCache class KnekkpunktFinder(private val trygdetidFastsetter: TrygdetidFastsetter) { // FinnKnekkpunkterHelper.finnKnekkpunkter fun finnKnekkpunkter(knekkpunktSpec: KnekkpunktSpec): SortedMap<LocalDate, MutableList<KnekkpunktAarsak>> { val kravhode = knekkpunktSpec.kravhode val simuleringSpec = knekkpunktSpec.simulering val soekerForsteVirkning = knekkpunktSpec.soekerVirkningFom val avdoedFoersteVirkning = knekkpunktSpec.avdoedVirkningFom val foersteUttakDato = simuleringSpec.foersteUttakDato val soekerGrunnlag = kravhode.hentPersongrunnlagForSoker() val avdoedGrunnlag = kravhode.hentPersongrunnlagForRolle(GrunnlagRolle.AVDOD, false) var knekkpunktMap: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>> = TreeMap() // STEP 1 - Calculate forsteBerDato val foersteBeregningDato = knekkpunktSpec.forrigeAlderspensjonBeregningResultatVirkningFom?.let { calculateFoersteBeregningDato( foedselDato = soekerGrunnlag.fodselsdato.toLocalDate()!!, foersteUttakDato = foersteUttakDato!!, forrigeBeregningResultVirkning = it ) } ?: forsteBeregningsdato(simuleringSpec) // STEP 2 - Add knekkpunkter based the opptjeningsgrunnlag for SOKER (and AVDOD if GJR) addKnekkpunkterBasedOnOpptjeningsgrunnlag( knekkpunktMap = knekkpunktMap, opptjeningGrunnlagListe = soekerGrunnlag.opptjeningsgrunnlagListe, aarsak = KnekkpunktAarsak.OPPTJBRUKER ) if (avdoedGrunnlag != null) { addKnekkpunkterBasedOnOpptjeningsgrunnlag( knekkpunktMap = knekkpunktMap, opptjeningGrunnlagListe = avdoedGrunnlag.opptjeningsgrunnlagListe, aarsak = KnekkpunktAarsak.OPPTJAVDOD ) } // STEP 3 - Add knekkpunkter based the trygdetid for SOKER (and AVDOD if GJR) addKnekkpunkterBasedOnTrygdetid( knekkpunktMap = knekkpunktMap, foersteBeregningDato = foersteBeregningDato!!, foersteVirkning = soekerForsteVirkning, kravhode = kravhode, aarsak = KnekkpunktAarsak.TTBRUKER, sakId = knekkpunktSpec.sakId ) if (avdoedGrunnlag != null) { addKnekkpunkterBasedOnTrygdetid( knekkpunktMap = knekkpunktMap, foersteBeregningDato = foersteBeregningDato, foersteVirkning = avdoedFoersteVirkning!!, kravhode = kravhode, aarsak = KnekkpunktAarsak.TTAVDOD, sakId = knekkpunktSpec.sakId ) } // STEP 4 - Add knekkpunkter based the uttaksgradliste addKnekkpunkterBasedOnUttaksgrader(knekkpunktMap, kravhode.uttaksgradListe) // STEP 5 - Add a knekkpunkt the 1st of the month after bruker turns 67 years old addKnekkpunkt( knekkpunktMap = knekkpunktMap, knekkpunktDato = soekerGrunnlag.fodselsdato?.let { ubetingetPensjoneringDato(it).toLocalDate() }!!, aarsak = KnekkpunktAarsak.OPPTJBRUKER ) // Make sure knekkpunkter before forsteBerDato are all stripped away knekkpunktMap = knekkpunktMap.tailMap(foersteBeregningDato) // When simulation is called from eksterne ordninger for a 2025-bruker, then we should // force a Kap 19 simulation even for pure Kap 20 brukere (2025) since eksterne ordninger currently aren't able to parse // a Kap 20 result. The following is part of that "logic". This "hack" should be removed as soon as they're able to // receive Kap 20 results. if (simuleringSpec.simulerForTp) { knekkpunktMap = trimKnekkpunkterInCaseOfSimulerForTp(soekerGrunnlag.fodselsdato.toLocalDate()!!, knekkpunktMap) } return knekkpunktMap } // FastsettTrygdetidCache.fastsettTrygdetid + fastsettTrygdetidInPreg + updateSisteGyldigeOpptjeningsaar private fun fastsettTrygdetid( aarsak: KnekkpunktAarsak, kravhode: Kravhode, foersteBeregningDato: LocalDate, foersteVirkning: LocalDate, sakId: Long? ): TrygdetidCombo { if (aarsak == KnekkpunktAarsak.TTBRUKER) { // from FinnKnekkpunkterHelper.addKnekkpunkterBasedOnTrygdetid val persongrunnlag = kravhode.hentPersongrunnlagForRolle(grunnlagsrolle = GrunnlagRolle.SOKER, checkBruk = false)!! return trygdetidFastsetter.fastsettTrygdetidForPeriode( spec = trygdetidFastsetterInput( kravhode = kravhode, persongrunnlag = persongrunnlag, knekkpunktDato = foersteBeregningDato, soekerFoersteVirkning = foersteVirkning, ytelseType = KravlinjeTypePlus.AP, boddEllerArbeidetUtenlands = kravhode.boddEllerArbeidetIUtlandet ), rolle = GrunnlagRolle.SOKER, kravIsUforetrygd = persongrunnlag.gjelderUforetrygd, sakId = sakId ) } val persongrunnlag = kravhode.hentPersongrunnlagForRolle(grunnlagsrolle = GrunnlagRolle.AVDOD, checkBruk = false)!! return trygdetidFastsetter.fastsettTrygdetidForPeriode( spec = trygdetidFastsetterInput( kravhode = kravhode, persongrunnlag = persongrunnlag, knekkpunktDato = foersteBeregningDato, soekerFoersteVirkning = foersteVirkning, ytelseType = KravlinjeTypePlus.GJR, boddEllerArbeidetUtenlands = kravhode.boddArbeidUtlandAvdod ), rolle = GrunnlagRolle.AVDOD, kravIsUforetrygd = persongrunnlag.gjelderUforetrygd, sakId = sakId ) } // FinnKnekkpunkterHelper.addKnekkpunkterBasedOnTrygdetid private fun addKnekkpunkterBasedOnTrygdetid( knekkpunktMap: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>>, foersteBeregningDato: LocalDate, foersteVirkning: LocalDate, kravhode: Kravhode, aarsak: KnekkpunktAarsak, sakId: Long? ) { val gjelderSoeker = aarsak == KnekkpunktAarsak.TTBRUKER val grunnlagRolle = if (gjelderSoeker) GrunnlagRolle.SOKER else GrunnlagRolle.AVDOD val persongrunnlag = kravhode.hentPersongrunnlagForRolle(grunnlagRolle, false)!! val boddEllerArbeidetUtenlands = if (gjelderSoeker) kravhode.boddEllerArbeidetIUtlandet else kravhode.boddArbeidUtlandAvdod val kravlinjeType = if (gjelderSoeker) KravlinjeTypePlus.AP else KravlinjeTypePlus.GJR val sisteRelevanteAar = if (gjelderSoeker) yearUserTurnsGivenAge(persongrunnlag.fodselsdato!!, MAX_RELEVANTE_TRYGDETID_ALDER) else getYear(getRelativeDateByYear(persongrunnlag.dodsdato!!, ANTALL_RELEVANTE_AR_ETTER_DODSDATO)) addKnekkpunkt(knekkpunktMap, foersteBeregningDato, aarsak) val forrigeTrygdetid = fastsettTrygdetid(aarsak, kravhode, foersteBeregningDato, foersteVirkning, sakId) var forrigeTrygdetidKap19 = forrigeTrygdetid.kapittel19 var forrigeTrygdetidKap20 = forrigeTrygdetid.kapittel20 for (kalenderAar in foersteBeregningDato.year + 1..sisteRelevanteAar) { val virkDato = LocalDate.of(kalenderAar, 1, 1) val trygdetidInput = trygdetidFastsetterInput( kravhode, persongrunnlag, virkDato, foersteVirkning, kravlinjeType, boddEllerArbeidetUtenlands ) val trygdetid = trygdetidFastsetter.fastsettTrygdetidForPeriode( trygdetidInput, grunnlagRolle, persongrunnlag.gjelderUforetrygd, sakId ) val trygdetidKap19 = trygdetid.kapittel19 val trygdetidKap20 = trygdetid.kapittel20 if (areDifferent(trygdetidKap19, forrigeTrygdetidKap19) || areDifferent(trygdetidKap20, forrigeTrygdetidKap20) ) { addKnekkpunkt(knekkpunktMap, virkDato, aarsak) } if (erFull(trygdetidKap19) && erFull(trygdetidKap20)) { break } forrigeTrygdetidKap19 = trygdetidKap19 forrigeTrygdetidKap20 = trygdetidKap20 } } private companion object { private const val MAX_RELEVANTE_TRYGDETID_ALDER = 76 private const val FULL_TRYGDETID_ANTALL_AR = 40 private const val ANTALL_RELEVANTE_AR_ETTER_DODSDATO = 2 // FinnKnekkpunkterHelper.addKnekkpunkt private fun addKnekkpunkt( knekkpunktMap: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>>, knekkpunktDato: LocalDate, aarsak: KnekkpunktAarsak ) { var aarsaker = knekkpunktMap[knekkpunktDato] if (aarsaker == null) { aarsaker = mutableListOf() knekkpunktMap[knekkpunktDato] = aarsaker } aarsaker.add(aarsak) } // FinnKnekkpunkterHelper.addKnekkpunkterBasedOnOpptjeningsgrunnlagListe private fun addKnekkpunkterBasedOnOpptjeningsgrunnlag( knekkpunktMap: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>>, opptjeningGrunnlagListe: MutableList<Opptjeningsgrunnlag>, aarsak: KnekkpunktAarsak ) { for (grunnlag in opptjeningGrunnlagListe) { if (grunnlag.pi > 0) { addKnekkpunkt( knekkpunktMap, LocalDate.of(grunnlag.ar + OPPTJENING_ETTERSLEP_ANTALL_AAR, 1, 1), aarsak ) } } } // FinnKnekkpunkterHelper.addKnekkpunkterBasedOnUttaksgradListe private fun addKnekkpunkterBasedOnUttaksgrader( knekkpunktMap: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>>, uttakGradListe: MutableList<Uttaksgrad> ) { for (uttaksgrad in uttakGradListe) { addKnekkpunkt(knekkpunktMap, uttaksgrad.fomDato.toLocalDate()!!, KnekkpunktAarsak.UTG) } } // FinnKnekkpunkterHelper.calculateForsteBeregningDato private fun calculateFoersteBeregningDato( foedselDato: LocalDate, foersteUttakDato: LocalDate, forrigeBeregningResultVirkning: LocalDate ): LocalDate { // Citation from design: // SETT forsteBerDato = den første av følgende datoer // - 1.1 neste kalenderår etter den siste av dagens dato og forrigeBerResAP.virkDato // - forsteUttaksdato // - den 1. i måneden etter at bruker blir 67 år, dersom denne er etter dagens dato og forrigeBerResAP.virkDato //val today = DateProvider.getToday() val today = LocalDate.now() val ubetingetPensjoneringDato: Date = ubetingetPensjoneringDato(fromLocalDate(foedselDato)!!) val latestOfTodayAndForrigeBerResVirk: Date? = findLatestDateByDay(fromLocalDate(today), fromLocalDate(forrigeBeregningResultVirkning)) val sortedDates: SortedSet<Date> = TreeSet() sortedDates.add(createDate(getYear(latestOfTodayAndForrigeBerResVirk!!) + 1, Calendar.JANUARY, 1)) sortedDates.add(fromLocalDate(foersteUttakDato)) if (isAfterByDay(ubetingetPensjoneringDato, latestOfTodayAndForrigeBerResVirk, false)) { sortedDates.add(ubetingetPensjoneringDato) } return sortedDates.iterator().next().toLocalDate()!! } // FinnKnekkpunkterHelper.trimKnekkpunktListeInCaseOfSimulerForTp private fun trimKnekkpunkterInCaseOfSimulerForTp( foedselDato: LocalDate, knekkpunkter: SortedMap<LocalDate, MutableList<KnekkpunktAarsak>> ): SortedMap<LocalDate, MutableList<KnekkpunktAarsak>> { var latestRelevantKnekkpunkt: LocalDate = ubetingetPensjoneringDato(foedselDato) // If there is a UTG knekkpunkt later than 67m, then use that as latest relevant knekkpunkt date for ((key, value) in knekkpunkter) { if (value.contains(KnekkpunktAarsak.UTG)) { if (isAfterByDay(key, latestRelevantKnekkpunkt, false)) { latestRelevantKnekkpunkt = key } } } // Strip all knekkpunkter later than last relevant knekkpunkt date: // return knekkpunkter.headMap(getRelativeDateByDays(latestRelevantKnekkpunkt, 1).toLocalDate()) return knekkpunkter.headMap(getRelativeDateByDays(latestRelevantKnekkpunkt, 1)) } private fun forsteBeregningsdato(spec: SimuleringSpec) = if (spec.gjelderPre2025OffentligAfp()) spec.heltUttakDato else spec.foersteUttakDato private fun areDifferent(a: Trygdetid?, b: Trygdetid?): Boolean { if (a == null != (b == null)) { return true } return b != null && a!!.tt != b.tt } private fun erFull(trygdetid: Trygdetid?) = trygdetid == null || trygdetid.tt == FULL_TRYGDETID_ANTALL_AR private fun trygdetidFastsetterInput( kravhode: Kravhode, persongrunnlag: Persongrunnlag, knekkpunktDato: LocalDate, soekerFoersteVirkning: LocalDate, ytelseType: KravlinjeTypePlus, boddEllerArbeidetUtenlands: Boolean ) = TrygdetidRequest().apply { this.virkFom = fromLocalDate(knekkpunktDato)!!.noon() this.brukerForsteVirk = fromLocalDate(soekerFoersteVirkning)!!.noon() this.ytelsesType = KravUtil.kravlinjeType(ytelseType) this.persongrunnlag = persongrunnlag this.boddEllerArbeidetIUtlandet = boddEllerArbeidetUtenlands this.regelverkType = RegelverkTypeCti(kravhode.regelverkTypeCti!!.kode) this.uttaksgradListe = kravhode.uttaksgradListe // Not set: virkTom, beregningsvilkarPeriodeListe // NB: grunnlagsrolle is only used for caching } } }
2
Kotlin
0
0
77b8c4e0a80e5bf44cb44468466362956fe82da8
16,354
pensjonssimulator
MIT License
src/main/kotlin/model/Submission.kt
steep-wms
237,438,539
false
null
package model import helper.UniqueID import model.metadata.Service import model.workflow.Action import model.workflow.ExecuteAction import model.workflow.ForEachAction import model.workflow.Workflow import java.time.Instant /** * A submission * @param id the submission's unique identifier * @param workflow the workflow to execute * @param startTime the time when the workflow was started * @param endTime the time when the workflow has finished * @param status the current execution status * @author Michel Kraemer */ data class Submission( val id: String = UniqueID.next(), val workflow: Workflow, val startTime: Instant? = null, val endTime: Instant? = null, val status: Status = Status.ACCEPTED ) { enum class Status { ACCEPTED, RUNNING, CANCELLED, SUCCESS, PARTIAL_SUCCESS, ERROR } companion object { private fun collectRequiredCapabilities(actions: List<Action>, serviceMetadata: Map<String, Service>): Set<String> { val result = mutableSetOf<String>() for (a in actions) { when (a) { is ExecuteAction -> { val service = serviceMetadata[a.service] if (service != null) { result.addAll(service.requiredCapabilities) } } is ForEachAction -> result.addAll(collectRequiredCapabilities(a.actions, serviceMetadata)) } } return result } } /** * Use the metadata of the given [services] to calculate a set of * capabilities required to execute this submission */ fun collectRequiredCapabilities(services: List<Service>): Set<String> { val serviceMetadata = services.map { it.id to it }.toMap() return collectRequiredCapabilities(workflow.actions, serviceMetadata) } }
9
Kotlin
4
15
c9fd601c6ab0a81e8dbebe8351ea73b20bd29756
1,803
steep
Apache License 2.0
src/main/kotlin/model/Submission.kt
steep-wms
237,438,539
false
null
package model import helper.UniqueID import model.metadata.Service import model.workflow.Action import model.workflow.ExecuteAction import model.workflow.ForEachAction import model.workflow.Workflow import java.time.Instant /** * A submission * @param id the submission's unique identifier * @param workflow the workflow to execute * @param startTime the time when the workflow was started * @param endTime the time when the workflow has finished * @param status the current execution status * @author Michel Kraemer */ data class Submission( val id: String = UniqueID.next(), val workflow: Workflow, val startTime: Instant? = null, val endTime: Instant? = null, val status: Status = Status.ACCEPTED ) { enum class Status { ACCEPTED, RUNNING, CANCELLED, SUCCESS, PARTIAL_SUCCESS, ERROR } companion object { private fun collectRequiredCapabilities(actions: List<Action>, serviceMetadata: Map<String, Service>): Set<String> { val result = mutableSetOf<String>() for (a in actions) { when (a) { is ExecuteAction -> { val service = serviceMetadata[a.service] if (service != null) { result.addAll(service.requiredCapabilities) } } is ForEachAction -> result.addAll(collectRequiredCapabilities(a.actions, serviceMetadata)) } } return result } } /** * Use the metadata of the given [services] to calculate a set of * capabilities required to execute this submission */ fun collectRequiredCapabilities(services: List<Service>): Set<String> { val serviceMetadata = services.map { it.id to it }.toMap() return collectRequiredCapabilities(workflow.actions, serviceMetadata) } }
9
Kotlin
4
15
c9fd601c6ab0a81e8dbebe8351ea73b20bd29756
1,803
steep
Apache License 2.0
android/src/test/java/com/revenuecat/purchases/hybridcommon/ConfiguringUnitTests.kt
RevenueCat
197,481,725
false
{"Swift": 149543, "Kotlin": 143786, "TypeScript": 48493, "Java": 21431, "Ruby": 15864, "Objective-C": 10158, "JavaScript": 185}
package com.revenuecat.purchases.hybridcommon import android.app.Application import android.content.Context import com.revenuecat.purchases.DangerousSettings import com.revenuecat.purchases.Purchases import com.revenuecat.purchases.PurchasesConfiguration import com.revenuecat.purchases.Store import com.revenuecat.purchases.common.PlatformInfo import io.mockk.CapturingSlot import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.slot import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertTrue internal class ConfiguringUnitTests { private val mockPurchases = mockk<Purchases>() private val mockContext = mockk<Context>(relaxed = true) private val mockApplicationContext = mockk<Application>(relaxed = true) private val expectedPlatformInfo = PlatformInfo("flavor", "version") private val purchasesConfigurationSlot = slot<PurchasesConfiguration>() @BeforeEach fun setup() { every { mockContext.applicationContext } returns mockApplicationContext mockkObject(Purchases) every { Purchases.configure(any()) } returns mockPurchases every { Purchases.configure(configuration = capture(purchasesConfigurationSlot)) } returns mockPurchases } @Test fun `calling configure with observer mode false should configure the Android SDK with observer mode false`() { configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = false, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) assertConfiguration( purchasesConfigurationSlot, expectedContext = mockContext, expectedApiKey = "api_key", expectedAppUserID = "appUserID", expectedObserverMode = false, ) } @Test fun `calling configure with observer mode true, should configure the Android SDK with observer mode true`() { configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = true, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) assertConfiguration( purchasesConfigurationSlot, expectedContext = mockContext, expectedApiKey = "api_key", expectedAppUserID = "appUserID", expectedObserverMode = true, ) } @Test fun `calling configure with a null observer mode should configure the Android SDK with observer mode false`() { configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = null, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) assertConfiguration( purchasesConfigurationSlot, expectedContext = mockContext, expectedApiKey = "api_key", expectedAppUserID = "appUserID", expectedObserverMode = false, ) } @Test fun `calling configure with a null app user ID, should configure the Android SDK with null app user ID`() { configure( context = mockContext, apiKey = "api_key", appUserID = null, observerMode = null, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) assertConfiguration( purchasesConfigurationSlot, expectedContext = mockContext, expectedApiKey = "api_key", expectedAppUserID = null, expectedObserverMode = false, ) } @Test fun `calling configure with a platform info, should configure the Android SDK with that platform info`() { configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = false, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) verify(exactly = 1) { Purchases.platformInfo = expectedPlatformInfo } } @Test fun `calling configure without dangerous settings defaults to autosync on`() { val expectedDangerousSettings = DangerousSettings(autoSyncPurchases = true) configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = false, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, ) assertEquals(expectedDangerousSettings, purchasesConfigurationSlot.captured.dangerousSettings) } @Test fun `calling configure passing dangerous settings on`() { val expectedDangerousSettings = DangerousSettings(autoSyncPurchases = false) configure( context = mockContext, apiKey = "api_key", appUserID = "appUserID", observerMode = false, platformInfo = expectedPlatformInfo, store = Store.PLAY_STORE, dangerousSettings = expectedDangerousSettings, ) assertEquals(expectedDangerousSettings, purchasesConfigurationSlot.captured.dangerousSettings) } private fun assertConfiguration( purchasesConfigurationSlot: CapturingSlot<PurchasesConfiguration>, expectedContext: Context, expectedApiKey: String, expectedAppUserID: String?, expectedObserverMode: Boolean, ) { assertTrue(purchasesConfigurationSlot.isCaptured) purchasesConfigurationSlot.captured.let { captured -> assertEquals(expectedContext, captured.context) assertEquals(expectedApiKey, captured.apiKey) assertEquals(expectedAppUserID, captured.appUserID) assertEquals(expectedObserverMode, captured.observerMode) } } }
3
Swift
5
14
feded777ccf2d5bc48b7b85f352eff8f71908b5b
6,148
purchases-hybrid-common
MIT License
app/src/main/java/com/qhy040404/libraryonetap/base/IBinding.kt
qhy040404
484,416,715
false
null
package com.absinthe.libchecker.ui.base import android.view.LayoutInflater import androidx.viewbinding.ViewBinding import java.lang.reflect.Method import java.lang.reflect.ParameterizedType internal sealed interface IBinding<VB : ViewBinding> { val binding: VB fun <T : ViewBinding> inflateBinding(inflater: LayoutInflater): T { var method: Method? var clazz: Class<*> = javaClass while (clazz.superclass != null) { method = clazz.filterBindingMethod() if (method == null) { clazz = clazz.superclass } else { @Suppress("UNCHECKED_CAST") return method.invoke(null, inflater) as T } } error("No Binding type argument found.") } private fun Class<*>.filterBindingMethod(): Method? { return (genericSuperclass as? ParameterizedType)?.actualTypeArguments ?.asSequence() ?.filterIsInstance<Class<*>>() ?.firstOrNull { it.simpleName.endsWith("Binding") } ?.getDeclaredMethod("inflate", LayoutInflater::class.java) ?.also { it.isAccessible = true } } }
3
Kotlin
307
9
db5d2cf858f05a03273c5fe1e06944a713842c71
1,061
Library-One-Tap-Android
Apache License 2.0
service/src/main/kotlin/simple_feature_toggles/api/models/FeatureToggleUpdateRequest.kt
sebastian-struecker
818,679,238
false
{"Kotlin": 49204, "Dockerfile": 594}
package simple_feature_toggles.api.models data class FeatureToggleUpdateRequest( var name: String? = null, var description: String? = null, var contexts: List<ContextApiModel>? = null )
0
Kotlin
0
0
b8bfff328a4d9a80e5e69ca56478bcfb8b0baf2e
191
simple-feature-toggles
MIT License
app/src/main/java/com/example/jeonghyun/movieapp/api/ResponseTransformer.kt
yoojh9
225,756,921
false
null
package com.example.jeonghyun.movieapp.api import retrofit2.Call import retrofit2.Callback import retrofit2.Response fun <T> Call<T>.async(onResult: (response: ApiResponse<T>) -> Unit) { enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { onResult(ApiResponse.of{response}) } override fun onFailure(call: Call<T>, throwable: Throwable) { onResult(ApiResponse.error(throwable)) } }) } fun <T> ApiResponse.Failure.Error<T>.message() = "$code: ${responseBody?.string()}" fun <T> ApiResponse.Failure.Exception<T>.message() = "$message"
0
Kotlin
0
0
55bf44cc91d856c6fe9562509151eb52cf76e5ad
643
MovieApp
Apache License 2.0
src/main/kotlin/me/ddevil/util/math/vector/Vector4.kt
BrunoSilvaFreire
88,533,092
false
{"Kotlin": 89852}
package me.ddevil.util.math.vector import me.ddevil.util.immutableMap import me.ddevil.util.set abstract class Vector4<N : Number> : Vector3<N>() { abstract val w: N override val normalized: Vector4<N> get() = clone.normalize() override fun normalize(): Vector4<N> { super.normalize() return this } abstract override val clone: Vector4<N> override fun serialize(): Map<String, Any> = immutableMap { putAll(super.serialize()) this[W_IDENTIFIER] = w } fun distance(other: Vector4<*>) = (other - this).magnitude protected abstract fun plusAssignW(value: Number) protected abstract fun minusAssignW(value: Number) protected abstract fun timesAssignW(value: Number) protected abstract fun divAssignW(value: Number) override fun toInt(): Vector4<Int> = IntVector4(x.toInt(), z.toInt(), y.toInt(), w.toInt()) override fun toFloat(): Vector4<Float> = FloatVector4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat()) override fun toLong(): Vector4<Long> = LongVector4(x.toLong(), y.toLong(), z.toLong(), w.toLong()) override fun toDouble(): Vector4<Double> = DoubleVector4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble()) fun plusAssign(other: Vector4<*>) { super.plusAssign(other) plusAssignW(other.w) } fun minusAssign(other: Vector4<*>) { super.minusAssign(other) minusAssignW(other.w) } fun timesAssign(other: Vector4<*>) { super.timesAssign(other) timesAssignW(other.w) } fun divAssign(other: Vector4<*>) { super.divAssign(other) divAssignW(other.w) } override fun plusAssign(value: Number) { super.plus(value) plusAssignW(value) } override fun minusAssign(value: Number) { super.minusAssign(value) minusAssignW(value) } override fun timesAssign(value: Number) { super.timesAssign(value) timesAssignW(value) } override fun divAssign(value: Number) { super.divAssign(value) divAssignW(value) } fun plus(other: Vector4<*>): Vector4<N> { val clone = this.clone clone += other return clone } fun minus(other: Vector4<*>): Vector4<N> { val clone = this.clone clone -= other return clone } fun times(other: Vector4<*>): Vector4<N> { val clone = this.clone clone *= other return clone } fun div(other: Vector4<*>): Vector4<N> { val clone = this.clone clone /= other return clone } override fun plus(value: Number): Vector4<N> { val clone = this.clone clone += value return clone } override fun minus(value: Number): Vector4<N> { val clone = this.clone clone -= value return clone } override fun times(value: Number): Vector4<N> { val clone = this.clone clone *= value return clone } override fun div(value: Number): Vector4<N> { val clone = this.clone clone /= value return clone } }
0
Kotlin
0
1
65044d7f9d4ea6d4f201adb832418f13c1ae5e0c
3,172
KotlinUtils
Do What The F*ck You Want To Public License
meistercharts-canvas/src/jvmTest/kotlin/com/meistercharts/canvas/layout/cache/DoubleCacheTest.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meistercharts.canvas.layout.cache import assertk.* import assertk.assertions.* import it.neckar.open.provider.MultiDoublesProvider import it.neckar.open.unit.other.Index import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class DoubleCacheTest { private lateinit var doubleCache: DoubleCache @BeforeEach fun setUp() { doubleCache = DoubleCache() } @Test fun `check size after initialization`() { assertThat(doubleCache.size).isEqualTo(0) } @Test fun `ensure size`() { doubleCache.prepare(5) assertThat(doubleCache.size).isEqualTo(5) } @Test fun `resize`() { doubleCache.prepare(2) assertThat(doubleCache.size).isEqualTo(2) doubleCache.setAll(17.0) assertThat(doubleCache[0]).isEqualTo(17.0) assertThat(doubleCache[1]).isEqualTo(17.0) doubleCache.resize(5) assertThat(doubleCache.size).isEqualTo(5) assertThat(doubleCache[0]).isEqualTo(17.0) assertThat(doubleCache[1]).isEqualTo(17.0) assertThat(doubleCache[2]).isEqualTo(0.0) assertThat(doubleCache[3]).isEqualTo(0.0) assertThat(doubleCache[4]).isEqualTo(0.0) doubleCache.setAll(17.0) assertThat(doubleCache[0]).isEqualTo(17.0) assertThat(doubleCache[1]).isEqualTo(17.0) assertThat(doubleCache[2]).isEqualTo(17.0) assertThat(doubleCache[3]).isEqualTo(17.0) assertThat(doubleCache[4]).isEqualTo(17.0) } @Test fun `set and get values`() { doubleCache.prepare(1) doubleCache[0] = 2.0 assertThat(doubleCache[0]).isEqualTo(2.0) } @Test fun `set all values and check`() { doubleCache.prepare(3) doubleCache.setAll(2.0) assertThat(doubleCache[0]).isEqualTo(2.0) assertThat(doubleCache[1]).isEqualTo(2.0) assertThat(doubleCache[2]).isEqualTo(2.0) } @Test fun `get or else returns correct value`() { doubleCache.prepare(2) doubleCache[0] = 3.0 doubleCache[1] = 4.0 val defaultValue = MultiDoublesProvider<Index> { 99.0 } assertThat(doubleCache.getOrElse(0, defaultValue)).isEqualTo(3.0) assertThat(doubleCache.getOrElse(1, defaultValue)).isEqualTo(4.0) assertThat(doubleCache.getOrElse(2, defaultValue)).isEqualTo(99.0) } @Test fun `last or fallback returns correct value`() { doubleCache.prepare(2) doubleCache[0] = 5.0 doubleCache[1] = 6.0 assertThat(doubleCache.lastOr(7.0)).isEqualTo(6.0) } @Test fun `last or NaN returns correct value`() { doubleCache.prepare(2) doubleCache[0] = 5.0 doubleCache[1] = 6.0 assertThat(doubleCache.lastOrNaN()).isEqualTo(6.0) } @Test fun `fast any returns correct value`() { doubleCache.prepare(3) doubleCache[0] = 5.0 doubleCache[1] = 6.0 doubleCache[2] = 7.0 assertThat(doubleCache.fastAny { value -> value == 6.0 }).isTrue() } }
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
3,440
meistercharts
Apache License 2.0
twitlin/src/common/main/kotlin/com/sorrowblue/twitlin/users/account/impl/AccountApiImpl.kt
SorrowBlue
278,215,181
false
null
package com.sorrowblue.twitlin.users.account.impl import com.sorrowblue.twitlin.client.Response import com.sorrowblue.twitlin.client.TwitterClient import com.sorrowblue.twitlin.objects.User import com.sorrowblue.twitlin.users.account.AccountApi import com.sorrowblue.twitlin.users.account.Settings import com.sorrowblue.twitlin.utils.API_ACCOUNT import io.ktor.client.request.parameter import io.ktor.http.Parameters import kotlinx.serialization.builtins.serializer @Suppress("EXPERIMENTAL_API_USAGE_FUTURE_ERROR") internal class AccountApiImpl(private val client: TwitterClient) : AccountApi { override suspend fun settings(): Response<Settings> { return client.get("$API_ACCOUNT/settings.json", Response.serializer(Settings.serializer())) } override suspend fun verifyCredentials( includeEntities: Boolean, skipStatus: Boolean, includeEmail: Boolean ): Response<User> { return client.get("$API_ACCOUNT/verify_credentials.json", Response.serializer(User.serializer())) { parameter("include_entities", includeEntities) parameter("skip_status", skipStatus) parameter("include_email", includeEmail) } } override suspend fun removeProfileBanner(): Response<Unit> { return client.post("$API_ACCOUNT/remove_profile_banner.json", Response.serializer(Unit.serializer())) } override suspend fun settings( sleepTimeEnabled: Boolean?, startSleepTime: Int?, endSleepTime: Int?, timeZone: String?, trendLocationWoeid: Int?, lang: String? ): Response<Settings> { return client.submitForm( "$API_ACCOUNT/settings.json", Response.serializer(Settings.serializer()), Parameters.build { sleepTimeEnabled?.let { append("sleep_time_enabled", it.toString()) } startSleepTime?.let { append("start_sleep_time", it.toString()) } endSleepTime?.let { append("end_sleep_time", it.toString()) } timeZone?.let { append("time_zone", it) } trendLocationWoeid?.let { append("trend_location_woeid", it.toString()) } lang?.let { append("lang", it) } }) } override suspend fun updateProfile( name: String?, url: String?, location: String?, description: String?, profileLinkColor: String?, includeEntities: Boolean, skipStatus: Boolean ): Response<User> { return client.submitForm( "$API_ACCOUNT/update_profile.json", Response.serializer(User.serializer()), Parameters.build { name?.let { append("name", it) } url?.let { append("url", it) } location?.let { append("location", it) } description?.let { append("description", it) } profileLinkColor?.let { append("profile_link_color", it) } append("include_entities", includeEntities.toString()) append("skip_status", skipStatus.toString()) }) } override suspend fun updateProfileBanner( banner: String, width: Int?, height: Int?, offsetLeft: Int?, offsetTop: Int? ): Response<Unit> { return client.submitForm( "$API_ACCOUNT/update_profile_banner.json", Response.serializer(Unit.serializer()), Parameters.build { append("banner", banner) width?.let { append("width", it.toString()) } height?.let { append("height", it.toString()) } offsetLeft?.let { append("offset_left", it.toString()) } offsetTop?.let { append("offset_top", it.toString()) } }) } override suspend fun updateProfileImage( image: String, includeEntities: Boolean, skipStatus: Boolean ): Response<User> { return client.submitForm( "$API_ACCOUNT/update_profile_image.json", Response.serializer(User.serializer()), Parameters.build { append("image", image) append("include_entities", includeEntities.toString()) append("skip_status", skipStatus.toString()) }) } }
1
Kotlin
0
1
d6a3fdf66dea3d44f95e6800d35031d9339293cd
4,344
Twitlin
MIT License
src/main/kotlin/com/shrralis/serialnumbergenerator/config/format/part/impl/generated/Base26SerialNumberPartConfig.kt
shrralis
606,564,926
false
null
/* * The following code is created by shrralis. * * - Base26SerialNumberPartConfig.kt (Last change: 2/24/23, 9:50 PM by shrralis) * * Copyright (c) 2023-2023 by shrralis. */ package com.shrralis.serialnumbergenerator.config.format.part.impl.generated import com.shrralis.serialnumbergenerator.config.BASE_26_RADIX import com.shrralis.serialnumbergenerator.config.format.part.AbstractGeneratedSerialNumberPartConfig /** * A concrete implementation of the GeneratedSerialNumberPartConfig abstract class, * which generates serial number parts using the base-26 number system. * * @property width the width of the base-26 serial number part. * * @author shrralis * @see <a href="https://t.me/Shrralis">https://t.me/Shrralis</a> */ class Base26SerialNumberPartConfig(width: Int) : AbstractGeneratedSerialNumberPartConfig(width) { override val radix: Int = BASE_26_RADIX }
0
Kotlin
0
0
9eed8c1d7e9557be3b26ebe1f73a1d0684aee5d9
890
serial-number-generator
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/LinkHeaderViewHolder.kt
feelfreelinux
97,154,881
false
null
package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.ui.fragments.link.LinkHeaderActionListener import io.github.feelfreelinux.wykopmobilny.ui.fragments.link.LinkInteractor import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi import io.github.feelfreelinux.wykopmobilny.utils.api.getGroupColor import io.github.feelfreelinux.wykopmobilny.utils.api.stripImageCompression import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.loadImage import io.github.feelfreelinux.wykopmobilny.utils.textview.prepareBody import io.github.feelfreelinux.wykopmobilny.utils.textview.removeHtml import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.link_bury_menu_bottomsheet.view.* import kotlinx.android.synthetic.main.link_details_header_layout.* import kotlinx.android.synthetic.main.link_menu_bottomsheet.view.* import java.net.URL class LinkHeaderViewHolder( override val containerView: View, private val linkActionListener: LinkHeaderActionListener, val navigatorApi: NewNavigatorApi, val linkHandlerApi: WykopLinkHandlerApi, val userManagerApi: UserManagerApi ) : RecyclableViewHolder(containerView), LayoutContainer { companion object { const val TYPE_HEADER = 64 /** * Inflates correct view (with embed, survey or both) depending on viewType */ fun inflateView( parent: ViewGroup, userManagerApi: UserManagerApi, navigatorApi: NewNavigatorApi, linkHandlerApi: WykopLinkHandlerApi, linkHeaderActionListener: LinkHeaderActionListener ): LinkHeaderViewHolder { return LinkHeaderViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.link_details_header_layout, parent, false), linkHeaderActionListener, navigatorApi, linkHandlerApi, userManagerApi ) } } override fun cleanRecycled() { } fun bindView(link: Link) { when (link.userVote) { "dig" -> showDigged(link) "bury" -> showBurried(link) null -> showUnvoted(link) } setupHeader(link) setupButtons(link) setupBody(link) } private fun setupHeader(link: Link) { dateTextView.text = link.date hotBadgeStrip.isVisible = link.isHot val author = link.author if (author != null) { avatarView.isVisible = true userTextView.isVisible = true userTextView.setOnClickListener { navigatorApi.openProfileActivity(link.author.nick) } avatarView.setOnClickListener { navigatorApi.openProfileActivity(link.author.nick) } avatarView.setAuthor(link.author) userTextView.text = link.author.nick userTextView.setTextColor(containerView.context.getGroupColor(link.author.group)) } else { avatarView.isVisible = false userTextView.isVisible = false } urlTextView.text = URL(link.sourceUrl).host.removePrefix("www.") blockedTextView.prepareBody(link.tags.convertToTagsHtml()) { linkHandlerApi.handleUrl(it) } } private fun setupButtons(link: Link) { diggCountTextView.text = link.voteCount.toString() diggCountTextView.setup(userManagerApi) commentsCountTextView.text = link.commentsCount.toString() moreOptionsTextView.setOnClickListener { openOptionsMenu(link) } shareTextView.setOnClickListener { navigatorApi.shareUrl(link.url) } commentsCountTextView.setOnClickListener {} favoriteButton.isVisible = userManagerApi.isUserAuthorized() favoriteButton.isFavorite = link.userFavorite favoriteButton.setOnClickListener { linkActionListener.markFavorite(link) } } private fun setupBody(link: Link) { titleTextView.text = link.title.removeHtml() image.isVisible = link.preview != null link.preview?.let { image.loadImage(link.preview!!.stripImageCompression()) } description.text = link.description.removeHtml() relatedCountTextView.text = link.relatedCount.toString() relatedCountTextView.setOnClickListener { if (link.relatedCount > 0) { navigatorApi.openLinkRelatedActivity(link.id) } } containerView.setOnClickListener { linkHandlerApi.handleUrl(link.sourceUrl) } } private fun showBurried(link: Link) { link.userVote = "bury" diggCountTextView.isButtonSelected = true diggCountTextView.setVoteState("bury") diggCountTextView.unvoteListener = { linkActionListener.removeVote(link) diggCountTextView.isEnabled = false } diggCountTextView.isEnabled = true } private fun showDigged(link: Link) { link.userVote = "dig" diggCountTextView.isButtonSelected = true diggCountTextView.setVoteState("dig") diggCountTextView.unvoteListener = { linkActionListener.removeVote(link) diggCountTextView.isEnabled = false } diggCountTextView.isEnabled = true } private fun showUnvoted(link: Link) { diggCountTextView.isButtonSelected = false diggCountTextView.setVoteState(null) diggCountTextView.voteListener = { linkActionListener.digLink(link) diggCountTextView.isEnabled = false } link.userVote = null diggCountTextView.isEnabled = true } private fun openOptionsMenu(link: Link) { val activityContext = containerView.getActivityContext()!! val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(activityContext) val bottomSheetView = activityContext.layoutInflater.inflate(R.layout.link_menu_bottomsheet, null) dialog.setContentView(bottomSheetView) bottomSheetView.apply { tvDiggerList.text = resources.getString(R.string.dig_list, link.voteCount) tvBuryList.text = resources.getString(R.string.bury_list, link.buryCount) link_diggers.setOnClickListener { navigatorApi.openLinkUpvotersActivity(link.id) dialog.dismiss() } link_bury_list.setOnClickListener { navigatorApi.openLinkDownvotersActivity(link.id) dialog.dismiss() } link_bury.setOnClickListener { dialog.dismiss() openBuryReasonMenu(link) } link_related.setOnClickListener { if (link.relatedCount > 0) { navigatorApi.openLinkRelatedActivity(link.id) } dialog.dismiss() } link_bury.isVisible = userManagerApi.isUserAuthorized() } val mBehavior = com.google.android.material.bottomsheet.BottomSheetBehavior.from(bottomSheetView.parent as View) dialog.setOnShowListener { mBehavior.peekHeight = bottomSheetView.height } dialog.show() } private fun openBuryReasonMenu(link: Link) { val activityContext = containerView.getActivityContext()!! val dialog = com.google.android.material.bottomsheet.BottomSheetDialog(activityContext) val bottomSheetView = activityContext.layoutInflater.inflate(R.layout.link_bury_menu_bottomsheet, null) dialog.setContentView(bottomSheetView) bottomSheetView.apply { reason_duplicate.setOnClickListener { linkActionListener.buryLink(link, LinkInteractor.BURY_REASON_DUPLICATE) dialog.dismiss() } reason_spam.setOnClickListener { linkActionListener.buryLink(link, LinkInteractor.BURY_REASON_SPAM) dialog.dismiss() } reason_fake_info.setOnClickListener { linkActionListener.buryLink(link, LinkInteractor.BURY_REASON_FAKE_INFO) dialog.dismiss() } reason_wrong_content.setOnClickListener { linkActionListener.buryLink(link, LinkInteractor.BURY_REASON_WRONG_CONTENT) dialog.dismiss() } reason_unsuitable_content.setOnClickListener { linkActionListener.buryLink(link, LinkInteractor.BURY_REASON_UNSUITABLE_CONTENT) dialog.dismiss() } } val mBehavior = com.google.android.material.bottomsheet.BottomSheetBehavior.from(bottomSheetView.parent as View) dialog.setOnShowListener { mBehavior.peekHeight = bottomSheetView.height } dialog.show() } private fun String.convertToTagsHtml(): String { val html = StringBuilder() split(" ").forEach { html.append("<a href=\"$it\">$it<\\a> ") } return html.toString() } }
47
null
51
166
ec6365b9570818a7ee00c5b512f01cedead30867
9,610
WykopMobilny
MIT License
app/src/main/java/cz/blackchameleon/trendingprojects/framework/local/LocalLanguageSourceImpl.kt
klepackovakarolina
327,316,960
false
null
package cz.blackchameleon.trendingprojects.framework.local import android.content.Context import cz.blackchameleon.data.local.LocalLanguageSource import cz.blackchameleon.domain.Language import cz.blackchameleon.trendingprojects.framework.database.Database import cz.blackchameleon.trendingprojects.framework.database.dao.LanguageDao import cz.blackchameleon.trendingprojects.framework.database.db.LanguageDb /** * Local source implementation for getting language object from DB * Implementation of [LocalLanguageSource] * * @author <NAME> on 29.11.2020. */ class LocalLanguageSourceImpl( context: Context ) : LocalLanguageSource { private val database = Database.getInstance(context) private val languageDao: LanguageDao? init { languageDao = database?.languageDao() } override suspend fun getLanguages(): List<Language>? = languageDao?.getLanguages()?.map { it.toLanguage() } override suspend fun saveLanguage(language: Language) { language.run { languageDao?.insert( LanguageDb( urlParam ?: "", name ) ) } } override suspend fun clean() { languageDao?.deleteAll() } }
0
Kotlin
0
0
43b8ca613f068f06dbc7c8a20569c0788f0bdf39
1,237
trending-projects
MIT License