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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
subprojects/android-test/ui-testing-core/src/main/kotlin/com/avito/android/test/espresso/action/ActionOnLongClickableElement.kt | avito-tech | 230,265,582 | false | null | package com.avito.android.test.espresso.action
import android.view.View
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import com.avito.android.test.matcher.CanBeLongClickedMatcher
import org.hamcrest.Matcher
import org.hamcrest.Matchers
public class ActionOnLongClickableElement(
private val action: ViewAction
) : ViewAction {
override fun getDescription(): String = "${action.description} on long-clickable element"
override fun getConstraints(): Matcher<View> = Matchers.allOf(
CanBeLongClickedMatcher(),
action.constraints
)
override fun perform(uiController: UiController, view: View) {
action.perform(uiController, view)
}
}
| 10 | null | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 722 | avito-android | MIT License |
app/src/main/java/com/personal/tmdb/detail/data/models/CombinedCredits.kt | Avvami | 755,489,313 | false | {"Kotlin": 656155} | package com.personal.tmdb.detail.data.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class CombinedCredits(
@Json(name = "cast")
val cast: List<CombinedCastCrew>?,
@Json(name = "crew")
val crew: List<CombinedCastCrew>?
) | 0 | Kotlin | 0 | 2 | d5b4d2ee9eb9616ab0e217f8d6fff45723bf5e58 | 306 | TMDB | MIT License |
spring/src/test/kotlin/tw/waterballsa/gaas/spring/it/AbstractSpringBootTest.kt | Game-as-a-Service | 623,554,204 | false | null | package tw.waterballsa.gaas.spring.it
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.ResultActions
@SpringBootTest
@AutoConfigureMockMvc
abstract class AbstractSpringBootTest {
@Autowired
lateinit var mockMvc: MockMvc
@Autowired
private lateinit var objectMapper: ObjectMapper
protected fun <T> ResultActions.getBody(type: Class<T>): T =
andReturn().response.contentAsString.let { objectMapper.readValue(it, type) }
protected fun <T> ResultActions.getBody(type: TypeReference<T>): T =
andReturn().response.contentAsString.let { objectMapper.readValue(it, type) }
protected fun Any.toJson(): String = objectMapper.writeValueAsString(this)
}
| 27 | Kotlin | 5 | 22 | b117145d1841ee3ade37993c52ff8bec908b2338 | 1,049 | Lobby-Platform-Service | Apache License 2.0 |
ddd/src/main/kotlin/net/rikarin/multitenancy/CurrentTenantAccessor.kt | Rikarin | 586,107,122 | false | null | package net.rikarin.multitenancy
interface CurrentTenantAccessor {
var current: TenantInfo?
}
| 0 | Kotlin | 0 | 0 | ae49fd70b3a46c5e74e161758f6e7eeaed08ed88 | 99 | kotlin | MIT License |
packages/expo-battery/android/src/main/java/expo/modules/battery/BatteryModule.kt | betomoedano | 462,599,485 | false | null | package expo.modules.battery
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import org.unimodules.core.ExportedModule
import org.unimodules.core.ModuleRegistry
import org.unimodules.core.Promise
import org.unimodules.core.interfaces.ExpoMethod
import org.unimodules.core.interfaces.RegistryLifecycleListener
import org.unimodules.core.interfaces.services.EventEmitter
class BatteryModule(context: Context) : ExportedModule(context), RegistryLifecycleListener {
private val NAME = "ExpoBattery"
enum class BatteryState(val value: Int) {
UNKNOWN(0), UNPLUGGED(1), CHARGING(2), FULL(3);
}
override fun getName(): String {
return NAME
}
override fun getConstants(): Map<String, Any> {
return hashMapOf("isSupported" to true)
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
val eventEmitter = moduleRegistry.getModule(EventEmitter::class.java)
context.registerReceiver(BatteryStateReceiver(eventEmitter), IntentFilter(Intent.ACTION_BATTERY_CHANGED))
context.registerReceiver(PowerSaverReceiver(eventEmitter), IntentFilter("android.os.action.POWER_SAVE_MODE_CHANGED"))
val ifilter = IntentFilter().apply {
addAction(Intent.ACTION_BATTERY_LOW)
addAction(Intent.ACTION_BATTERY_OKAY)
}
context.registerReceiver(BatteryLevelReceiver(eventEmitter), ifilter)
}
@ExpoMethod
fun getBatteryLevelAsync(promise: Promise) {
val batteryIntent: Intent? = context.applicationContext.registerReceiver(null,
IntentFilter(Intent.ACTION_BATTERY_CHANGED))
if (batteryIntent == null) {
promise.resolve(-1)
return
}
val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryLevel = if (level != -1 && scale != -1) {
level / scale.toFloat()
} else {
-1f
}
promise.resolve(batteryLevel)
}
@ExpoMethod
fun getBatteryStateAsync(promise: Promise) {
val batteryIntent: Intent? = context.applicationContext.registerReceiver(null,
IntentFilter(Intent.ACTION_BATTERY_CHANGED))
if (batteryIntent == null) {
promise.resolve(BatteryState.UNKNOWN.value)
return
}
val status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
promise.resolve(batteryStatusNativeToJS(status).value)
}
@ExpoMethod
fun isLowPowerModeEnabledAsync(promise: Promise) {
promise.resolve(isLowPowerModeEnabled)
}
@ExpoMethod
fun isBatteryOptimizationEnabledAsync(promise: Promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val packageName: String = context.applicationContext.packageName
val powerManager = context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager?
if (powerManager != null && !powerManager.isIgnoringBatteryOptimizations(packageName)) {
promise.resolve(true)
return
}
}
promise.resolve(false)
}
// We default to false on web and any future platforms that haven't been
// implemented yet
private val isLowPowerModeEnabled: Boolean
get() {
val powerManager = context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager // We default to false on web and any future platforms that haven't been
// implemented yet
?: return false
return powerManager.isPowerSaveMode
}
}
| 627 | null | 4443 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 3,531 | expo | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/ListDropdown.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
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.straight.Icons
public val Icons.Bold.ListDropdown: ImageVector
get() {
if (_listDropdown != null) {
return _listDropdown!!
}
_listDropdown = Builder(name = "ListDropdown", 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(20.5f, 0.0f)
lineTo(3.5f, 0.0f)
curveTo(1.57f, 0.0f, 0.0f, 1.57f, 0.0f, 3.5f)
lineTo(0.0f, 24.0f)
lineTo(24.0f, 24.0f)
lineTo(24.0f, 3.5f)
curveToRelative(0.0f, -1.93f, -1.57f, -3.5f, -3.5f, -3.5f)
close()
moveTo(20.0f, 3.0f)
lineToRelative(-2.76f, 2.71f)
curveToRelative(-0.39f, 0.39f, -1.01f, 0.39f, -1.4f, 0.0f)
lineToRelative(-2.76f, -2.71f)
horizontalLineToRelative(6.91f)
close()
moveTo(3.0f, 21.0f)
lineTo(3.0f, 8.0f)
lineTo(21.0f, 8.0f)
verticalLineToRelative(13.0f)
lineTo(3.0f, 21.0f)
close()
moveTo(5.0f, 15.0f)
horizontalLineToRelative(14.0f)
verticalLineToRelative(3.0f)
lineTo(5.0f, 18.0f)
verticalLineToRelative(-3.0f)
close()
moveTo(5.0f, 10.0f)
horizontalLineToRelative(14.0f)
verticalLineToRelative(3.0f)
lineTo(5.0f, 13.0f)
verticalLineToRelative(-3.0f)
close()
}
}
.build()
return _listDropdown!!
}
private var _listDropdown: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,534 | icons | MIT License |
src/domain/shelter/src/main/kotlin/yapp.be.domain/port/inbound/shelter/GetShelterUseCase.kt | YAPP-Github | 634,126,325 | false | null | package yapp.be.domain.port.inbound.shelter
import yapp.be.domain.model.Shelter
import yapp.be.domain.model.ShelterOutLink
import yapp.be.domain.model.dto.ShelterDto
interface GetShelterUseCase {
fun getShelterById(shelterId: Long): Shelter
fun getNonMemberShelterInfoById(shelterId: Long): ShelterDto
fun getMemberShelterInfoByIdAndVolunteerId(shelterId: Long, volunteerId: Long): ShelterDto
fun getShelterOutLinkByShelterId(shelterId: Long): List<ShelterOutLink>
}
| 5 | Kotlin | 1 | 5 | 4b7cba48a16e0ec305ddea49d278c99200cce11c | 486 | DangleDangle-server | Apache License 2.0 |
arsceneview/src/main/java/io/github/sceneview/ar/node/ArNode.kt | rbf1222 | 671,468,043 | false | null | package io.github.sceneview.ar.node
import com.google.ar.core.*
import com.google.ar.core.Anchor.CloudAnchorState
import com.google.ar.core.Config.PlaneFindingMode
import com.google.ar.sceneform.math.Vector3
import dev.romainguy.kotlin.math.*
import io.github.sceneview.*
import io.github.sceneview.ar.ArSceneLifecycle
import io.github.sceneview.ar.ArSceneLifecycleObserver
import io.github.sceneview.ar.ArSceneView
import io.github.sceneview.ar.arcore.*
import io.github.sceneview.node.ModelNode
open class ArNode() : ModelNode(), ArSceneLifecycleObserver {
override val sceneView: ArSceneView? get() = super.sceneView as? ArSceneView
override val lifecycle: ArSceneLifecycle? get() = sceneView?.lifecycle
protected val arSession: ArSession? get() = sceneView?.arSession
/**
* TODO : Doc
*/
open val isTracking get() = pose != null
/**
* ### Move smoothly/slowly when there is a pose (AR position and rotation) update
*
* Use [smoothSpeed] to adjust the position and rotation change smoothness level
*/
var isSmoothPoseEnable = true
/**
* ### Adjust the anchor pose update interval in seconds
*
* ARCore may update the [anchor] pose because of environment detection evolving during time.
* You can choose to retrieve more accurate anchor position and rotation or let it as it was
* when it was anchored.
* Only used when the [ArNode] is anchored.
* `null` means never update the pose
*/
var anchorPoseUpdateInterval: Double? = null
var anchorUpdateFrame: ArFrame? = null
private set
/**
* ### The position of the intersection between a ray and detected real-world geometry.
*
* The position is the location in space where the ray intersected the geometry.
* The orientation is a best effort to face the user's device, and its exact definition differs
* depending on the Trackable that was hit.
*
* - [Plane]: X+ is perpendicular to the cast ray and parallel to the plane, Y+ points along the
* plane normal (up, for [Plane.Type.HORIZONTAL_UPWARD_FACING] planes), and Z+ is parallel to
* the plane, pointing roughly toward the user's device.
*
* - [Point]: Attempt to estimate the normal of the surface centered around the hit test.
* Surface normal estimation is most likely to succeed on textured surfaces and with camera
* motion. If [Point.getOrientationMode] returns
* [Point.OrientationMode.ESTIMATED_SURFACE_NORMAL], then X+ is perpendicular to the cast ray
* and parallel to the physical surface centered around the hit test, Y+ points along the
* estimated surface normal, and Z+ points roughly toward the user's device.
* If [Point.getOrientationMode] returns [Point.OrientationMode.INITIALIZED_TO_IDENTITY], then
* X+ is perpendicular to the cast ray and points right from the perspective of the user's
* device, Y+ points up, and Z+ points roughly toward the user's device.
*
* - If you wish to retain the location of this pose beyond the duration of a single frame,
* create an [Anchor] using [createAnchor] to save the pose in a physically consistent way.
*
* @see createAnchor
*/
open var pose: Pose? = null
set(value) {
val position = value?.position
val quaternion = value?.quaternion
if (position != field?.position || quaternion != field?.quaternion) {
field = value
if (position != null && quaternion != null) {
if (isSmoothPoseEnable) {
smooth(position = position, quaternion = quaternion)
} else {
transform(position = position, quaternion = quaternion)
}
}
onPoseChanged(value)
}
}
/**
* TODO : Doc
*/
val isAnchored get() = anchor != null
/**
* TODO : Doc
*/
var anchor: Anchor? = null
set(value) {
field?.detach()
field = value
pose = value?.pose
onAnchorChanged(value)
}
/**
* ### The current cloud anchor state of the [anchor].
*/
val cloudAnchorState: CloudAnchorState
get() = anchor?.cloudAnchorState ?: CloudAnchorState.NONE
/**
* ### Whether a Cloud Anchor is currently being hosted or resolved
*/
var cloudAnchorTaskInProgress = false
private set
/** ## Deprecated: Use [onPoseChanged] and [isTracking] */
@Deprecated(
"Replaced by onPoseChanged",
replaceWith = ReplaceWith("onPoseChanged"),
DeprecationLevel.ERROR
)
var onTrackingChanged: ((node: ArNode, isTracking: Boolean, pose: Pose?) -> Unit)? = null
var onPoseChanged: ((node: ArNode, pose: Pose?) -> Unit)? = null
var onAnchorChanged: ((node: ArNode, anchor: Anchor?) -> Unit)? = null
private var onCloudAnchorTaskCompleted: ((anchor: Anchor, success: Boolean) -> Unit)? = null
open val isEditable: Boolean
get() = editableTransforms.isNotEmpty()
open var editableTransforms: Set<EditableTransform> = EditableTransform.ALL
/**
* ### How/where does the node is positioned in the real world
*
* Depending on your need, you can change it to adjust between a quick
* ([PlacementMode.INSTANT]), more accurate ([PlacementMode.DEPTH]), only on planes/walls
* ([PlacementMode.PLANE_HORIZONTAL], [PlacementMode.PLANE_VERTICAL],
* [PlacementMode.PLANE_HORIZONTAL_AND_VERTICAL]) or auto refining accuracy
* ([PlacementMode.BEST_AVAILABLE]) placement.
* The [hitTest], [pose] and [anchor] will be influenced by this choice.
*/
var placementMode: PlacementMode = DEFAULT_PLACEMENT_MODE
set(value) {
field = value
doOnAttachedToScene { sceneView ->
(sceneView as? ArSceneView)?.apply {
planeFindingMode = value.planeFindingMode
depthEnabled = value.depthEnabled
instantPlacementEnabled = value.instantPlacementEnabled
}
}
}
/**
* TODO : Doc
*/
constructor(placementMode: PlacementMode) : this() {
this.placementMode = placementMode
}
/**
* TODO : Doc
*/
constructor(anchor: Anchor) : this() {
this.anchor = anchor
}
override fun onArFrame(arFrame: ArFrame) {
val anchor = anchor ?: return
// Update the anchor position if any
if (anchor.trackingState == TrackingState.TRACKING) {
if (anchorPoseUpdateInterval != null
&& arFrame.intervalSeconds(anchorUpdateFrame) >= anchorPoseUpdateInterval!!
) {
pose = anchor.pose
anchorUpdateFrame = arFrame
}
}
if (cloudAnchorTaskInProgress) {
// Call the listener when the task completes successfully or with an error
if (cloudAnchorState != CloudAnchorState.NONE &&
cloudAnchorState != CloudAnchorState.TASK_IN_PROGRESS
) {
cloudAnchorTaskInProgress = false
onCloudAnchorTaskCompleted?.invoke(
anchor,
cloudAnchorState == CloudAnchorState.SUCCESS
)
onCloudAnchorTaskCompleted = null
}
}
}
/**
* TODO : Doc
*/
open fun onPoseChanged(pose: Pose?) {
onPoseChanged?.invoke(this, pose)
}
/**
* TODO : Doc
*/
open fun onAnchorChanged(anchor: Anchor?) {
onAnchorChanged?.invoke(this, anchor)
}
/**
* ### Performs a ray cast to retrieve the ARCore info at this camera point
*
* @param frame the [ArFrame] from where we take the [HitResult]
* By default the latest session frame if any exist
* @param xPx x view coordinate in pixels
* By default the [cameraPosition.x][placementPosition] of this Node is used
* @property yPx y view coordinate in pixels
* By default the [cameraPosition.y][placementPosition] of this Node is used
*
* @return the hitResult or null if no info is retrieved
*
* @see ArFrame.hitTest
*/
fun hitTest(
frame: ArFrame? = arSession?.currentFrame,
xPx: Float,
yPx: Float,
approximateDistanceMeters: Float = placementMode.instantPlacementDistance,
plane: Boolean = placementMode.planeEnabled,
depth: Boolean = placementMode.depthEnabled,
instantPlacement: Boolean = placementMode.instantPlacementEnabled
): HitResult? =
frame?.hitTest(xPx, yPx, approximateDistanceMeters, plane, depth, instantPlacement)
/**
* ### Creates a new anchor at actual node worldPosition and worldRotation (hit location)
*
* Creates an anchor at the given pose in the world coordinate space that is attached to this
* trackable. The type of trackable will determine the semantics of attachment and how the
* anchor's pose will be updated to maintain this relationship. Note that the relative offset
* between the pose of multiple anchors attached to a trackable may adjust slightly over time as
* ARCore updates its model of the world.
*
* Anchors incur ongoing processing overhead within ARCore. To release unneeded anchors use
* [Anchor.detach]
*/
open fun createAnchor(): Anchor? = null
/**
* ### Anchor this node to make it fixed at the actual position and orientation is the world
*
* Creates an anchor at the given pose in the world coordinate space that is attached to this
* trackable. The type of trackable will determine the semantics of attachment and how the
* anchor's pose will be updated to maintain this relationship. Note that the relative offset
* between the pose of multiple anchors attached to a trackable may adjust slightly over time as
* ARCore updates its model of the world.
*/
open fun anchor(): Boolean {
anchor = createAnchor()
return anchor != null
}
/**
* ### Anchor this node to make it fixed at the actual position and orientation is the world
*
* Creates an anchor at the given pose in the world coordinate space that is attached to this
* trackable. The type of trackable will determine the semantics of attachment and how the
* anchor's pose will be updated to maintain this relationship. Note that the relative offset
* between the pose of multiple anchors attached to a trackable may adjust slightly over time as
* ARCore updates its model of the world.
*/
open fun detachAnchor() {
anchor = null
}
/**
* ### Hosts a Cloud Anchor based on the [anchor]
*
* The [anchor] is replaced with a new anchor returned by [Session.hostCloudAnchorWithTtl].
*
* @param ttlDays The lifetime of the anchor in days. See [Session.hostCloudAnchorWithTtl] for more details.
* @param onTaskCompleted Called when the task completes successfully or with an error.
*/
fun hostCloudAnchor(
ttlDays: Int = 1,
onTaskCompleted: (anchor: Anchor, success: Boolean) -> Unit
) {
if (cloudAnchorTaskInProgress) throw IllegalStateException("The task is already in progress")
if (anchor == null) throw IllegalStateException("The anchor shouldn't be null")
anchor = arSession?.hostCloudAnchorWithTtl(anchor, ttlDays)
cloudAnchorTaskInProgress = true
onCloudAnchorTaskCompleted = onTaskCompleted
}
/**
* ### Resolves a Cloud Anchor
*
* The [anchor] is replaced with a new anchor returned by [Session.resolveCloudAnchor].
*
* @param cloudAnchorId The Cloud Anchor ID of the Cloud Anchor.
* @param onTaskCompleted Called when the task completes successfully or with an error.
*/
fun resolveCloudAnchor(
cloudAnchorId: String,
onTaskCompleted: (anchor: Anchor, success: Boolean) -> Unit
) {
if (cloudAnchorTaskInProgress) throw IllegalStateException("The task is already in progress")
anchor = arSession?.resolveCloudAnchor(cloudAnchorId)
cloudAnchorTaskInProgress = true
onCloudAnchorTaskCompleted = onTaskCompleted
}
/**
* ### Cancels a resolve task
*
* The [anchor] is detached to cancel the resolve task.
*/
fun cancelCloudAnchorResolveTask() {
if (cloudAnchorTaskInProgress) {
anchor?.detach()
cloudAnchorTaskInProgress = false
onCloudAnchorTaskCompleted = null
}
}
/**
* ### Creates a new anchored Node at the actual worldPosition and worldRotation
*
* The returned node position and rotation will be fixed within camera movements.
*
* See [ArFrame.hitTest] and [ArFrame.hitTests] for details.
*
* Anchors incur ongoing processing overhead within ARCore.
* To release unneeded anchors use [destroy].
*/
open fun createAnchoredNode(): ArNode? {
return createAnchor()?.let { anchor ->
ArNode(anchor)
}
}
/**
* TODO: Doc
*/
open fun createAnchoredCopy(): ArNode? {
return createAnchoredNode()?.apply {
copy(this)
}
}
override fun destroy() {
anchor?.detach()
anchor = null
cloudAnchorTaskInProgress = false
onCloudAnchorTaskCompleted = null
super.destroy()
}
//TODO : Move all those functions
/**
* ### Converts a point in the local-space of this node to world-space.
*
* @param point the point in local-space to convert
* @return a new vector that represents the point in world-space
*/
fun localToWorldPosition(point: Vector3) = transformationMatrix.transformPoint(point)
/**
* ### Converts a point in world-space to the local-space of this node.
*
* @param point the point in world-space to convert
* @return a new vector that represents the point in local-space
*/
fun worldToLocalPosition(point: Vector3) = transformationMatrixInverted.transformPoint(point)
/**
* ### Converts a direction from the local-space of this node to world-space.
*
* Not impacted by the position or scale of the node.
*
* @param direction the direction in local-space to convert
* @return a new vector that represents the direction in world-space
*/
// fun localToWorldDirection(direction: Vector3) =
// Quaternion.rotateVector(worldQuaternion, direction)
/**
* ### Converts a direction from world-space to the local-space of this node.
*
* Not impacted by the position or scale of the node.
*
* @param direction the direction in world-space to convert
* @return a new vector that represents the direction in local-space
*/
// fun worldToLocalDirection(direction: Vector3) =
// Quaternion.inverseRotateVector(worldQuaternion, direction)
/** ### Gets the world-space forward direction vector (-z) of this node */
// val worldForward get() = localToWorldDirection(Vector3.forward())
/** ### Gets the world-space back direction vector (+z) of this node */
// val worldBack get() = localToWorldDirection(Vector3.back())
/** ### Gets the world-space right direction vector (+x) of this node */
// val worldRight get() = localToWorldDirection(Vector3.right())
/** ### Gets the world-space left direction vector (-x) of this node */
// val worldLeft get() = localToWorldDirection(Vector3.left())
/** ### Gets the world-space up direction vector (+y) of this node */
// val worldUp get() = localToWorldDirection(Vector3.up())
/** ### Gets the world-space down direction vector (-y) of this node */
// val worldDown get() = localToWorldDirection(Vector3.down())
override fun clone() = copy(ArNode())
fun copy(toNode: ArNode = ArNode()) = toNode.apply {
super.copy(toNode)
placementMode = [email protected]
}
companion object {
val DEFAULT_PLACEMENT_MODE = PlacementMode.BEST_AVAILABLE
val DEFAULT_PLACEMENT_DISTANCE = 2.0f
}
}
/**
* # How an object is placed on the real world
*
* @param instantPlacementDistance Distance in meters at which to create an InstantPlacementPoint.
* This is only used while the tracking method for the returned point is InstantPlacementPoint.
* @param instantPlacementFallback Fallback to instantly place nodes at a fixed orientation and an
* approximate distance when the base placement type is not available yet or at all.
*/
enum class PlacementMode(
var instantPlacementDistance: Float = ArNode.DEFAULT_PLACEMENT_DISTANCE,
var instantPlacementFallback: Boolean = false
) {
/**
* ### Disable every AR placement
* @see PlaneFindingMode.DISABLED
*/
DISABLED,
/**
* ### Place and orientate nodes only on horizontal planes
* @see PlaneFindingMode.HORIZONTAL
*/
PLANE_HORIZONTAL,
/**
* ### Place and orientate nodes only on vertical planes
* @see PlaneFindingMode.VERTICAL
*/
PLANE_VERTICAL,
/**
* ### Place and orientate nodes on both horizontal and vertical planes
* @see PlaneFindingMode.HORIZONTAL_AND_VERTICAL
*/
PLANE_HORIZONTAL_AND_VERTICAL,
/**
* ### Place and orientate nodes on every detected depth surfaces
*
* Not all devices support this mode. In case on non depth enabled device the placement mode
* will automatically fallback to [PLANE_HORIZONTAL_AND_VERTICAL].
* @see Config.DepthMode.AUTOMATIC
*/
DEPTH,
/**
* ### Instantly place only nodes at a fixed orientation and an approximate distance
*
* No AR orientation will be provided = fixed +Y pointing upward, against gravity
*
* This mode is currently intended to be used with hit tests against horizontal surfaces.
* Hit tests may also be performed against surfaces with any orientation, however:
* - The resulting Instant Placement point will always have a pose with +Y pointing upward,
* against gravity.
* - No guarantees are made with respect to orientation of +X and +Z. Specifically, a hit
* test against a vertical surface, such as a wall, will not result in a pose that's in any
* way aligned to the plane of the wall, other than +Y being up, against gravity.
* - The [InstantPlacementPoint]'s tracking method may never become
* [InstantPlacementPoint.TrackingMethod.FULL_TRACKING] } or may take a long time to reach
* this state. The tracking method remains
* [InstantPlacementPoint.TrackingMethod.SCREENSPACE_WITH_APPROXIMATE_DISTANCE] until a
* (tiny) horizontal plane is fitted at the point of the hit test.
*/
INSTANT,
/**
* ### Place nodes on every detected surfaces
*
* The node will be placed instantly and then adjusted to fit the best accurate, precise,
* available placement.
*/
BEST_AVAILABLE(instantPlacementFallback = true);
val planeEnabled: Boolean
get() = when (planeFindingMode) {
PlaneFindingMode.HORIZONTAL,
PlaneFindingMode.VERTICAL,
PlaneFindingMode.HORIZONTAL_AND_VERTICAL -> true
else -> false
}
val planeFindingMode: PlaneFindingMode
get() = when (this) {
PLANE_HORIZONTAL -> PlaneFindingMode.HORIZONTAL
PLANE_VERTICAL -> PlaneFindingMode.VERTICAL
PLANE_HORIZONTAL_AND_VERTICAL,
BEST_AVAILABLE -> PlaneFindingMode.HORIZONTAL_AND_VERTICAL
else -> PlaneFindingMode.DISABLED
}
val depthEnabled: Boolean
get() = when (this) {
DEPTH, BEST_AVAILABLE -> true
else -> false
}
val instantPlacementEnabled: Boolean
get() = when {
this == INSTANT || instantPlacementFallback -> true
else -> false
}
}
enum class EditableTransform {
POSITION, ROTATION, SCALE;
companion object {
val ALL = setOf(POSITION, ROTATION, SCALE)
val NONE = setOf<EditableTransform>()
}
}
| 1 | null | 1 | 1 | d537fea9a47bff39f79b93fadc20cafb321d65fd | 20,367 | sceneview-android | Apache License 2.0 |
app/src/test/java/com/blackcrowsys/ui/splash/SplashActivityViewModelTest.kt | blackcrowsys | 116,029,789 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "JSON": 2, "Kotlin": 80, "XML": 29, "Java": 1} | package com.blackcrowsys.ui.splash
import android.arch.lifecycle.Observer
import com.blackcrowsys.R
import com.blackcrowsys.exceptions.ErrorMapper
import com.blackcrowsys.exceptions.ExceptionTransformer
import com.blackcrowsys.util.SchedulerProvider
import com.blackcrowsys.util.SharedPreferencesHandler
import com.blackcrowsys.util.ViewState
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
/**
* Unit test for [SplashActivityViewModel].
*/
@RunWith(RobolectricTestRunner::class)
class SplashActivityViewModelTest {
@Mock
private lateinit var mockSharedPreferencesHandler: SharedPreferencesHandler
@Mock
private lateinit var observer: Observer<ViewState>
private val schedulerProvider =
SchedulerProvider(Schedulers.trampoline(), Schedulers.trampoline())
private lateinit var splashActivityViewModel: SplashActivityViewModel
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val exceptionTransformer = ExceptionTransformer(ErrorMapper(RuntimeEnvironment.application))
splashActivityViewModel =
SplashActivityViewModel(
schedulerProvider,
mockSharedPreferencesHandler,
exceptionTransformer
)
splashActivityViewModel.viewStateResponse.observeForever(observer)
}
@Test
fun `findPinHash when hash exists in Shared Prefs`() {
`when`(mockSharedPreferencesHandler.getPinHash()).thenReturn(Observable.just("AiaskskASKjdkjA"))
splashActivityViewModel.findPinHash()
val viewStateSuccess =
splashActivityViewModel.viewStateResponse.value as ViewState.Success<*>
assertEquals(viewStateSuccess.data, "AiaskskASKjdkjA")
verify(observer).onChanged(ViewState.Success("AiaskskASKjdkjA"))
}
@Test
fun `findPinHash when hash does not exist in Shared Prefs`() {
`when`(mockSharedPreferencesHandler.getPinHash()).thenReturn(Observable.just(""))
splashActivityViewModel.findPinHash()
val viewStateError = splashActivityViewModel.viewStateResponse.value as ViewState.Error
assertEquals(
viewStateError.throwable.message,
RuntimeEnvironment.application.getString(R.string.no_pin_has_been_set_error)
)
}
} | 1 | Kotlin | 0 | 1 | 0610d1474ea83b7b16e9811111e6946ea983d32c | 2,668 | dinewell-carehome-app | MIT License |
libnavigation-core/src/test/java/com/mapbox/navigation/core/trip/session/TripSessionLocationEngineTest.kt | mapbox | 87,455,763 | false | {"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624} | package com.mapbox.navigation.core.trip.session
import android.os.Looper
import com.mapbox.bindgen.ExpectedFactory
import com.mapbox.common.Cancelable
import com.mapbox.common.location.DeviceLocationProvider
import com.mapbox.common.location.DeviceLocationProviderFactory
import com.mapbox.common.location.Location
import com.mapbox.common.location.LocationError
import com.mapbox.common.location.LocationErrorCode
import com.mapbox.common.location.LocationProvider
import com.mapbox.common.location.LocationProviderRequest
import com.mapbox.common.location.LocationService
import com.mapbox.common.location.LocationServiceFactory
import com.mapbox.navigation.base.options.LocationOptions
import com.mapbox.navigation.core.replay.ReplayLocationProvider
import com.mapbox.navigation.testing.LoggingFrontendTestRule
import com.mapbox.navigation.utils.internal.LoggerFrontend
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkStatic
import io.mockk.verify
import io.mockk.verifyOrder
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class TripSessionLocationEngineTest {
private val logger = mockk<LoggerFrontend>(relaxed = true)
@get:Rule
val loggerRule = LoggingFrontendTestRule(logger)
private val defaultDeviceLocationProvider = mockk<DeviceLocationProvider>(relaxed = true).also {
mockLocationProvider(it)
}
private val replayLocationProvider = mockk<ReplayLocationProvider>(relaxed = true).also {
mockLocationProvider(it)
}
private val locationOptions = LocationOptions.Builder().build()
private val locationService = mockk<LocationService>(relaxUnitFun = true) {
every {
getDeviceLocationProvider(any<LocationProviderRequest>())
} returns ExpectedFactory.createValue(defaultDeviceLocationProvider)
}
private lateinit var sut: TripSessionLocationEngine
@Before
fun setUp() {
mockkStatic(LocationServiceFactory::class)
every { LocationServiceFactory.getOrCreate() } returns locationService
}
@After
fun tearDown() {
unmockkStatic(LocationServiceFactory::class)
}
@Test
fun `should request location updates from navigation options when replay is disabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verify(exactly = 1) {
defaultDeviceLocationProvider.addLocationObserver(any(), any())
}
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
}
}
@Test
fun `should not request location updates from navigation options when error is returned`() {
every { LocationServiceFactory.getOrCreate() } returns mockk {
every {
getDeviceLocationProvider(any<LocationProviderRequest>())
} returns ExpectedFactory.createError(
LocationError(LocationErrorCode.FAILED_TO_DETECT_LOCATION, "Some error"),
)
}
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verify(exactly = 0) {
defaultDeviceLocationProvider.addLocationObserver(any(), any())
}
verify(exactly = 1) {
logger.logW(
"TripSessionLocationEngine",
"Location updates are not possible: " +
"could not find suitable location provider. " +
"Error code: FailedToDetectLocation, " +
"message: Some error.",
)
}
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
}
}
@Test
fun `should request location updates from custom real provider when replay is disabled`() {
val customLocationProvider = mockk<DeviceLocationProvider>(relaxed = true)
val customLocationProviderFactory = DeviceLocationProviderFactory {
ExpectedFactory.createValue(customLocationProvider)
}
every {
locationService.getDeviceLocationProvider(any<LocationProviderRequest>())
} returns ExpectedFactory.createValue(customLocationProvider)
val locationOptions = LocationOptions.Builder()
.locationProviderFactory(
customLocationProviderFactory,
LocationOptions.LocationProviderType.REAL,
)
.build()
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verifyOrder {
locationService.setUserDefinedDeviceLocationProviderFactory(
customLocationProviderFactory,
)
locationService.getDeviceLocationProvider(any<LocationProviderRequest>())
}
verify(exactly = 1) {
customLocationProvider.addLocationObserver(any(), not(Looper.getMainLooper()))
}
}
@Test
fun `should request location updates from custom mocked provider when replay is disabled`() {
val customLocationProvider = mockk<DeviceLocationProvider>(relaxed = true)
val customLocationProviderFactory = DeviceLocationProviderFactory {
ExpectedFactory.createValue(customLocationProvider)
}
val locationOptions = LocationOptions.Builder()
.locationProviderFactory(
customLocationProviderFactory,
LocationOptions.LocationProviderType.MOCKED,
)
.build()
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
locationService.getDeviceLocationProvider(any<LocationProviderRequest>())
}
verify(exactly = 1) {
customLocationProvider.addLocationObserver(any(), not(Looper.getMainLooper()))
}
}
@Test
fun `should request location updates from custom mixed provider when replay is disabled`() {
val customLocationProvider = mockk<DeviceLocationProvider>(relaxed = true)
val customLocationProviderFactory = DeviceLocationProviderFactory {
ExpectedFactory.createValue(customLocationProvider)
}
val locationOptions = LocationOptions.Builder()
.locationProviderFactory(
customLocationProviderFactory,
LocationOptions.LocationProviderType.MIXED,
)
.build()
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
locationService.getDeviceLocationProvider(any<LocationProviderRequest>())
}
verify(exactly = 1) {
customLocationProvider.addLocationObserver(any(), not(Looper.getMainLooper()))
}
}
@Test
fun `should stop location updates from navigation options when replay is disabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
sut.stopLocationUpdates()
verifyOrder {
defaultDeviceLocationProvider.addLocationObserver(any(), any())
defaultDeviceLocationProvider.removeLocationObserver(any())
}
}
@Test
fun `should not request location updates from replay engine when replay is disabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
verify(exactly = 0) {
replayLocationProvider.addLocationObserver(any(), any())
}
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
}
}
@Test
fun `should request location updates from replay engine when replay is enabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
verify(exactly = 1) {
replayLocationProvider.addLocationObserver(any(), not(Looper.getMainLooper()))
}
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
}
}
@Test
fun `should stop location updates from replay engine when replay is enabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
sut.stopLocationUpdates()
verifyOrder {
replayLocationProvider.addLocationObserver(any(), any())
replayLocationProvider.removeLocationObserver(any())
}
}
@Test
fun `should clean up last location from replay engine when replay is enabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
sut.stopLocationUpdates()
verify { replayLocationProvider.cleanUpLastLocation() }
}
@Test
fun `should not clean up last location from replay engine when replay is disabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(false, onRawLocationUpdate)
sut.stopLocationUpdates()
verify(exactly = 0) { replayLocationProvider.cleanUpLastLocation() }
}
@Test
fun `should not request location updates from navigation options when replay is enabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
verify(exactly = 0) {
defaultDeviceLocationProvider.addLocationObserver(any(), any())
}
verify(exactly = 0) {
locationService.setUserDefinedDeviceLocationProviderFactory(any())
}
}
@Test
fun `should remove location updates from previous location engine`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
verify(exactly = 0) {
defaultDeviceLocationProvider.addLocationObserver(any(), any())
}
}
@Test
fun `startLocationUpdates should remove updates from previous location engine`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val onRawLocationUpdate: (Location) -> Unit = mockk()
sut.startLocationUpdates(true, onRawLocationUpdate)
sut.startLocationUpdates(false, onRawLocationUpdate)
sut.startLocationUpdates(true, onRawLocationUpdate)
verifyOrder {
replayLocationProvider.addLocationObserver(any(), any())
replayLocationProvider.removeLocationObserver(any())
defaultDeviceLocationProvider.addLocationObserver(any(), any())
defaultDeviceLocationProvider.removeLocationObserver(any())
replayLocationProvider.addLocationObserver(any(), any())
}
}
@Test
fun `isReplayEnabled is true after replay is enabled`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
sut.startLocationUpdates(true, mockk())
assertTrue(sut.isReplayEnabled)
}
@Test
fun `isReplayEnabled is false when replay is disabled for location updates`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
sut.startLocationUpdates(false, mockk())
assertFalse(sut.isReplayEnabled)
}
@Test
fun `isReplayEnabled is false after stopLocationUpdates`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
sut.startLocationUpdates(true, mockk())
sut.stopLocationUpdates()
assertFalse(sut.isReplayEnabled)
}
@Test
fun `should cancel last location task when updates are stopped`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
val firstCallback = mockk<(Location) -> Unit>(relaxed = true)
val locationTask = mockk<Cancelable>(relaxed = true)
every { replayLocationProvider.getLastLocation(any()) } returns locationTask
sut.startLocationUpdates(true, firstCallback)
verify {
replayLocationProvider.getLastLocation(any())
}
sut.stopLocationUpdates()
verify { locationTask.cancel() }
}
@Test
fun `should unsets custom location provider factory`() {
sut = TripSessionLocationEngine(locationOptions) {
replayLocationProvider
}
clearAllMocks(answers = false)
sut.destroy()
verify(exactly = 1) {
locationService.setUserDefinedDeviceLocationProviderFactory(null)
}
}
private fun mockLocationProvider(locationProvider: LocationProvider) {
val locationObserverSlot = slot<com.mapbox.common.location.LocationObserver>()
every {
locationProvider.addLocationObserver(
capture(locationObserverSlot),
any(),
)
} answers {}
}
}
| 508 | Kotlin | 318 | 621 | 88163ae3d7e34948369d6945d5b78a72bdd68d7c | 15,173 | mapbox-navigation-android | Apache License 2.0 |
common/common-ui/src/main/java/com/duckduckgo/common/ui/view/divider/VerticalDivider.kt | duckduckgo | 78,869,127 | false | {"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784} | /*
* Copyright (c) 2022 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.mobile.android.ui.view.divider
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.duckduckgo.mobile.android.R
import com.duckduckgo.mobile.android.databinding.ViewVerticalDividerBinding
import com.duckduckgo.mobile.android.ui.viewbinding.viewBinding
class VerticalDivider @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding: ViewVerticalDividerBinding by viewBinding()
init {
val typedArray =
context.obtainStyledAttributes(
attrs,
R.styleable.VerticalDivider,
0,
R.style.Widget_DuckDuckGo_VerticalDivider
)
val defaultPadding = typedArray.getBoolean(R.styleable.VerticalDivider_defaultPadding, false)
val sidePadding = if (defaultPadding) {
resources.getDimensionPixelOffset(R.dimen.verticalDividerSidePadding)
} else {
0
}
binding.root.setPadding(sidePadding, 0, sidePadding, 0)
typedArray.recycle()
}
}
| 67 | Kotlin | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,798 | Android | Apache License 2.0 |
xesar-connect/src/test/kotlin/com/open200/xesar/connect/testutils/IdentificationMediumFixture.kt | open200 | 684,928,079 | false | {"Kotlin": 438614} | package com.open200.xesar.connect.testutils
import com.open200.xesar.connect.messages.DisengagePeriod
import com.open200.xesar.connect.messages.query.IdentificationMedium
import java.time.LocalDateTime
import java.util.*
object IdentificationMediumFixture {
val identificationMediumFixture =
IdentificationMedium(
id = UUID.fromString("8293e920-90ce-48da-851c-cff54a13e2c6"),
label = "test door",
issuedAt = LocalDateTime.parse("2023-07-05T15:22:13.509825"),
syncedAt = LocalDateTime.parse("2023-07-05T15:22:38.230076"),
authorizationProfileId = UUID.fromString("d08fdd62-bc36-4e47-8bc9-62b603e75ed9"),
authorizationProfileName = "Authorization Profile 1",
validityDuration = 151,
individualAuthorizationProfileIds =
listOf(
UUID.fromString("3dba6935-6904-4bc0-99d3-8115c9bbbedc"),
UUID.fromString("66b9f5d9-5664-4bb9-9546-af315987752b")),
mediumState = "ACTIVE",
accessBeginAt = LocalDateTime.parse("2021-01-01T00:00:00"),
accessEndAt = LocalDateTime.parse("2021-01-01T00:00:00"),
validityBeginAt = LocalDateTime.parse("2021-01-01T00:00:00"),
validityEndAt = LocalDateTime.parse("2021-01-01T00:00:00"),
validityBeginAtInHardware = LocalDateTime.parse("2021-01-01T00:00:00"),
validityEndAtInHardware = LocalDateTime.parse("2021-01-01T00:00:00"),
external = false,
disengagePeriod = DisengagePeriod.SHORT,
mediumIdentifier = 1,
outdated = true,
personId = UUID.fromString("82a8a2cc-5d39-4cfa-b04e-49111a0bcdf7"),
person = "test Person",
hardwareId = "f45ebc226706800e1cf942c995d0a43db78ec563173fb79a43eedbfbd8f29222",
nativeId = "046e0b8a967280",
secure = true,
softwareStatus = "ACTIVE",
hardwareStatus = "ACTIVE",
fitsOnHardware = true,
userId = UUID.fromString("91781b22-ebdf-4ada-80cf-91f1fb9a4d96"),
userName = "test User",
requiredAction = "UPDATE",
mediumType = "PASSIVE")
}
| 18 | Kotlin | 0 | 9 | b23bc36a644f1bf5b94de0324e774365d9cbfa91 | 2,224 | xesar-connect | Apache License 2.0 |
core/model/src/main/java/com/whakaara/model/stopwatch/Lap.kt | ahudson20 | 531,856,934 | false | {"Kotlin": 536307} | package com.whakaara.model.stopwatch
data class Lap(
val time: Long,
val diff: Long
)
| 1 | Kotlin | 3 | 30 | f63a8f59815bec094a6d0c19d0368a87a2b87923 | 95 | whakaara | MIT License |
api-server/src/main/kotlin/com/companimal/member/domain/exception/CannotUseSamePasswordException.kt | roseoutz | 609,769,119 | false | null | package com.companimal.member.domain.exception
import com.companimal.common.domain.exception.CompanimalException
import com.companimal.member.domain.constants.MemberErrorCode
class CannotUseSamePasswordException: CompanimalException(errorCode = MemberErrorCode.SAME_PASSWORD) {
} | 0 | Kotlin | 0 | 0 | e065faa6eedfc95d724cc00dfad3f7ae3488d241 | 281 | companimal | MIT License |
tests/application/src/androidTest/java/dev/enro/test/application/fragment/UnboundBottomSheetTestWithEnroRule.kt | isaac-udy | 256,179,010 | false | {"Kotlin": 1447007} | package dev.enro.test.application.fragment
import androidx.compose.ui.test.ComposeTimeoutException
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import dev.enro.test.EnroTestRule
import dev.enro.tests.application.TestActivity
import dev.enro.tests.application.fragment.UnboundBottomSheetFragment
import org.junit.Rule
import org.junit.Test
/**
* A bug was reported where unbound BottomSheets (i.e. those not opened through Enro directly)
* were not being dismissed correctly when Espresso is used to trigger the back press
*/
class UnboundBottomSheetTestWithEnroRule {
@get:Rule
val enroRule = EnroTestRule()
@get:Rule
val composeRule = createAndroidComposeRule<TestActivity>()
// When the EnroTestRule is active, Enro based instructions should not execute, and instead
// should be captured against the TestNavigationHandle for assertion, so we should expect
// that closing the UnboundBottomSheetFragment through Enro won't actually cause
// the fragment to be dismissed
@Test(expected = ComposeTimeoutException::class)
fun test_closeWithEnro() {
UnboundBottomSheetFragment().show(composeRule.activity.supportFragmentManager, null)
UnboundBottomSheetRobot(composeRule)
.closeWithEnro()
}
@Test
fun test_pressBack() {
UnboundBottomSheetFragment().show(composeRule.activity.supportFragmentManager, null)
UnboundBottomSheetRobot(composeRule)
.closeWithBackPress()
}
@Test
fun test_closeWithDismiss() {
UnboundBottomSheetFragment().show(composeRule.activity.supportFragmentManager, null)
UnboundBottomSheetRobot(composeRule)
.dismiss()
}
} | 1 | Kotlin | 13 | 246 | fab4af27fd1d0c066f1ad99ded202e1c6b16c575 | 1,717 | Enro | Apache License 2.0 |
app/src/main/java/com/istu/schedule/domain/usecase/schedule/GetClassroomsListUseCase.kt | imysko | 498,018,609 | false | {"Kotlin": 862247} | package com.istu.schedule.domain.usecase.schedule
import com.istu.schedule.domain.entities.schedule.Classroom
import com.istu.schedule.domain.repository.schedule.ClassroomsRepository
import javax.inject.Inject
interface GetClassroomsListUseCase {
suspend operator fun invoke(): Result<List<Classroom>>
}
class GetClassroomsListUseCaseImpl @Inject constructor(
private val classroomsRepository: ClassroomsRepository
) : GetClassroomsListUseCase {
override suspend fun invoke(): Result<List<Classroom>> {
return classroomsRepository.getClassrooms()
}
}
| 1 | Kotlin | 1 | 2 | 36ff18c29364921c0eb9b09af090b434fca2a36e | 580 | Schedule-ISTU | MIT License |
src/main/kotlin/me/fzzyhmstrs/fzzy_core/modifier_util/SlotId.kt | fzzyhmstrs | 591,771,816 | false | {"Kotlin": 205455, "Java": 14440} | package me.fzzyhmstrs.fzzy_core.modifier_util
import net.minecraft.entity.EquipmentSlot
import java.util.*
open class SlotId(private val id: String) {
fun getUUID(prefix: String): UUID{
return UUID.nameUUIDFromBytes("$prefix@$id".toByteArray())
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun equals(other: Any?): Boolean{
if (other !is SlotId) return false
return other.id == this.id
}
companion object{
val HEAD = SlotId(EquipmentSlot.HEAD.getName())
val CHEST = SlotId(EquipmentSlot.CHEST.getName())
val LEGS = SlotId(EquipmentSlot.LEGS.getName())
val FEET = SlotId(EquipmentSlot.FEET.getName())
val MAINHAND = SlotId(EquipmentSlot.MAINHAND.getName())
val OFFHAND = SlotId(EquipmentSlot.CHEST.getName())
private val slotIds: Array<SlotId>
init{
val list: MutableList<SlotId> = mutableListOf()
list.add(MAINHAND)
list.add(OFFHAND)
list.add(FEET)
list.add(LEGS)
list.add(CHEST)
list.add(HEAD)
slotIds = list.toTypedArray()
}
fun getIdBySlot(slot: EquipmentSlot): SlotId{
return slotIds[slot.ordinal]
}
}
}
| 0 | Kotlin | 1 | 0 | 9b6ca751fb26d65b3153a86059955c3fbc15dc01 | 1,312 | fc | MIT License |
app/src/main/java/com/webaddicted/newhiltproject/view/dashboard/L3MRetailersFragment.kt | webaddicted | 434,853,888 | false | {"Kotlin": 403122, "Java": 83} | package com.webaddicted.newhiltproject.view.dashboard
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.webaddicted.newhiltproject.R
import com.webaddicted.newhiltproject.databinding.FrmL3mRetailerBinding
import com.webaddicted.newhiltproject.utils.constant.AppConstant
import com.webaddicted.newhiltproject.view.base.BaseFragment
import com.webaddicted.newhiltproject.view.home.HomeActivity
import com.webaddicted.newhiltproject.viewmodel.HomeViewModel
class L3MRetailersFragment : BaseFragment(R.layout.frm_l3m_retailer) {
private var retailerList: ArrayList<String>? = null
private var l3mRetailersAdapter: L3mRetailersAdapter? = null
private lateinit var mBinding: FrmL3mRetailerBinding
private val homeViewModel: HomeViewModel by viewModels()
companion object {
val TAG = L3MRetailersFragment::class.qualifiedName
const val BEAT_DATA = "Beat Data"
fun getInstance(): L3MRetailersFragment {
val bundle = Bundle()
// bundle.putSerializable(BEAT_DATA, beatRespo)
val fragment = L3MRetailersFragment()
fragment.arguments = bundle
return fragment
}
}
override fun onBindTo(binding: ViewDataBinding) {
mBinding = binding as FrmL3mRetailerBinding
// beatData = arguments?.getSerializable(VisitDetailsFragment.BEAT_DATA) as BeatRespo
(mActivity as HomeActivity).setActionBarTitle(getString(R.string.l3m_retailer))
(mActivity as HomeActivity).setActionBarBackIcon(true)
(mActivity as HomeActivity).lockDrawer(true)
retailerList = AppConstant.OrderCategory.values().map { it.value } as ArrayList<String>
setUi()
clickListener()
l3mRetailer()
setAdapter()
}
private fun setUi() {
}
private fun clickListener() {
mBinding.nextFabBtn.setOnClickListener(this)
}
override fun onClick(v: View) {
super.onClick(v)
when (v.id) {
R.id.next_fabBtn -> {
navigateScreen(RetailerCreditWiseFragment.TAG)
}
}
}
private fun l3mRetailer() {
// homeViewModel.l3mRetailer("")
// homeViewModel.l3MRetailerRespo.observe(this, {
// handleApiRespo(
// it,
// mBinding.loadingTyreIv
// ) { isFailure: Boolean, result: ApiResponse<CommonListRespo<L3MRetailerRespo>>? ->
// if (isFailure) l3mRetailer()
// else {
// retailerList = result?.data?.respDetails
// setAdapter()
// }
// }
// })
}
private fun setAdapter() {
l3mRetailersAdapter = L3mRetailersAdapter(retailerList)
mBinding.itemRv.run {
layoutManager = LinearLayoutManager(
mActivity,
LinearLayoutManager.VERTICAL,
false
)
adapter = l3mRetailersAdapter
}
}
private fun navigateScreen(tag: String?) {
var frm: Fragment? = null
when (tag) {
RetailerCreditWiseFragment.TAG -> frm = RetailerCreditWiseFragment.getInstance()
}
if (frm != null) navigateFragment(R.id.container, frm, true)
}
}
| 0 | Kotlin | 0 | 1 | 3dcf906deec23c672cfb3a1212411395fa319edf | 3,505 | HiltDemo | Apache License 2.0 |
src/controller/java/generated/java/chip/devicecontroller/cluster/structs/PowerSourceClusterWiredFaultChangeType.kt | project-chip | 244,694,174 | false | null | /*
*
* Copyright (c) 2023 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package chip.devicecontroller.cluster.structs
import chip.devicecontroller.cluster.*
import chip.tlv.AnonymousTag
import chip.tlv.ContextSpecificTag
import chip.tlv.Tag
import chip.tlv.TlvReader
import chip.tlv.TlvWriter
class PowerSourceClusterBatChargeFaultChangeType(val current: List<Int>, val previous: List<Int>) {
override fun toString(): String = buildString {
append("PowerSourceClusterBatChargeFaultChangeType {\n")
append("\tcurrent : $current\n")
append("\tprevious : $previous\n")
append("}\n")
}
fun toTlv(tag: Tag, tlvWriter: TlvWriter) {
tlvWriter.apply {
startStructure(tag)
startList(ContextSpecificTag(TAG_CURRENT))
for (item in current.iterator()) {
put(AnonymousTag, item)
}
endList()
startList(ContextSpecificTag(TAG_PREVIOUS))
for (item in previous.iterator()) {
put(AnonymousTag, item)
}
endList()
endStructure()
}
}
companion object {
private const val TAG_CURRENT = 0
private const val TAG_PREVIOUS = 1
fun fromTlv(tag: Tag, tlvReader: TlvReader): PowerSourceClusterBatChargeFaultChangeType {
tlvReader.enterStructure(tag)
val current =
buildList<Int> {
tlvReader.enterList(ContextSpecificTag(TAG_CURRENT))
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getInt(AnonymousTag))
}
tlvReader.exitContainer()
}
val previous =
buildList<Int> {
tlvReader.enterList(ContextSpecificTag(TAG_PREVIOUS))
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getInt(AnonymousTag))
}
tlvReader.exitContainer()
}
tlvReader.exitContainer()
return PowerSourceClusterBatChargeFaultChangeType(current, previous)
}
}
}
| 1,120 | C++ | 1588 | 6,261 | 693b30264d3a91c663218ff04d2a83846ca247c5 | 2,474 | connectedhomeip | Apache License 2.0 |
tongs-plugin-android/src/main/java/com/github/tarcv/tongs/runner/listeners/RawLogCatWriter.kt | engeniousio | 262,129,936 | false | null | /*
* Copyright 2020 TarCV
* Copyright 2014 Shazam Entertainment Limited
*
* 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.github.tarcv.tongs.runner.listeners
import com.android.ddmlib.logcat.LogCatMessage
import com.github.tarcv.tongs.api.devices.Device
import com.github.tarcv.tongs.api.devices.Pool
import com.github.tarcv.tongs.api.result.TestCaseFile
import com.github.tarcv.tongs.api.result.TestCaseFileManager
import org.apache.commons.io.IOUtils
internal class RawLogCatWriter(
private val fileManager: TestCaseFileManager,
private val pool: Pool,
private val device: Device,
private val file: TestCaseFile
) : LogCatWriter {
override fun writeLogs(logCatMessages: List<LogCatMessage>) {
file.create()
.bufferedWriter(Charsets.UTF_8)
.use { fileWriter ->
for (logCatMessage in logCatMessages) {
IOUtils.write(logCatMessage.toString(), fileWriter)
IOUtils.write("\n", fileWriter)
}
}
}
} | 1 | HTML | 2 | 3 | da5ee89d7509f66fe58468eb30e03dd05a1b89c9 | 1,593 | sift-android | Apache License 2.0 |
app/src/main/kotlin/no/nav/paw/kafkakeygenerator/api/v1/Response.kt | navikt | 708,718,823 | false | {"Kotlin": 35163} | package no.nav.paw.kafkakeygenerator.api.v1
data class Response(val id: Long) | 0 | Kotlin | 0 | 1 | 89fa6709b888c6009da6b6bb0d2c6b8fa8df7208 | 78 | paw-kafka-key-generator | MIT License |
composablesweettoast/src/main/java/com/talhafaki/composablesweettoast/util/SweetToastProperty.kt | tfaki | 431,441,275 | false | {"Kotlin": 18743} | package com.talhafaki.composablesweettoast.util
import androidx.compose.ui.graphics.Color
interface SweetToastProperty {
fun getResourceId(): Int
fun getBackgroundColor(): Color
}
| 3 | Kotlin | 5 | 83 | 4d5cd0a94fafe633ce8331f8f6c888b3bb249723 | 190 | ComposableSweetToast | MIT License |
app/src/main/java/com/example/intelligent_shopping_cart/ui/screens/home/RotationChartItem.kt | cxp-13 | 629,093,945 | false | null | package com.example.intelligent_shopping_cart.ui.screens.home
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
@Composable
fun RotationChartItem(modifier: Modifier, image: String, title: String) {
Card(
shape = MaterialTheme.shapes.small,
modifier = modifier
.size(136.dp),
) {
Column {
AsyncImage(
model = image,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(136.dp)
.height(96.dp)
)
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
modifier = Modifier
.paddingFromBaseline(top = 24.dp)
.padding(horizontal = 16.dp),
)
}
}
} | 0 | Kotlin | 0 | 0 | 6a003112f1b1b1f67e191cf5ed59d3942afc1d25 | 1,195 | Intelligent-Shopping-Cart-APP | Apache License 2.0 |
ziti/src/main/kotlin/org/openziti/ZitiAddress.kt | openziti | 214,175,575 | false | null | /*
* Copyright (c) 2018-2021 NetFoundry 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
*
* 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 org.openziti
import java.net.SocketAddress
/**
* Object representing Ziti address.
* It can be used to initiate connections or host services on Ziti network.
*/
sealed class ZitiAddress: SocketAddress() {
/**
* Address representing a Ziti service.
* @param name name of the service
* @param identity target terminator
* @param callerId caller identity
*/
data class Dial @JvmOverloads constructor (
val service: String,
val appData: Any? = null,
val identity: String? = null,
val callerId: String? = null
) : ZitiAddress()
data class Bind @JvmOverloads constructor(
val service: String, val identity: String? = null, val useEdgeId: Boolean = false)
: ZitiAddress()
data class Session internal constructor(internal val id: String, val service: String, val callerId: String?): ZitiAddress()
} | 9 | null | 4 | 9 | 4f561799f9d47e209e802ad46e23b308131b949c | 1,510 | ziti-sdk-jvm | Apache License 2.0 |
client/android-kotlin/app/src/main/java/com/example/app/CardBrandChoiceActivity.kt | stripe-samples | 270,634,286 | false | null | package com.example.app
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.example.app.databinding.CardActivityBinding
import com.stripe.android.ApiResultCallback
import com.stripe.android.PaymentConfiguration
import com.stripe.android.Stripe
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodOptionsParams
import com.stripe.android.payments.paymentlauncher.PaymentLauncher
import com.stripe.android.payments.paymentlauncher.PaymentResult
import com.stripe.android.view.CardValidCallback
class CardBrandChoiceActivity : AppCompatActivity() {
private lateinit var paymentLauncher: PaymentLauncher
private lateinit var stripe: Stripe
private lateinit var binding: CardActivityBinding
private var cardBrand: String? = null
private lateinit var paymentIntentClientSecret: String
private val unknownIndexPosition = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = CardActivityBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
this.createIntent()
this.wireViewEvents()
val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext)
paymentLauncher = PaymentLauncher.Companion.create(
this,
paymentConfiguration.publishableKey,
paymentConfiguration.stripeAccountId,
::onPaymentResult
)
stripe = Stripe(
applicationContext,
paymentConfiguration.publishableKey,
paymentConfiguration.stripeAccountId
)
}
private fun wireViewEvents() {
// set card network
binding.listBrands.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
cardBrand = if (position === unknownIndexPosition) {
null
} else {
resources.getStringArray(R.array.network_cards_values)[position]
}
}
}
binding.cardInputWidget.setCardValidCallback(callback = { isValid: Boolean, _: Set<CardValidCallback.Fields> ->
if (isValid) {
binding.cardInputWidget.cardParams?.brand?.code?.let { code ->
cardBrand = code
val brands = resources.getStringArray(R.array.network_cards_values)
binding.listBrands.setSelection(brands.indexOf(code))
}
}
})
//binding the spinner
val adapter = ArrayAdapter.createFromResource(
this,
R.array.network_cards,
android.R.layout.simple_spinner_item
)
binding.listBrands.adapter = adapter
//selecting Unknown by default
binding.listBrands.setSelection(unknownIndexPosition)
// binding the submit button
binding.payButton.setOnClickListener {
binding.cardInputWidget.paymentMethodCreateParams?.let { paymentMethodCreateParams ->
stripe.createPaymentMethod(
paymentMethodCreateParams,
callback = object : ApiResultCallback<PaymentMethod> {
override fun onSuccess(paymentMethod: PaymentMethod) {
confirmPayment(paymentIntentClientSecret, paymentMethod)
}
override fun onError(error: Exception) {
AlertManager.displayAlert(
this@CardBrandChoiceActivity,
"Failed to create payment method",
"Error: $error",
)
}
}
)
}
}
}
private fun confirmPayment(paymentIntentClientSecret: String, paymentMethod: PaymentMethod) {
val paymentIntentParams = ConfirmPaymentIntentParams.createWithPaymentMethodId(
paymentMethod.id!!, paymentIntentClientSecret
)
val availableNetworks = paymentMethod.card?.networks?.available
if (availableNetworks != null && cardBrand != null && availableNetworks.contains(cardBrand)) {
val paymentMethodOptions = PaymentMethodOptionsParams.Card(null, cardBrand)
paymentIntentParams.paymentMethodOptions = paymentMethodOptions
}
// give UI feedback and prevent re-submit
binding.payButton.isEnabled = false
paymentLauncher.confirm(paymentIntentParams)
}
private fun createIntent() {
ApiClient().createPaymentIntent(completion = { paymentIntentClientSecret, error ->
run {
paymentIntentClientSecret?.let {
this.paymentIntentClientSecret = it
}
error?.let {
AlertManager.displayAlert(
this,
"Failed to load page",
"Error: $error",
)
}
}
})
}
private fun onPaymentResult(paymentResult: PaymentResult) {
val message = when (paymentResult) {
is PaymentResult.Completed -> {
"Completed! The demo will now restart"
}
is PaymentResult.Canceled -> {
"Canceled!"
}
is PaymentResult.Failed -> {
// This string comes from the PaymentIntent's error message.
// See here: https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-message
"Failed: " + paymentResult.throwable.message
}
}
AlertManager.displayAlert(
this, "Payment Result:", message,
) {
if (paymentResult == PaymentResult.Completed) {
this.finish()
}
}
binding.payButton.isEnabled = true
}
}
| 19 | Kotlin | 7 | 6 | 654e6c4c356886fad42008efa9cb7a491ff46801 | 6,464 | card-brand-choice | MIT License |
app/src/main/java/prieto/fernando/spacex/ui/LaunchesFragment.kt | ferPrieto | 226,459,777 | false | null | package prieto.fernando.spacex.ui
import android.animation.Animator
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.mitteloupe.solid.recyclerview.SolidAdapter
import prieto.fernando.core.event.observeEvent
import prieto.fernando.presentation.LaunchesViewModel
import prieto.fernando.presentation.model.LaunchUiModel
import prieto.fernando.spacex.R
import prieto.fernando.spacex.databinding.FragmentLaunchesBinding
import prieto.fernando.spacex.ui.adapter.ClickListener
import prieto.fernando.spacex.ui.adapter.LaunchViewBinder
import prieto.fernando.spacex.ui.adapter.LaunchViewHolder
import prieto.fernando.spacex.ui.adapter.LaunchViewProvider
import prieto.fernando.spacex.ui.util.UrlUtils
import javax.inject.Inject
class LaunchesFragment @Inject constructor(
viewModelFactory: ViewModelProvider.Factory
) : Fragment(R.layout.fragment_launches) {
private val viewModel by viewModels<LaunchesViewModel> { viewModelFactory }
private lateinit var binding: FragmentLaunchesBinding
private var launchesAdapter: SolidAdapter<LaunchViewHolder, LaunchUiModel>? = null
private var linkYoutube = ""
private var linkWikipedia = ""
private val clickListener = object : ClickListener {
override fun onItemClicked(urls: Link) {
when (urls) {
is Link.OneLink -> showOneOptionSheet(urls)
is Link.TwoLinks -> showTwoOptionsSheet(urls)
else -> binding.bottomSheet.collapse()
}
expandOrCollapseBottomSheet()
}
}
private fun expandOrCollapseBottomSheet() {
if (binding.bottomSheet.isExpended()) {
binding.bottomSheet.collapse()
} else {
binding.bottomSheet.expand()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentLaunchesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
setupBottomSheet()
setupLaunchesFilter()
setViewModelObservers()
}
private fun setupRecyclerView() {
launchesAdapter = SolidAdapter(
LaunchViewProvider(layoutInflater),
{ view, _ -> LaunchViewHolder(view) },
LaunchViewBinder(context = requireContext(), clickListener = clickListener)
)
binding.launchesRecyclerView.apply {
adapter = launchesAdapter
layoutManager = LinearLayoutManager(context)
setOnScrollChangeListener { _, _, _, _, _ ->
binding.bottomSheet.collapse()
}
}
}
private fun setupBottomSheet() {
binding.bottomSheet.animationDuration = 500
binding.youtubeTitle.setOnClickListener {
viewModel.openLink(
linkYoutube
)
}
binding.wikipediaTitle.setOnClickListener {
viewModel.openLink(
linkWikipedia
)
}
}
private fun setupLaunchesFilter() {
binding.launchesFilter.setOnClickListener {
viewModel.onFilterClicked()
}
}
private fun setViewModelObservers() {
viewModel.launches.observe(viewLifecycleOwner, { launches ->
bindLaunches(launches)
})
viewModel.loadingLaunches.observe(viewLifecycleOwner, { show ->
showLaunchesAnimation(show)
})
viewModel.openLink.observeEvent(this) { link ->
openLink(link)
}
viewModel.showDialog.observeEvent(this) {
showDialog()
}
viewModel.launchesError.observeEvent(this) {
setLaunchesErrorViewsVisibility(true)
setLaunchesViewsVisbility(false)
}
}
override fun onResume() {
super.onResume()
viewModel.launches()
collapseBottomSheet()
}
private fun collapseBottomSheet(){
if (binding.bottomSheet.isExpended()) {
binding.bottomSheet.collapse()
}
}
override fun onPause() {
super.onPause()
setLaunchesViewsVisbility(false)
}
private fun bindLaunches(launchesUiModel: List<LaunchUiModel>?) {
launchesUiModel?.let { launches ->
launchesAdapter?.setItems(launches)
setLaunchesErrorViewsVisibility(false)
binding.launchesAnimation.isVisible = true
}
}
private fun showLaunchesAnimation(loading: Boolean) {
if (loading) {
binding.launchesAnimation.apply {
playAnimation()
addAnimatorListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
isVisible = false
setLaunchesViewsVisbility(true)
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
}
})
}
}
}
private fun showTwoOptionsSheet(link: Link.TwoLinks) {
setItemsVisibility(showYoutube = true, showWikipedia = true)
linkYoutube = link.linkYoutube
linkWikipedia = link.linkWikipedia
}
private fun showOneOptionSheet(oneLink: Link.OneLink) {
when (oneLink.linkType) {
LinkType.YOUTUBE -> showYoutube(oneLink.link)
LinkType.WIKIPEDIA -> showWikipedia(oneLink.link)
}
}
private fun showYoutube(url: String) {
linkYoutube = url
setItemsVisibility(showYoutube = true, showWikipedia = false)
}
private fun showWikipedia(url: String) {
linkWikipedia = url
setItemsVisibility(showYoutube = false, showWikipedia = true)
}
private fun setItemsVisibility(showYoutube: Boolean, showWikipedia: Boolean) {
binding.wikipediaTitle.isVisible = showWikipedia
binding.youtubeTitle.isVisible = showYoutube
}
private fun openLink(link: String) {
UrlUtils.navigateTo(activity as Context, link)
}
private fun setLaunchesErrorViewsVisibility(show: Boolean) {
binding.launchesErrorDescription.isVisible = show
binding.launchesErrorAnimation.isVisible = show
}
private fun setLaunchesViewsVisbility(show: Boolean) {
binding.launchesRecyclerView.isVisible = show
binding.launchesFilter.isVisible = show
}
private fun showDialog() {
val dialog = layoutInflater.inflate(R.layout.view_dialog, null)
val orderToggle = dialog.findViewById<SwitchCompat>(R.id.order_toggle)
val yearEditText = dialog.findViewById<EditText>(R.id.dialog_year)
val dialogBuilder = setUpDialogBuilder(orderToggle, yearEditText, dialog)
dialogBuilder.show()
}
private fun setUpDialogBuilder(
orderToggle: SwitchCompat,
yearEditText: EditText,
dialog: View
) =
AlertDialog.Builder(requireContext(), R.style.RoundedCornersDialog).apply {
setPositiveButton(
getString(R.string.dialog_ok_button)
) { _, _ ->
binding.launchesRecyclerView.isVisible = false
requestFilteredData(orderToggle, yearEditText)
}
setNegativeButton(
getString(R.string.dialog_cancel_button)
) { dialog, _ ->
dialog.dismiss()
}
setView(dialog)
}
private fun requestFilteredData(orderToggle: SwitchCompat, yearEditText: EditText) {
val ascendant = orderToggle.isChecked
val yearValue = yearEditText.text.toString()
val year = Integer.parseInt(integerValueOrZero(yearValue))
viewModel.launches(year, ascendant)
}
private fun integerValueOrZero(yearValue: String) =
if (yearValue.isNotBlank()) {
yearValue
} else {
"0"
}
}
sealed class Link {
data class OneLink(val linkType: LinkType, val link: String) : Link()
data class TwoLinks(val linkYoutube: String, val linkWikipedia: String) : Link()
data class Empty(val unit: Unit) : Link()
}
enum class LinkType {
YOUTUBE,
WIKIPEDIA
} | 0 | Kotlin | 34 | 277 | 8b9c5e19f4fb9370f15c1d1e0b5a667ee2ad660b | 8,990 | Coroutines-Flows-Modularised | Apache License 2.0 |
tmp/arrays/kotlinAndJava/93.kt | mandelshtamd | 346,008,310 | false | {"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1} | //File MyClass.java
import kotlin.Metadata;
@Ann(
p1 = 128,
p2 = 2,
p4 = 2,
p5 = 2
)
public final class MyClass {
}
//File Main.kt
// IGNORE_BACKEND_FIR: JVM_IR
// TARGET_BACKEND: JVM
// WITH_RUNTIME
fun box(): String {
val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!!
if (annotation.p1 != 128) return "fail 1, expected = ${128}, actual = ${annotation.p1}"
if (annotation.p2 != 2.toByte()) return "fail 2, expected = ${2}, actual = ${annotation.p2}"
if (annotation.p4 != 2) return "fail 4, expected = ${2}, actual = ${annotation.p4}"
if (annotation.p5 != 2) return "fail 5, expected = ${2}, actual = ${annotation.p5}"
return "OK"
}
//File Ann.java
import java.lang.annotation.RetentionPolicy;
import kotlin.Metadata;
import kotlin.annotation.AnnotationRetention;
import kotlin.annotation.Retention;
@Retention(AnnotationRetention.RUNTIME)
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
public @interface Ann {
int p1();
byte p2();
int p4();
int p5();
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 1,044 | kotlinWithFuzzer | Apache License 2.0 |
airbyte-workload-api-server/src/main/kotlin/io/airbyte/workload/server/Application.kt | airbytehq | 592,970,656 | false | null | package io.airbyte.workload.server
import io.micronaut.runtime.Micronaut.run
import io.swagger.v3.oas.annotations.OpenAPIDefinition
import io.swagger.v3.oas.annotations.info.Info
import io.swagger.v3.oas.annotations.servers.Server
@OpenAPIDefinition(
info =
Info(
title = "WorkloadApi",
description = "API managing the workload",
version = "1.0.0",
),
servers = [Server(url = "http://localhost:8007/api")],
)
class Application {
companion object {
@JvmStatic fun main(args: Array<String>) {
run(*args)
}
}
}
| 54 | null | 249 | 205 | a2e58f1b60ea79ec96546c98f712077c82de373a | 558 | airbyte-platform | MIT License |
base/src/test/kotlin/proguard/classfile/util/ClassPoolClassLoaderTest.kt | Guardsquare | 263,266,232 | false | null | package proguard.classfile.util
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import proguard.classfile.ClassPool
import proguard.testutils.ClassPoolBuilder
import proguard.testutils.JavaSource
class ClassPoolClassLoaderTest : FreeSpec({
"Given a ProGuard ProgramClass" - {
val (programClassPool, _) = ClassPoolBuilder.fromSource(
JavaSource(
"Test.java",
"""
public class Test {
public static String test() {
return "Hello World";
}
}
""".trimIndent()
),
javacArguments = listOf("-source", "1.8", "-target", "1.8")
)
"When loaded with the ClassPoolClassLoader" - {
val clazz = ClassPoolClassLoader(programClassPool).loadClass("Test")
"Then the main method can be executed" {
clazz
.declaredMethods
.single { it.name == "test" }
.invoke(null) shouldBe "Hello World"
}
}
}
"Given a class not in the class pool" - {
"When calling findClass with the ClassPoolClassLoader" - {
val emptyClassPool = ClassPool()
"Then the class loader should throw a ClassNotFoundException" {
shouldThrow<ClassNotFoundException> {
ClassPoolClassLoader(emptyClassPool).findClass("Test")
}
}
}
}
})
| 8 | null | 61 | 279 | 158061999ebd35ffa8e79a55cd38c06d0aeb10d7 | 1,604 | proguard-core | Apache License 2.0 |
app/src/main/java/com/redvelvet/trivia_game/ui/composable/NoInternetCard.kt | RedVelvet-Team | 661,473,736 | false | null | package com.redvelvet.trivia_game.ui.composable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.redvelvet.trivia_game.R
import com.redvelvet.trivia_game.ui.theme.Poppins
import com.redvelvet.trivia_game.ui.theme.*
@Composable
fun LottieAnimationComponent() {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cheack))
var isPlaying by remember {
mutableStateOf(true)
}
val progress by animateLottieCompositionAsState(
composition = composition,
isPlaying = isPlaying
)
LaunchedEffect(key1 = progress) {
if (progress == 0f) {
isPlaying = true
}
if (progress == 1f) {
isPlaying = false
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.background(Color.White)
.fillMaxHeight()
.padding(horizontal = 32.dp, vertical = 32.dp),
verticalArrangement = Arrangement.Center
) {
LottieAnimation(
modifier = Modifier.size(500.dp),
composition = composition,
progress = progress
)
Button(onClick = { isPlaying = true }) {
Text(
text = "try again",
fontSize = 14.sp,
color = White,
textAlign = TextAlign.Center,
maxLines = 1,
fontFamily = Poppins,
)
}
}
} | 0 | Kotlin | 0 | 3 | b1cf6e438b78f490b7b8d4b87fb37260840459f9 | 2,546 | Trivia-Game | Apache License 2.0 |
SpinCalendarField/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.*
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.swing.*
import javax.swing.JSpinner.DefaultEditor
import javax.swing.text.DateFormatter
import javax.swing.text.DefaultFormatterFactory
fun makeUI(): Component {
val c = Calendar.getInstance()
c[Calendar.HOUR_OF_DAY] = 0
c.clear(Calendar.MINUTE)
c.clear(Calendar.SECOND)
c.clear(Calendar.MILLISECOND)
val d = c.time
val format = SimpleDateFormat("mm:ss", Locale.getDefault())
val factory = DefaultFormatterFactory(DateFormatter(format))
val spinner1 = JSpinner(SpinnerDateModel(d, null, null, Calendar.SECOND))
(spinner1.editor as? DefaultEditor)?.textField?.formatterFactory = factory
val spinner2 = JSpinner(object : SpinnerDateModel(d, null, null, Calendar.SECOND) {
override fun setCalendarField(calendarField: Int) {
// https://docs.oracle.com/javase/8/docs/api/javax/swing/SpinnerDateModel.html#setCalendarField-int-
// If you only want one field to spin you can subclass and ignore the setCalendarField calls.
}
})
(spinner2.editor as? DefaultEditor)?.textField?.formatterFactory = factory
return JPanel(GridLayout(2, 1)).also {
it.add(makeTitledPanel("Default SpinnerDateModel", spinner1))
it.add(makeTitledPanel("Override SpinnerDateModel#setCalendarField(...)", spinner2))
it.border = BorderFactory.createEmptyBorder(10, 5, 10, 5)
it.preferredSize = Dimension(320, 240)
}
}
private fun makeTitledPanel(
title: String,
cmp: Component,
): Component {
val p = JPanel(GridBagLayout())
p.border = BorderFactory.createTitledBorder(title)
val c = GridBagConstraints()
c.weightx = 1.0
c.fill = GridBagConstraints.HORIZONTAL
c.insets = Insets(5, 5, 5, 5)
p.add(cmp, c)
return p
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 6 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 2,224 | kotlin-swing-tips | MIT License |
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RestaurantDetailFragment.kt | firebase | 57,147,349 | false | null | package com.google.firebase.example.fireeats
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.google.android.gms.tasks.Task
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.example.fireeats.databinding.FragmentRestaurantDetailBinding
import com.google.firebase.example.fireeats.adapter.RatingAdapter
import com.google.firebase.example.fireeats.model.Rating
import com.google.firebase.example.fireeats.model.Restaurant
import com.google.firebase.example.fireeats.util.RestaurantUtil
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.toObject
import com.google.firebase.ktx.Firebase
import com.mixpanel.android.mpmetrics.MixpanelAPI
class RestaurantDetailFragment : Fragment(),
EventListener<DocumentSnapshot>,
RatingDialogFragment.RatingListener {
private var ratingDialog: RatingDialogFragment? = null
private lateinit var binding: FragmentRestaurantDetailBinding
private lateinit var firestore: FirebaseFirestore
private lateinit var restaurantRef: DocumentReference
private lateinit var ratingAdapter: RatingAdapter
private var restaurantRegistration: ListenerRegistration? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentRestaurantDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Get restaurant ID from extras
val restaurantId = RestaurantDetailFragmentArgs.fromBundle(requireArguments()).keyRestaurantId
// Initialize Firestore
firestore = Firebase.firestore
// Get reference to the restaurant
restaurantRef = firestore.collection("colleges").document(restaurantId)
// Get ratings
val ratingsQuery = restaurantRef
.collection("ratings")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(50)
// RecyclerView
ratingAdapter = object : RatingAdapter(ratingsQuery) {
override fun onDataChanged() {
if (itemCount == 0) {
binding.recyclerRatings.visibility = View.GONE
binding.viewEmptyRatings.visibility = View.VISIBLE
} else {
binding.recyclerRatings.visibility = View.VISIBLE
binding.viewEmptyRatings.visibility = View.GONE
}
}
}
binding.recyclerRatings.layoutManager = LinearLayoutManager(context)
binding.recyclerRatings.adapter = ratingAdapter
ratingDialog = RatingDialogFragment()
binding.restaurantButtonBack.setOnClickListener { onBackArrowClicked() }
binding.fabShowRatingDialog.setOnClickListener { onAddRatingClicked() }
}
public override fun onStart() {
super.onStart()
ratingAdapter.startListening()
restaurantRegistration = restaurantRef.addSnapshotListener(this)
}
public override fun onStop() {
super.onStop()
ratingAdapter.stopListening()
restaurantRegistration?.remove()
restaurantRegistration = null
}
/**
* Listener for the Restaurant document ([.restaurantRef]).
*/
override fun onEvent(snapshot: DocumentSnapshot?, e: FirebaseFirestoreException?) {
if (e != null) {
Log.w(TAG, "restaurant:onEvent", e)
return
}
snapshot?.let {
val restaurant = snapshot.toObject<Restaurant>()
if (restaurant != null) {
onRestaurantLoaded(restaurant)
}
}
}
private fun onRestaurantLoaded(restaurant: Restaurant) {
binding.restaurantName.text = restaurant.name
binding.restaurantRating.rating = restaurant.avgRating.toFloat()
binding.restaurantNumRatings.text = getString(R.string.fmt_num_ratings, restaurant.numRatings)
binding.restaurantCity.text = restaurant.city
binding.restaurantCategory.text = restaurant.category
binding.restaurantPrice.text = RestaurantUtil.getPriceString(restaurant)
// Background image
Glide.with(binding.restaurantImage.context)
.load(restaurant.photo)
.into(binding.restaurantImage)
}
private fun onBackArrowClicked() {
requireActivity().onBackPressed()
}
private fun onAddRatingClicked() {
ratingDialog?.show(childFragmentManager, RatingDialogFragment.TAG)
}
override fun onRating(rating: Rating) {
// In a transaction, add the new rating and update the aggregate totals
addRating(restaurantRef, rating)
.addOnSuccessListener(requireActivity()) {
Log.d(TAG, "Rating added")
// Hide keyboard and scroll to top
hideKeyboard()
binding.recyclerRatings.smoothScrollToPosition(0)
}
.addOnFailureListener(requireActivity()) { e ->
Log.w(TAG, "Add rating failed", e)
// Show failure message and hide keyboard
hideKeyboard()
Snackbar.make(
requireView().findViewById(android.R.id.content), "Failed to add rating",
Snackbar.LENGTH_SHORT).show()
}
}
private lateinit var mixpanel: MixpanelAPI
private fun addRating(restaurantRef: DocumentReference, rating: Rating): Task<Void> {
// TODO(developer): Implement
// Create reference for new rating, for use inside the transaction
val ratingRef = restaurantRef.collection("ratings").document()
// In a transaction, add the new rating and update the aggregate totals
return firestore.runTransaction { transaction ->
val restaurant = transaction.get(restaurantRef).toObject<Restaurant>()
?: throw Exception("Colleges not found at ${restaurantRef.path}")
// Compute new number of ratings
val newNumRatings = restaurant.numRatings + 1
// Compute new average rating
val oldRatingTotal = restaurant.avgRating * restaurant.numRatings
val newAvgRating = (oldRatingTotal + rating.rating) / newNumRatings
// Set new restaurant info
restaurant.numRatings = newNumRatings
restaurant.avgRating = newAvgRating
//mixpanel = MixpanelAPI.getInstance(this, "c30a02575c1d82150edb3cac8f318d77", false);
//mixpanel.track("test api", null)
// mixpanel = MixpanelAPI.getInstance(this, "c30a02575c1d82150edb3cac8f318d77", false)
// mixpanel.track("test api", null)
// Commit to Firestore
transaction.set(restaurantRef, restaurant)
transaction.set(ratingRef, rating)
null
}
}
private fun hideKeyboard() {
val view = requireActivity().currentFocus
if (view != null) {
(requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(view.windowToken, 0)
}
}
companion object {
private const val TAG = "RestaurantDetail"
const val KEY_RESTAURANT_ID = "key_restaurant_id"
}
}
| 68 | null | 7450 | 8,858 | 4d1e253dd1dd8052310e889fc1785084b1997aca | 8,214 | quickstart-android | Apache License 2.0 |
view/view-api/src/main/kotlin/query/data/DataEntriesForUserQuery.kt | holunda-io | 135,994,693 | false | null | package io.holunda.polyflow.view.query.data
import io.holunda.polyflow.view.DataEntry
import io.holunda.polyflow.view.auth.User
import io.holunda.polyflow.view.query.FilterQuery
import io.holunda.polyflow.view.query.PageableSortableQuery
/**
* Queries data entries for provided user.
* @param user user authorized to access data entries.
* @param page current page.
* @param size page size.
* @param sort sort of data entries.
* @param filters list of filters.
*/
data class DataEntriesForUserQuery(
val user: User,
override val page: Int = 1,
override val size: Int = Int.MAX_VALUE,
override val sort: String? = null,
val filters: List<String> = listOf()
) : FilterQuery<DataEntry>, PageableSortableQuery {
override fun applyFilter(element: DataEntry): Boolean =
// authorized users
element.authorizedUsers.contains(this.user.username)
// authorized groups
|| (element.authorizedGroups.any { candidateGroup -> this.user.groups.contains(candidateGroup) })
}
| 29 | null | 25 | 64 | f789322e29f7012fe0a59809bcf8d7777e609849 | 1,000 | camunda-bpm-taskpool | Apache License 2.0 |
defitrack-protocols/kyberswap/src/main/java/io/defitrack/protocol/kyberswap/graph/domain/PairDayData.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack.protocol.kyberswap.graph.domain
import java.math.BigDecimal
class PairDayData(
val id: String,
val dailyVolumeUSD: BigDecimal
) | 17 | Kotlin | 6 | 9 | f7c65aa58bec3268101d90fc538c3f8bd0c29093 | 158 | defi-hub | MIT License |
src/main/kotlin/org/opentripplanner/trakpi/store/schema/framwork.kt | opentripplanner | 208,077,511 | false | null | package org.opentripplanner.trakpi.store.schema
import org.opentripplanner.trakpi.model.Entity
import org.opentripplanner.trakpi.model.NamedClass
import org.opentripplanner.trakpi.model.NamedEntity
open class DbEntity(
/** Id used by the data store and automatically set by data store. */
var _id : String?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Entity
return _id == other._id
}
override fun hashCode(): Int {
toString()
return _id?.hashCode() ?: 0
}
}
open class DbNamedEntity(var _id : String?, val name : String) : Comparable<NamedClass> {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NamedEntity
return name == other.name
}
override fun hashCode(): Int = name.hashCode()
override fun compareTo(other: NamedClass): Int = name.compareTo(other.name)
override fun toString(): String = name
}
open class DbNamedClass(val name : String) : Comparable<NamedClass> {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NamedClass
return name == other.name
}
override fun hashCode(): Int = name.hashCode()
override fun compareTo(other: NamedClass): Int = name.compareTo(other.name)
override fun toString(): String = name
}
class DbMigrations (
id : String? = null,
val names: MutableList<String> = mutableListOf()
) : Entity(id)
| 2 | Kotlin | 2 | 4 | 852612750a4fe5748863d8f44525e5cd2a56af8b | 1,696 | TrakPi | MIT License |
app/src/main/java/com/jakubvanko/incloset/presentation/settings/components/CategoryDropdownMenu.kt | jakubvanko | 614,302,934 | false | null | package com.jakubvanko.incloset.presentation.settings.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import com.jakubvanko.incloset.domain.model.ClothingCategory
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CategoryDropdownMenu(
categories: List<ClothingCategory>,
currentCategory: ClothingCategory,
setCurrentCategory: (ClothingCategory) -> Unit
) {
var isExpanded by remember { mutableStateOf(false) }
Row {
ExposedDropdownMenuBox(
modifier = Modifier.fillMaxWidth(),
expanded = isExpanded,
onExpandedChange = { isExpanded = !isExpanded },
) {
TextField(
// The `menuAnchor` modifier must be passed to the text field for correctness.
modifier = Modifier
.menuAnchor()
.fillMaxWidth(),
readOnly = true,
value = currentCategory.name,
onValueChange = {/* TODO */ },
label = { Text("Select category") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isExpanded) },
colors = ExposedDropdownMenuDefaults.textFieldColors(),
)
ExposedDropdownMenu(
expanded = isExpanded,
onDismissRequest = { isExpanded = false },
) {
categories.forEach {
DropdownMenuItem(
text = { Text(text = it.name) },
onClick = {
setCurrentCategory(it)
isExpanded = false
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 0a079e868b197e8f20b32da66075e4c70e1cf21a | 1,992 | incloset | The Unlicense |
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/CanBeNonNullableSpec.kt | detekt | 71,729,669 | false | null | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class CanBeNonNullableSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { CanBeNonNullable(Config.empty) }
describe("CanBeNonNullable Rule") {
it("does not report when there is no context") {
val code = """
class A {
private var a: Int? = 5
fun foo() {
a = 6
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
context("evaluating private vars") {
it("reports when class-level vars are never assigned nullable values") {
val code = """
class A(bVal: Int) {
private var a: Int? = 5
private var b: Int?
init {
b = bVal
}
fun foo(): Int {
val b = a!!
a = b + 1
val a = null
return b
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("reports when vars utilize non-nullable delegate values") {
val code = """
import kotlin.reflect.KProperty
class A {
private var a: Int? by PropDelegate()
fun foo(): Int {
val b = a!!
a = b + 1
val a = null
return b
}
}
class PropDelegate(private var propVal: Int = 0) {
operator fun getValue(thisRef: A, property: KProperty<*>): Int {
return propVal
}
operator fun setValue(thisRef: A, property: KProperty<*>, value: Any?) {
if (value is Int) {
propVal = value
}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("reports when file-level vars are never assigned nullable values") {
val code = """
private var fileA: Int? = 5
private var fileB: Int? = 5
fun fileFoo() {
fileB = 6
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("does not report when class-level vars are assigned nullable values") {
val code = """
import kotlin.random.Random
class A(fVal: Int?) {
private var a: Int? = 0
private var b: Int? = 0
private var c: Int? = 0
private var d: Int? = 0
private var e: Int? = null
private var f: Int?
init {
f = fVal
}
fun foo(fizz: Int): Int {
a = null
b = if (fizz % 2 == 0) fizz else null
c = buzz(fizz)
d = a
return fizz
}
private fun buzz(bizz: Int): Int? {
return if (bizz % 2 == 0) null else bizz
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report vars that utilize nullable delegate values") {
val code = """
class A(private var aDelegate: Int?) {
private var a: Int? by this::aDelegate
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when file-level vars are assigned nullable values") {
val code = """
import kotlin.random.Random
private var fileA: Int? = 5
private var fileB: Int? = null
private var fileC: Int? = 5
fun fileFoo() {
fileC = null
}
class A {
fun foo() {
fileA = null
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("reports when vars with private setters are never assigned nullable values") {
val code = """
class A {
var a: Int? = 5
private set
fun foo() {
a = 6
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when vars with private setters are assigned nullable values") {
val code = """
class A {
var a: Int? = 5
private set
fun foo() {
a = null
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when vars use public setters") {
val code = """
class A {
var a: Int? = 5
fun foo() {
a = 6
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when vars use non-private setters") {
val code = """
class A {
var a: Int? = 5
internal set
fun foo() {
a = 6
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when private vars are declared in the constructor") {
val code = """
class A(private var a: Int?) {
fun foo() {
a = 6
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("evaluating private vars") {
it("reports when class-level vals are set to non-nullable values") {
val code = """
class A(cVal: Int) {
val a: Int? = 5
val b: Int?
val c: Int?
init {
b = 5
c = cVal
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3)
}
it("reports when vals utilize non-nullable delegate values") {
val code = """
class A {
val a: Int? by lazy {
5
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("reports when file-level vals are set to non-nullable values") {
val code = """
val fileA: Int? = 5
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when class-level vals are assigned a nullable value") {
val code = """
import kotlin.random.Random
class A(cVal: Int?) {
val a: Int? = null
val b: Int?
val c: Int?
init {
b = null
c = cVal
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when vals utilize nullable delegate values") {
val code = """
import kotlin.random.Random
class A {
val d: Int? by lazy {
val randVal = Random.nextInt()
if (randVal % 2 == 0) randVal else null
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when file-level vals are assigned a nullable value") {
val code = """
val fileA: Int? = null
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when vals are declared non-nullable") {
val code = """
class A {
val a: Int = 5
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when vals are declared in the constructor") {
val code = """
class A(private val a: Int?)
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("reports when vals with getters never return nullable values") {
val code = """
class A {
val a: Int?
get() = 5
val b: Int?
get() {
return 5
}
val c: Int?
get() = foo()
private fun foo(): Int {
return 5
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3)
}
it("does not report when vals with getters return potentially-nullable values") {
val code = """
import kotlin.random.Random
class A {
val a: Int?
get() = Random.nextInt()?.let { if (it % 2 == 0) it else null }
val b: Int?
get() {
return Random.nextInt()?.let { if (it % 2 == 0) it else null }
}
val c: Int?
get() = foo()
private fun foo(): Int? {
val randInt = Random.nextInt()
return if (randInt % 2 == 0) randInt else null
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
it("does not report open properties") {
val code = """
abstract class A {
open val a: Int? = 5
open var b: Int? = 5
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report properties whose initial assignment derives from unsafe non-Java code") {
val code = """
class A(msg: String?) {
private val e = Exception(msg)
// e.localizedMessage is marked as String! by Kotlin, meaning Kotlin
// cannot guarantee that it will be non-null, even though it is treated
// as non-null in Kotlin code.
private var a: String? = e.localizedMessage
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report interface properties") {
val code = """
interface A {
val a: Int?
var b: Int?
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
context("nullable function parameters") {
context("using a de-nullifier") {
it("does report when a param is de-nullified with a postfix expression") {
val code = """
fun foo(a: Int?) {
val b = a!! + 2
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does report when a param is de-nullified with a dot-qualified expression") {
val code = """
fun foo(a: Int?) {
val b = a!!.plus(2)
}
fun fizz(b: Int?) = b!!.plus(2)
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("does report when a de-nullifier precondition is called on the param") {
val code = """
fun foo(a: Int?, b: Int?) {
val aNonNull = requireNotNull(a)
val c = aNonNull + checkNotNull(b)
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("does not report a double-bang call the field of a non-null param") {
val code = """
class A(val a: Int?)
fun foo(a: A) {
val b = a.a!! + 2
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report on overridden function parameter") {
val code = """
interface A {
fun foo(a: Int?)
}
class B : A {
override fun foo(a: Int?) {
val b = a!! + 2
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("using a null-safe expression") {
context("in initializer") {
it("does not report when the safe-qualified expression is the only expression of the function") {
val code = """
class A {
val foo = "BAR"
}
fun foo(a: A?) = a?.foo
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("in a non-return statement") {
it("does report when the safe-qualified expression is the only expression of the function") {
val code = """
class A(val foo: String)
fun foo(a: A?) {
a?.let { println(it.foo) }
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when the safe-qualified expression is within a lambda") {
val code = """
class A {
fun doFoo(callback: () -> Unit) {
callback.invoke()
}
}
fun foo(a: String?, aObj: A) {
aObj.doFoo {
a?.let { println("a not null") }
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when the safe-qualified expression is not the only expression of the function") {
val code = """
class A {
fun doFoo() { println("FOO") }
}
fun foo(a: A?) {
a?.doFoo()
val b = 5 + 2
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("in a return statement") {
it("does not report when the safe-qualified expression is the only expression of the function") {
val code = """
class A {
val foo = "BAR"
}
fun fizz(aObj: A?): String? {
return aObj?.foo
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
}
context("when statements") {
context("without a subject") {
it("does not report when the parameter is checked on nullity") {
val code = """
fun foo(a: Int?) {
when {
a == null -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when the parameter is checked on nullity in a reversed manner") {
val code = """
fun foo(a: Int?) {
when {
null == a -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when the parameter is checked on nullity with multiple clauses") {
val code = """
fun foo(a: Int?, other: Int) {
when {
a == null && other % 2 == 0 -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does report when the parameter is only checked on non-nullity") {
val code = """
fun foo(a: Int?) {
when {
a != null -> println(2 + a)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does report when the parameter is only checked on non-nullity with multiple clauses") {
val code = """
fun foo(a: Int?) {
when {
a != null && a % 2 == 0 -> println(2 + a)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when the parameter is checked on non-nullity with an else statement") {
val code = """
fun foo(a: Int?) {
when {
a != null -> println(2 + a)
else -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report on nullable type matching") {
val code = """
fun foo(a: Int?) {
when {
a !is Int -> println("a is null")
}
}
fun fizz(b: Int?) {
when {
b is Int? -> println("b is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does report on non-null type matching") {
val code = """
fun foo(a: Int?) {
when {
a is Int -> println(2 + a)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does report on non-null type matching with multiple clauses") {
val code = """
fun foo(a: Int?) {
when {
a is Int && a % 2 == 0 -> println(2 + a)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report on non-null type matching with an else statement") {
val code = """
fun foo(a: Int?) {
when {
a is Int -> println(2 + a)
else -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("with a subject") {
it("does not report when the parameter is checked on nullity") {
val code = """
fun foo(a: Int?) {
when (a) {
null -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report on nullable type matching") {
val code = """
fun foo(a: Int?) {
when (a) {
!is Int -> println("a is null")
}
}
fun fizz(b: Int?) {
when (b) {
is Int? -> println("b is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does report on non-null type matching") {
val code = """
fun foo(a: Int?) {
when(a) {
is Int -> println(2 + a)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report on non-null type matching with an else statement") {
val code = """
fun foo(a: Int?) {
when(a) {
is Int -> println(2 + a)
else -> println("a is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
}
context("if-statements") {
it("does not report when the parameter is checked on nullity") {
val code = """
fun foo(a: Int?) {
if (a == null) {
println("'a' is null")
}
}
fun fizz(a: Int?) {
if (null == a) {
println("'a' is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when the if-check is in the else statement") {
val code = """
fun foo(num: Int, a: Int?) {
if (num % 2 == 0) {
println("'num' is even")
} else if (a == null) {
println("'a' is null")
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does report when the parameter is only checked on non-nullity in a function") {
val code = """
fun foo(a: Int?) {
if (a != null) {
println(a + 5)
}
}
fun fizz(a: Int?) {
if (null != a) {
println(a + 5)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2)
}
it("does report when the parameter is only checked on non-nullity with multiple clauses") {
val code = """
fun foo(a: Int?, other: Int) {
if (a != null && other % 2 == 0) {
println(a + 5)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1)
}
it("does not report when the parameter is checked on non-nullity with an else statement") {
val code = """
fun foo(a: Int?) {
if (a != null) {
println(a + 5)
} else {
println(5)
}
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when there are other expressions after the non-null check") {
val code = """
fun foo(a: Int?) {
if (a != null) {
println(a + 5)
}
val b = 5 + 2
}
""".trimIndent()
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
}
}
})
| 172 | null | 725 | 5,274 | a3dfea27eedc9239f371beab866abdeb397bdf9b | 30,825 | detekt | Apache License 2.0 |
app/src/main/java/com/arturostrowski/quiz/app/data/network/response/GetFriendsResponse.kt | Mesti193 | 215,134,193 | false | {"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 151, "XML": 93, "Java": 1, "JSON": 2} | package com.arturostrowski.quiz.app.data.network.response
import com.google.gson.annotations.SerializedName
data class GetFriendsResponse (
@SerializedName("Success")
var success: Boolean,
@SerializedName("Friends")
var friends: ArrayList<Friend>?,
@SerializedName("FriendRequests")
var friendRequests: ArrayList<Friend>?,
@SerializedName("Error")
var error: Error?
)
data class Friend(
@SerializedName("UserID")
var userID: Long,
@SerializedName("FirstName")
var firstName: String,
@SerializedName("LastName")
var lastName: String,
@SerializedName("Picture")
var picture: String,
@SerializedName("Level")
var level: Long,
@SerializedName("Points")
var points: Long
) | 0 | Kotlin | 0 | 0 | 1c0cef0108b0b90a4074f18b4690e5533214b41c | 835 | QuizApp | Apache License 2.0 |
app/src/main/java/de/uriegel/ulauncher/MainActivity.kt | uriegel | 226,920,154 | false | null | package de.uriegel.ulauncher
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.EdgeEffect
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.ceil
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
apps_list.layoutManager = GridLayoutManager(this, 3)
apps_list.adapter = appsAdapter
apps_list.edgeEffectFactory = object : RecyclerView.EdgeEffectFactory() {
override fun createEdgeEffect(view: RecyclerView, direction: Int): EdgeEffect {
return EdgeEffect(view.context).apply { color = Color.BLUE }
}
}
loadApps()
}
private fun loadApps() {
val i = Intent(Intent.ACTION_MAIN, null)
i.addCategory(Intent.CATEGORY_LAUNCHER)
val availableActivities = packageManager.queryIntentActivities(i, 0)
val apps = availableActivities.map {
AppDetail(
it.loadLabel(packageManager).toString(),
it.activityInfo.packageName,
it.activityInfo.loadIcon(packageManager),
View.OnClickListener { _ ->
val intent = packageManager.getLaunchIntentForPackage(it.activityInfo.packageName)
[email protected](intent)
})
}.sortedBy {
it.label
}
for (app in apps) {
//val bm = app!!.icon!!.toBitmap()
//bm.compress(Bitmap.CompressFormat.PNG, 1, )
appsList.add(app)
}
}
/*private fun loadListView() {
val adapter = object : ArrayAdapter<AppDetail>(
this,
R.layout.list_item,
apps!!
) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null)
if (position == 0)
convertView.setPadding(convertView.paddingLeft, convertView.paddingTop + statusBarHeight, convertView.paddingRight, convertView.paddingBottom)
}
val appIcon = convertView!!.findViewById(R.id.item_app_icon) as ImageView
appIcon.setImageDrawable(apps!!.get(position).icon)
val appLabel = convertView!!.findViewById(R.id.item_app_label) as TextView
appLabel.text = apps!![position].label
val appName = convertView!!.findViewById(R.id.item_app_name) as TextView
appName.text = apps!![position].name
return convertView!!
}
}
list!!.adapter = adapter
}*/
private val appsList = ArrayList<AppDetail>()
private val appsAdapter = AppsRecyclerAdapter(appsList)
}
| 0 | Kotlin | 0 | 0 | b0ae52707b2f1b9ddfb83cf11143806660dc02eb | 3,423 | ULauncher | MIT License |
src/main/kotlin/no/nav/tiltakspenger/skjerming/DefaultObjects.kt | navikt | 521,223,519 | false | null | package no.nav.tiltakspenger.vedtak
import com.fasterxml.jackson.core.util.DefaultIndenter
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import io.ktor.client.engine.cio.CIOEngineConfig
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.JacksonConverter
import mu.KotlinLogging
import java.time.Duration
private val LOG = KotlinLogging.logger {}
private val SECURELOG = KotlinLogging.logger("tjenestekall")
private const val SIXTY_SECONDS = 60L
// engine skal brukes primært i test-øyemed, når man sender med MockEngine.
// Forøvrig kan man la den være null.
fun defaultHttpClient(
objectMapper: ObjectMapper,
engine: HttpClientEngine? = null,
configBlock: HttpClientConfig<*>.() -> Unit = {},
engineConfigBlock: CIOEngineConfig.() -> Unit = {},
) = engine?.let {
HttpClient(engine) {
apply(defaultSetup(objectMapper))
apply(configBlock)
}
} ?: HttpClient(CIO) {
apply(defaultSetup(objectMapper))
apply(configBlock)
engine(engineConfigBlock)
}
private fun defaultSetup(objectMapper: ObjectMapper): HttpClientConfig<*>.() -> Unit = {
install(ContentNegotiation) {
register(ContentType.Application.Json, JacksonConverter(objectMapper))
}
install(HttpTimeout) {
connectTimeoutMillis = Duration.ofSeconds(SIXTY_SECONDS).toMillis()
requestTimeoutMillis = Duration.ofSeconds(SIXTY_SECONDS).toMillis()
socketTimeoutMillis = Duration.ofSeconds(SIXTY_SECONDS).toMillis()
}
this.install(Logging) {
logger = object : Logger {
override fun log(message: String) {
LOG.info("HttpClient detaljer logget til securelog")
SECURELOG.info(message)
}
}
level = LogLevel.ALL
}
this.expectSuccess = true
// install(HttpRequestRetry) {
// maxRetries = 5
// retryIf { _, response ->
// !response.status.isSuccess()
// }
// delayMillis { retry ->
// retry * 3000L
// }
// }
}
fun defaultObjectMapper(): ObjectMapper = ObjectMapper()
.registerModule(KotlinModule.Builder().build())
.registerModule(JavaTimeModule())
.setDefaultPrettyPrinter(
DefaultPrettyPrinter().apply {
indentArraysWith(DefaultPrettyPrinter.FixedSpaceIndenter.instance)
indentObjectsWith(DefaultIndenter(" ", "\n"))
},
)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
| 9 | null | 1 | 2 | d65d38657bdee740931fbf94b527a91d53a6b5c8 | 3,230 | tiltakspenger-vedtak | MIT License |
src/main/kotlin/com/github/gradle/node/variant/VariantComputer.kt | node-gradle | 160,181,282 | false | null | package com.github.gradle.node.variant
import com.github.gradle.node.NodeExtension
import com.github.gradle.node.util.PlatformHelper
import com.github.gradle.node.util.mapIf
import com.github.gradle.node.util.zip
import org.gradle.api.file.Directory
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
/**
* Get the expected node binary name, node.exe on Windows and node everywhere else.
*/
fun computeNodeExec(nodeExtension: NodeExtension, nodeBinDirProvider: Provider<Directory>): Provider<String> {
return zip(nodeExtension.download, nodeBinDirProvider).map {
val (download, nodeBinDir) = it
if (download) {
val nodeCommand = if (nodeExtension.computedPlatform.get().isWindows()) "node.exe" else "node"
nodeBinDir.dir(nodeCommand).asFile.absolutePath
} else "node"
}
}
fun computeNpmScriptFile(nodeDirProvider: Provider<Directory>, command: String, isWindows: Boolean): Provider<String> {
return nodeDirProvider.map { nodeDir ->
if (isWindows) nodeDir.dir("node_modules/npm/bin/$command-cli.js").asFile.path
else nodeDir.dir("lib/node_modules/npm/bin/$command-cli.js").asFile.path
}
}
fun computeNodeDir(nodeExtension: NodeExtension): Provider<Directory> {
val osName = nodeExtension.computedPlatform.get().name
val osArch = nodeExtension.computedPlatform.get().arch
return computeNodeDir(nodeExtension, osName, osArch)
}
fun computeNodeDir(nodeExtension: NodeExtension, osName: String, osArch: String): Provider<Directory> {
return zip(nodeExtension.workDir, nodeExtension.version).map { (workDir, version) ->
val dirName = "node-v$version-$osName-$osArch"
workDir.dir(dirName)
}
}
/**
* Get the node archive name in Gradle dependency format, using zip for Windows and tar.gz everywhere else.
*
* Essentially: org.nodejs:node:$version:[email protected]
*/
fun computeNodeArchiveDependency(extension: NodeExtension): Provider<String> {
val osName = extension.computedPlatform.get().name
val osArch = extension.computedPlatform.get().arch
val type = if (extension.computedPlatform.get().isWindows()) "zip" else "tar.gz"
return extension.version.map { version -> "org.nodejs:node:$version:$osName-$osArch@$type" }
}
open class VariantComputer constructor(
private val platformHelper: PlatformHelper
) {
constructor() : this(PlatformHelper.INSTANCE)
/**
* Get the expected directory for a given node version.
*
* Essentially: workingDir/node-v$version-$osName-$osArch
*/
@Deprecated(message = "moved to NodeExtension", replaceWith = ReplaceWith("nodeExtension.resolvedNodeDir"))
fun computeNodeDir(nodeExtension: NodeExtension): Provider<Directory> {
val osName = platformHelper.osName
val osArch = platformHelper.osArch
return computeNodeDir(nodeExtension, osName, osArch)
}
/**
* Get the expected node binary directory, taking Windows specifics into account.
*/
fun computeNodeBinDir(nodeDirProvider: Provider<Directory>) = computeProductBinDir(nodeDirProvider)
/**
* Get the expected node binary name, node.exe on Windows and node everywhere else.
*/
@Deprecated(message = "replaced by package-level function",
replaceWith =
ReplaceWith("com.github.gradle.node.variant.computeNodeExec(nodeExtension, nodeBinDirProvider)"))
fun computeNodeExec(nodeExtension: NodeExtension, nodeBinDirProvider: Provider<Directory>): Provider<String> {
return com.github.gradle.node.variant.computeNodeExec(nodeExtension, nodeBinDirProvider)
}
/**
* Get the expected directory for a given npm version.
*/
fun computeNpmDir(nodeExtension: NodeExtension, nodeDirProvider: Provider<Directory>): Provider<Directory> {
return zip(nodeExtension.npmVersion, nodeExtension.npmWorkDir, nodeDirProvider).map {
val (npmVersion, npmWorkDir, nodeDir) = it
if (npmVersion.isNotBlank()) {
val directoryName = "npm-v${npmVersion}"
npmWorkDir.dir(directoryName)
} else nodeDir
}
}
/**
* Get the expected npm binary directory, taking Windows specifics into account.
*/
fun computeNpmBinDir(npmDirProvider: Provider<Directory>) = computeProductBinDir(npmDirProvider)
/**
* Get the expected node binary name, npm.cmd on Windows and npm everywhere else.
*
* Can be overridden by setting npmCommand.
*/
fun computeNpmExec(nodeExtension: NodeExtension, npmBinDirProvider: Provider<Directory>): Provider<String> {
return zip(nodeExtension.download, nodeExtension.npmCommand, npmBinDirProvider).map {
val (download, npmCommand, npmBinDir) = it
val command = if (nodeExtension.computedPlatform.get().isWindows()) {
npmCommand.mapIf({ it == "npm" }) { "npm.cmd" }
} else npmCommand
if (download) npmBinDir.dir(command).asFile.absolutePath else command
}
}
@Deprecated(message = "replaced by package-level function")
fun computeNpmScriptFile(nodeDirProvider: Provider<Directory>, command: String): Provider<String> {
return computeNpmScriptFile(nodeDirProvider, command, platformHelper.isWindows)
}
/**
* Get the expected node binary name, npx.cmd on Windows and npx everywhere else.
*
* Can be overridden by setting npxCommand.
*/
fun computeNpxExec(nodeExtension: NodeExtension, npmBinDirProvider: Provider<Directory>): Provider<String> {
return zip(nodeExtension.download, nodeExtension.npxCommand, npmBinDirProvider).map {
val (download, npxCommand, npmBinDir) = it
val command = if (nodeExtension.computedPlatform.get().isWindows()) {
npxCommand.mapIf({ it == "npx" }) { "npx.cmd" }
} else npxCommand
if (download) npmBinDir.dir(command).asFile.absolutePath else command
}
}
fun computePnpmDir(nodeExtension: NodeExtension): Provider<Directory> {
return zip(nodeExtension.pnpmVersion, nodeExtension.pnpmWorkDir).map {
val (pnpmVersion, pnpmWorkDir) = it
val dirnameSuffix = if (pnpmVersion.isNotBlank()) {
"-v${pnpmVersion}"
} else "-latest"
val dirname = "pnpm$dirnameSuffix"
pnpmWorkDir.dir(dirname)
}
}
fun computePnpmBinDir(pnpmDirProvider: Provider<Directory>) = computeProductBinDir(pnpmDirProvider)
fun computePnpmExec(nodeExtension: NodeExtension, pnpmBinDirProvider: Provider<Directory>): Provider<String> {
return zip(nodeExtension.pnpmCommand, nodeExtension.download, pnpmBinDirProvider).map {
val (pnpmCommand, download, pnpmBinDir) = it
val command = if (nodeExtension.computedPlatform.get().isWindows()) {
pnpmCommand.mapIf({ it == "pnpm" }) { "pnpm.cmd" }
} else pnpmCommand
if (download) pnpmBinDir.dir(command).asFile.absolutePath else command
}
}
fun computeYarnDir(nodeExtension: NodeExtension): Provider<Directory> {
return zip(nodeExtension.yarnVersion, nodeExtension.yarnWorkDir).map {
val (yarnVersion, yarnWorkDir) = it
val dirnameSuffix = if (yarnVersion.isNotBlank()) {
"-v${yarnVersion}"
} else "-latest"
val dirname = "yarn$dirnameSuffix"
yarnWorkDir.dir(dirname)
}
}
fun computeYarnBinDir(yarnDirProvider: Provider<Directory>) = computeProductBinDir(yarnDirProvider)
fun computeYarnExec(nodeExtension: NodeExtension, yarnBinDirProvider: Provider<Directory>): Provider<String> {
return zip(nodeExtension.yarnCommand, nodeExtension.download, yarnBinDirProvider).map {
val (yarnCommand, download, yarnBinDir) = it
val command = if (nodeExtension.computedPlatform.get().isWindows()) {
yarnCommand.mapIf({ it == "yarn" }) { "yarn.cmd" }
} else yarnCommand
if (download) yarnBinDir.dir(command).asFile.absolutePath else command
}
}
private fun computeProductBinDir(productDirProvider: Provider<Directory>) =
if (platformHelper.isWindows) productDirProvider else productDirProvider.map { it.dir("bin") }
/**
* Get the node archive name in Gradle dependency format, using zip for Windows and tar.gz everywhere else.
*
* Essentially: org.nodejs:node:$version:[email protected]
*/
@Deprecated(message = "replaced by package-level function",
replaceWith = ReplaceWith("com.github.gradle.node.variant.computeNodeArchiveDependency(nodeExtension)"))
fun computeNodeArchiveDependency(nodeExtension: NodeExtension): Provider<String> {
return com.github.gradle.node.variant.computeNodeArchiveDependency(nodeExtension)
}
/**
* Get the node archive name in Gradle dependency format, using zip for Windows and tar.gz everywhere else.
*
* Essentially: org.nodejs:node:$version:[email protected]
*/
@Deprecated(message = "replaced by package-level function",
replaceWith = ReplaceWith("com.github.gradle.node.variant.computeNodeArchiveDependency(nodeExtension)"))
fun computeNodeArchiveDependency(nodeVersion: Property<String>): Provider<String> {
val osName = platformHelper.osName
val osArch = platformHelper.osArch
val type = if (platformHelper.isWindows) "zip" else "tar.gz"
return nodeVersion.map { version -> "org.nodejs:node:$version:$osName-$osArch@$type" }
}
}
| 72 | null | 76 | 533 | f327f5ae4580ea4a76b6526732cacdcbc9f241dd | 9,681 | gradle-node-plugin | Apache License 2.0 |
quick/src/main/java/com/hansoolabs/and/view/KeyboardVisibleListener.kt | brownsoo | 115,618,961 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 57, "XML": 29, "Java": 2} | package com.hansoolabs.and.view
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import androidx.fragment.app.Fragment
/**
* Created by brownsoo on 2018-11-11.
*/
interface OnKeyboardVisibleListener {
fun onKeyboardVisible(visible: Boolean)
}
class KeyboardVisibleListener {
constructor(fragment: Fragment,
listener: OnKeyboardVisibleListener? = null) {
root = fragment.view
this.listener = listener
}
constructor(activity: Activity,
listener: OnKeyboardVisibleListener? = null) {
root = activity.window.decorView.findViewById(android.R.id.content)
this.listener = listener
}
private var root: View? = null
var isKeyboardVisible: Boolean = false
private set
var listener: OnKeyboardVisibleListener? = null
private val layoutListener = ViewTreeObserver.OnGlobalLayoutListener {
val r = Rect()
root?.getWindowVisibleDisplayFrame(r)
val screenHeight = root?.rootView?.height ?: return@OnGlobalLayoutListener
// r.bottom is the position above soft keypad or device button.
// if keypad is isKeyboardVisible, the r.bottom is smaller than that before.
val keyboardHeight = screenHeight - r.bottom
var showing = false
if (keyboardHeight > screenHeight * 0.15) {
showing = true
} else if (keyboardHeight <= screenHeight * 0.15) {
showing = false
}
if (isKeyboardVisible != showing) {
isKeyboardVisible = showing
listener?.onKeyboardVisible(isKeyboardVisible)
}
}
fun listen() {
val observer = root?.viewTreeObserver
if (observer?.isAlive != true) {
return
}
observer.addOnGlobalLayoutListener(layoutListener)
}
fun avoid() {
root?.viewTreeObserver?.removeOnGlobalLayoutListener(layoutListener)
}
} | 1 | null | 1 | 1 | b31fd4f6f23d94d7a8ff54178edeee6423c6aeda | 2,019 | QuickAndComponent | MIT License |
mockmp-runtime/src/commonMain/kotlin/org/kodein/mock/MockSuspendFunctions.kt | kosi-libs | 426,590,561 | false | {"Kotlin": 111002} | package org.kodein.mock
public suspend fun <R>
mockSuspendFunction0(
mocker: Mocker,
functionName: String = defaultFunctionName,
block: (suspend () -> R)? = null
): suspend () -> R =
Anonymous().let { rec ->
val f: suspend () -> R = {
mocker.registerSuspend(rec, "$functionName()")
}
f
}.also {
if (block != null) mocker.everySuspending { it() } runs { block() }
}
public suspend inline fun <R, reified A1>
mockSuspendFunction1(
mocker: Mocker,
a1Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1) -> R)? = null
): suspend (A1) -> R =
Anonymous().let { rec ->
val f: suspend (A1) -> R = { a1 ->
mocker.registerSuspend(rec, "$functionName($a1Type)", a1)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny()) } runs { block(it[0] as A1) }
}
public suspend inline fun <R, reified A1, reified A2>
mockSuspendFunction2(
mocker: Mocker,
a1Type: String, a2Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2) -> R)? = null
): suspend (A1, A2) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2) -> R = { a1, a2 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type)", a1, a2)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3>
mockSuspendFunction3(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3) -> R)? = null
): suspend (A1, A2, A3) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3) -> R = { a1, a2, a3 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type)", a1, a2, a3)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4>
mockSuspendFunction4(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4) -> R)? = null
): suspend (A1, A2, A3, A4) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4) -> R = { a1, a2, a3, a4 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type)", a1, a2, a3, a4)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5>
mockSuspendFunction5(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5) -> R)? = null
): suspend (A1, A2, A3, A4, A5) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5) -> R = { a1, a2, a3, a4, a5 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type)", a1, a2, a3, a4, a5)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6>
mockSuspendFunction6(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String, a6Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5, A6) -> R = { a1, a2, a3, a4, a5, a6 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type, $a6Type)", a1, a2, a3, a4, a5, a6)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5, it[5] as A6) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7>
mockSuspendFunction7(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String, a6Type: String, a7Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5, A6, A7) -> R = { a1, a2, a3, a4, a5, a6, a7 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type, $a6Type, $a7Type)", a1, a2, a3, a4, a5, a6, a7)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5, it[5] as A6, it[6] as A7) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8>
mockSuspendFunction8(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String, a6Type: String, a7Type: String, a8Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R = { a1, a2, a3, a4, a5, a6, a7, a8 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type, $a6Type, $a7Type, $a8Type)", a1, a2, a3, a4, a5, a6, a7, a8)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5, it[5] as A6, it[6] as A7, it[7] as A8) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8, reified A9>
mockSuspendFunction9(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String, a6Type: String, a7Type: String, a8Type: String, a9Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R = { a1, a2, a3, a4, a5, a6, a7, a8, a9 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type, $a6Type, $a7Type, $a8Type, $a9Type)", a1, a2, a3, a4, a5, a6, a7, a8, a9)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5, it[5] as A6, it[6] as A7, it[7] as A8, it[8] as A9) }
}
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8, reified A9, reified A10>
mockSuspendFunction10(
mocker: Mocker,
a1Type: String, a2Type: String, a3Type: String, a4Type: String, a5Type: String, a6Type: String, a7Type: String, a8Type: String, a9Type: String, a10Type: String,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R =
Anonymous().let { rec ->
val f: suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R = { a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 ->
mocker.registerSuspend(rec, "$functionName($a1Type, $a2Type, $a3Type, $a4Type, $a5Type, $a6Type, $a7Type, $a8Type, $a9Type, $a10Type)", a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)
}
f
}.also {
if (block != null) mocker.everySuspending { it(isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny(), isAny()) } runs { block(it[0] as A1, it[1] as A2, it[2] as A3, it[3] as A4, it[4] as A5, it[5] as A6, it[6] as A7, it[7] as A8, it[8] as A9, it[9] as A10) }
}
public suspend inline fun <R, reified A1>
mockSuspendFunction1(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1) -> R)? = null
): suspend (A1) -> R =
mockSuspendFunction1(mocker, A1::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2>
mockSuspendFunction2(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2) -> R)? = null
): suspend (A1, A2) -> R =
mockSuspendFunction2(mocker, A1::class.bestName(), A2::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3>
mockSuspendFunction3(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3) -> R)? = null
): suspend (A1, A2, A3) -> R =
mockSuspendFunction3(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4>
mockSuspendFunction4(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4) -> R)? = null
): suspend (A1, A2, A3, A4) -> R =
mockSuspendFunction4(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5>
mockSuspendFunction5(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5) -> R)? = null
): suspend (A1, A2, A3, A4, A5) -> R =
mockSuspendFunction5(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6>
mockSuspendFunction6(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6) -> R =
mockSuspendFunction6(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), A6::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7>
mockSuspendFunction7(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7) -> R =
mockSuspendFunction7(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), A6::class.bestName(), A7::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8>
mockSuspendFunction8(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R =
mockSuspendFunction8(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), A6::class.bestName(), A7::class.bestName(), A8::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8, reified A9>
mockSuspendFunction9(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R =
mockSuspendFunction9(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), A6::class.bestName(), A7::class.bestName(), A8::class.bestName(), A9::class.bestName(), functionName, block)
public suspend inline fun <R, reified A1, reified A2, reified A3, reified A4, reified A5, reified A6, reified A7, reified A8, reified A9, reified A10>
mockSuspendFunction10(
mocker: Mocker,
functionName: String = defaultFunctionName,
noinline block: (suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R)? = null
): suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R =
mockSuspendFunction10(mocker, A1::class.bestName(), A2::class.bestName(), A3::class.bestName(), A4::class.bestName(), A5::class.bestName(), A6::class.bestName(), A7::class.bestName(), A8::class.bestName(), A9::class.bestName(), A10::class.bestName(), functionName, block)
| 9 | Kotlin | 12 | 160 | 50e8df40bc8faedce6a9186aa6629dcc04350a3d | 13,688 | MocKMP | MIT License |
shared/src/commonMain/kotlin/com/dino/unsplash/shared/data/PhotoRepository.kt | dinopriyano | 511,626,455 | false | {"Kotlin": 26902, "Swift": 4996, "Ruby": 1794} | package com.dino.unsplash.shared.data
import com.dino.unsplash.shared.data.model.response.PhotoItem
interface PhotoRepository {
suspend fun getPhotos(page: Int, perPage: Int, orderBy: String): List<PhotoItem>
} | 0 | Kotlin | 0 | 0 | e21836d28b6fab296e8ffd18abd512de6c478429 | 216 | Unplash-Mobile | Apache License 2.0 |
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/settings/PropertiesFacade.kt | detekt | 71,729,669 | false | null | package io.gitlab.arturbosch.detekt.core.settings
import io.gitlab.arturbosch.detekt.api.PropertiesAware
import io.gitlab.arturbosch.detekt.api.UnstableApi
import java.util.concurrent.ConcurrentHashMap
@OptIn(UnstableApi::class)
internal class PropertiesFacade : PropertiesAware {
private val _properties: MutableMap<String, Any?> = ConcurrentHashMap()
override val properties: Map<String, Any?> = _properties
override fun register(key: String, value: Any) {
_properties[key] = value
}
}
| 190 | null | 772 | 6,253 | c5d7ed3da2824534d0e15f8404ad4f1c59fb553c | 516 | detekt | Apache License 2.0 |
android/src/main/java/me/ashishekka/k8/android/RomPickerActivity.kt | AshishEkka97 | 542,257,044 | false | {"Kotlin": 80665, "Ruby": 1672, "Swift": 312, "HTML": 197} | @file:OptIn(ExperimentalMaterialApi::class)
package me.ashishekka.k8.android
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Colors
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalElevationOverlay
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.primarySurface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.ashishekka.k8.android.theming.fullScaffoldBackground
import me.ashishekka.k8.android.theming.getThemeColors
import me.ashishekka.k8.configs.ColorScheme
import me.ashishekka.k8.storage.K8Settings
import me.ashishekka.k8.storage.KEY_THEME
const val PICKED_ROM_PATH = "PICKED_ROM_PATH"
class RomPickerActivity : AppCompatActivity() {
private val setting by lazy { K8Settings() }
private val romFileList: MutableState<List<RomFile>> = mutableStateOf(emptyList())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
val themeState = setting.getIntSetting(KEY_THEME).collectAsState(0)
val theme = ColorScheme.getThemeFromIndex(themeState.value)
RomPickerScreen(getThemeColors(theme), romFileList.value, ::onRomFileClicked) {
onBackPressedDispatcher.onBackPressed()
}
}
loadRomFiles()
}
override fun onDestroy() {
val returnIntent = Intent()
setResult(RESULT_CANCELED, returnIntent)
super.onDestroy()
}
private fun loadRomFiles() {
lifecycleScope.launch(Dispatchers.IO) {
val fileNames = assets.list("c8games")
val romFiles = fileNames?.mapNotNull { fileName ->
if (fileName != null) {
val filePath = "c8games/$fileName"
RomFile(
romName = fileName,
romPath = filePath
)
} else {
null
}
} ?: emptyList()
romFileList.value = romFiles
}
}
private fun onRomFileClicked(romFile: RomFile) {
val returnIntent = Intent().apply {
putExtra(PICKED_ROM_PATH, romFile.romPath)
}
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
}
@Composable
fun RomPickerScreen(
themeColors: Colors,
files: List<RomFile>,
onRomFileClicked: (RomFile) -> Unit,
onBackClicked: () -> Unit
) {
MaterialTheme(colors = themeColors) { // or AppCompatTheme
Scaffold(
modifier = Modifier.background(
fullScaffoldBackground(
color = MaterialTheme.colors.primarySurface,
elevationOverlay = LocalElevationOverlay.current
)
).safeDrawingPadding(),
topBar = {
TopAppBar(
title = { Text("Load ROM", color = MaterialTheme.colors.primary) },
navigationIcon = {
IconButton(onBackClicked) {
Icon(
ImageVector.vectorResource(R.drawable.ic_back),
"Back to previous screen",
tint = MaterialTheme.colors.primary
)
}
}
)
}
) {
RomFileList(it, files, onRomFileClicked)
}
}
}
@Composable
fun RomFileList(
paddingValues: PaddingValues,
files: List<RomFile>,
onRomFileClicked: (RomFile) -> Unit
) {
LazyColumn(
modifier = Modifier.padding(paddingValues).fillMaxWidth()
) {
items(files) { romFile ->
Surface(
onClick = { onRomFileClicked(romFile) },
modifier = Modifier.fillMaxWidth()
) {
Text(
romFile.romName,
modifier = Modifier.padding(vertical = 12.dp, horizontal = 8.dp),
color = MaterialTheme.colors.primary
)
}
}
}
}
data class RomFile(
val romName: String,
val romPath: String
)
| 0 | Kotlin | 0 | 2 | 9629766d916cdf15ac7c877582966de97cebb3ff | 5,509 | k8 | MIT License |
src/main/kotlin/kotcity/data/Economy.kt | kotcity | 123,993,966 | false | null | package kotcity.data
import com.github.debop.kodatimes.dateTimeFromJson
import kotcity.pathfinding.Path
import kotcity.util.Debuggable
enum class Tradeable {
MONEY,
GOODS,
LABOR,
RAW_MATERIALS,
WHOLESALE_GOODS
}
object Prices {
fun priceForGoods(tradeable: Tradeable, quantity: Int): Int {
return when (tradeable) {
Tradeable.MONEY -> quantity * 1
Tradeable.GOODS -> quantity * 5
Tradeable.LABOR -> quantity * 1
Tradeable.RAW_MATERIALS -> quantity * 1
Tradeable.WHOLESALE_GOODS -> quantity * 3
}
}
}
interface TradeEntity {
fun description(): String?
fun building(): Building?
val coordinate: BlockCoordinate
fun addContract(contract: Contract)
fun createContract(otherTradeEntity: TradeEntity, tradeable: Tradeable, quantity: Int, path: Path)
fun voidContractsWith(otherTradeEntity: TradeEntity)
fun hasAnyContracts(): Boolean
fun currentQuantityForSale(tradeable: Tradeable): Int
fun currentQuantityWanted(tradeable: Tradeable): Int
fun producesQuantity(tradeable: Tradeable): Int
fun consumesQuantity(tradeable: Tradeable): Int
fun quantityOnHand(tradeable: Tradeable): Int
}
data class CityTradeEntity(override val coordinate: BlockCoordinate, val building: Building) : TradeEntity {
override fun hasAnyContracts(): Boolean {
return building.hasAnyContracts()
}
override fun quantityOnHand(tradeable: Tradeable): Int {
return building.quantityOnHand(tradeable)
}
override fun createContract(otherTradeEntity: TradeEntity, tradeable: Tradeable, quantity: Int, path: Path) {
building.createContract(otherTradeEntity, tradeable, quantity, path)
}
override fun voidContractsWith(otherTradeEntity: TradeEntity) {
building.voidContractsWith(otherTradeEntity)
}
override fun addContract(contract: Contract) {
building.addContract(contract)
}
override fun building(): Building? {
return building
}
override fun description(): String? {
return building.description
}
override fun producesQuantity(tradeable: Tradeable): Int {
return building.producesQuantity(tradeable)
}
override fun consumesQuantity(tradeable: Tradeable): Int {
return building.consumesQuantity(tradeable)
}
override fun currentQuantityForSale(tradeable: Tradeable): Int {
return building.currentQuantityForSale(tradeable)
}
override fun currentQuantityWanted(tradeable: Tradeable): Int {
return building.currentQuantityWanted(tradeable)
}
}
data class Contract(
val from: TradeEntity,
val to: TradeEntity,
val tradeable: Tradeable,
val quantity: Int,
val path: kotcity.pathfinding.Path?
): Debuggable {
override var debug: Boolean = false
override fun toString(): String {
return "Contract(to=${to.description()} from=${from.description()} tradeable=$tradeable quantity=$quantity)"
}
fun execute(): Boolean {
// get the hash order so we can lock deterministically...
val (first, second) = listOf(from, to).sortedBy { System.identityHashCode(it) }
synchronized(first) {
synchronized(second) {
// here is where we actually do the transfer...
val quantityWanted = to.currentQuantityWanted(tradeable)
val quantityAvailable = from.quantityOnHand(tradeable)
if (quantityAvailable >= quantityWanted) {
// we can actually do it...
val building = from.building() ?: return false
val otherBuilding = to.building() ?: return false
debug("The customer (${otherBuilding.description}) naturally wants this many $tradeable: ${otherBuilding.consumesQuantity(tradeable)}")
// try to put double what the customer wants there....
val doubleTradeable = otherBuilding.consumesQuantity(tradeable) * 2
debug("So let's try and make sure they have $doubleTradeable")
val customerWantsQuantity = doubleTradeable - otherBuilding.quantityOnHand(tradeable)
debug("They already have ${otherBuilding.quantityOnHand(tradeable)}")
debug("So they want $customerWantsQuantity more...")
// ok... pick whatever is least... how many we have in inventory OR how much the other guy wants...
val howManyToSend = listOf(customerWantsQuantity, building.quantityOnHand(tradeable)).min() ?: 0
if (howManyToSend > 0) {
debug("We have ${building.quantityOnHand(tradeable)} and we will send them $howManyToSend")
debug("Before transfer... building has $${building.quantityOnHand(Tradeable.MONEY)}")
val howManyTransferred = building.transferInventory(to, tradeable, howManyToSend)
building.addInventory(Tradeable.MONEY, Prices.priceForGoods(tradeable, howManyTransferred))
debug("${building.description}: We transferred $howManyToSend $tradeable to ${to.description()}")
debug("After transfer... building has $${building.quantityOnHand(Tradeable.MONEY)}")
} else {
debug("${building.description } wanted to send $quantity $tradeable but it was out of stock...")
return false
}
}
}
}
return true
}
fun void() {
// get the hash order so we can lock deterministically...
val (first, second) = listOf(from, to).sortedBy { System.identityHashCode(it) }
synchronized(first) {
synchronized(second) {
first.voidContractsWith(second)
second.voidContractsWith(first)
}
}
}
}
class Inventory {
private val inventory : MutableMap<Tradeable, Int> = mutableMapOf()
fun add(tradeable: Tradeable, quantity: Int): Int {
val onHand = inventory.getOrDefault(tradeable, 0)
inventory[tradeable] = onHand + quantity
return inventory[tradeable] ?: 0
}
fun subtract(tradeable: Tradeable, quantity: Int): Int {
val onHand = inventory.getOrDefault(tradeable, 0)
inventory[tradeable] = onHand - quantity
return inventory[tradeable] ?: 0
}
fun has(tradeable: Tradeable, quantity: Int): Boolean {
return inventory.getOrDefault(tradeable, 0) >= quantity
}
fun quantity(tradeable: Tradeable): Int {
return inventory.getOrDefault(tradeable, 0)
}
fun forEach(action: (Tradeable, Int) -> Unit) {
inventory.forEach { entry ->
action(entry.key, entry.value)
}
}
fun put(tradeable: Tradeable, quantity: Int): Int {
return inventory.put(tradeable, quantity) ?: 0
}
} | 0 | null | 23 | 480 | 0ee1cbf4ad345c956f4f2bcfc65bb0b2b423eb3b | 7,066 | kotcity | Apache License 2.0 |
app/src/main/java/com/vitovalov/taxilocator/domain/GetVehiclesUseCase.kt | vitovalov | 199,463,540 | false | null | package com.vitovalov.taxilocator.domain
import com.vitovalov.taxilocator.domain.bo.GetVehiclesResponse
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.Disposables
class GetVehiclesUseCase(
private val vehiclesRepository: VehiclesRepository,
private val observeOn: Scheduler,
private val subscribeOn: Scheduler
) {
private var subscription: Disposable = Disposables.empty()
fun execute(
lat1: Float,
lon1: Float,
lat2: Float,
lon2: Float,
onComplete: (GetVehiclesResponse) -> Unit,
onError: (Throwable) -> Unit
) {
subscription = vehiclesRepository.getVehicles(lat1, lon1, lat2, lon2)
.subscribeOn(subscribeOn)
.observeOn(observeOn)
.subscribe(onComplete, onError)
}
fun clear() {
if (!subscription.isDisposed) {
subscription.dispose()
}
}
} | 0 | Kotlin | 0 | 0 | 01857b4ab3d0d4843246a9272dbf2e9c9b2b1b10 | 959 | TaxiLocator | Apache License 2.0 |
data/src/main/java/com/hackertronix/data/repository/OverviewRepository.kt | kapiljhajhria | 249,911,789 | true | {"Kotlin": 54664} | package com.hackertronix.data.repository
import com.hackertronix.data.local.Covid19StatsDatabase
import com.hackertronix.data.network.API
import com.hackertronix.model.overview.Overview
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class OverviewRepository(
private val apiClient: API,
private val database: Covid19StatsDatabase
) {
fun getOverview(): Observable<Overview> {
return database.overviewDao().getOverview()
.toObservable()
.flatMap {
if (it.isEmpty()) {
return@flatMap getOverviewFromApi()
}
return@flatMap Observable.just(it.first())
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
private fun getOverviewFromApi(): Observable<Overview>? {
return apiClient.getOverview().toObservable()
.doOnNext {
database.overviewDao().deleteOverview()
database.overviewDao().insertOverview(it)
}
}
} | 0 | null | 0 | 0 | 1955520be2a68e5cfda4f9b055a28016c3e22c97 | 1,139 | 91-DIVOC | Apache License 2.0 |
lib/src/main/java/com/zyyoona7/extensions/toast.kt | zyyoona7 | 101,261,210 | false | null | package com.zj.utils.extends
import android.app.Fragment
import android.content.Context
import android.view.View
import android.widget.Toast
/**
* Created by zyyoona7 on 2017/8/24.
* Toast 扩展函数
*/
/*
---------- Context ----------
*/
fun Context.toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
if (duration == 0 || duration == 1) {
Toast.makeText(applicationContext, msg, duration).show()
} else {
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
}
}
/*
---------- Fragment ----------
*/
fun Fragment.toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
activity?.toast(msg, duration)
}
fun androidx.fragment.app.Fragment.toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
activity?.toast(msg, duration)
}
/*
---------- View ----------
*/
fun View.toast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
context.toast(msg, duration)
} | 1 | null | 12 | 94 | d6c6bb22f125e8cb30c97be3d5b508a1645a0c8c | 929 | KExtensions | Apache License 2.0 |
presentation-core/src/main/java/tachiyomi/presentation/core/util/Preference.kt | mihonapp | 743,704,912 | false | null | package tachiyomi.presentation.core.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import tachiyomi.core.preference.Preference
@Composable
fun <T> Preference<T>.collectAsState(): State<T> {
val flow = remember(this) { changes() }
return flow.collectAsState(initial = get())
}
| 83 | null | 447 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 413 | mihon | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/opsworks/CfnStackPropsDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.opsworks
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import io.cloudshiftdev.awscdkdsl.common.MapBuilder
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.opsworks.CfnStack
import software.amazon.awscdk.services.opsworks.CfnStackProps
/**
* Properties for defining a `CfnStack`.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.opsworks.*;
* Object customJson;
* CfnStackProps cfnStackProps = CfnStackProps.builder()
* .defaultInstanceProfileArn("defaultInstanceProfileArn")
* .name("name")
* .serviceRoleArn("serviceRoleArn")
* // the properties below are optional
* .agentVersion("agentVersion")
* .attributes(Map.of(
* "attributesKey", "attributes"))
* .chefConfiguration(ChefConfigurationProperty.builder()
* .berkshelfVersion("berkshelfVersion")
* .manageBerkshelf(false)
* .build())
* .cloneAppIds(List.of("cloneAppIds"))
* .clonePermissions(false)
* .configurationManager(StackConfigurationManagerProperty.builder()
* .name("name")
* .version("version")
* .build())
* .customCookbooksSource(SourceProperty.builder()
* .password("password")
* .revision("revision")
* .sshKey("sshKey")
* .type("type")
* .url("url")
* .username("username")
* .build())
* .customJson(customJson)
* .defaultAvailabilityZone("defaultAvailabilityZone")
* .defaultOs("defaultOs")
* .defaultRootDeviceType("defaultRootDeviceType")
* .defaultSshKeyName("defaultSshKeyName")
* .defaultSubnetId("defaultSubnetId")
* .ecsClusterArn("ecsClusterArn")
* .elasticIps(List.of(ElasticIpProperty.builder()
* .ip("ip")
* // the properties below are optional
* .name("name")
* .build()))
* .hostnameTheme("hostnameTheme")
* .rdsDbInstances(List.of(RdsDbInstanceProperty.builder()
* .dbPassword("dbPassword")
* .dbUser("dbUser")
* .rdsDbInstanceArn("rdsDbInstanceArn")
* .build()))
* .sourceStackId("sourceStackId")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .useCustomCookbooks(false)
* .useOpsworksSecurityGroups(false)
* .vpcId("vpcId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html)
*/
@CdkDslMarker
public class CfnStackPropsDsl {
private val cdkBuilder: CfnStackProps.Builder = CfnStackProps.builder()
private val _cloneAppIds: MutableList<String> = mutableListOf()
private val _elasticIps: MutableList<Any> = mutableListOf()
private val _rdsDbInstances: MutableList<Any> = mutableListOf()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* @param agentVersion The default AWS OpsWorks Stacks agent version. You have the following
* options:.
* * Auto-update - Set this parameter to `LATEST` . AWS OpsWorks Stacks automatically installs
* new agent versions on the stack's instances as soon as they are available.
* * Fixed version - Set this parameter to your preferred agent version. To update the agent
* version, you must edit the stack configuration and specify a new version. AWS OpsWorks
* Stacks installs that version on the stack's instances.
*
* The default setting is the most recent release of the agent. To specify an agent version, you
* must use the complete version number, not the abbreviated number shown on the console. For a
* list of available agent version numbers, call `DescribeAgentVersions` . AgentVersion cannot
* be set to Chef 12.2.
*
* You can also specify an agent version when you create or update an instance, which overrides
* the stack's default setting.
*/
public fun agentVersion(agentVersion: String) {
cdkBuilder.agentVersion(agentVersion)
}
/**
* @param attributes One or more user-defined key-value pairs to be added to the stack
* attributes.
*/
public fun attributes(attributes: Map<String, String>) {
cdkBuilder.attributes(attributes)
}
/**
* @param attributes One or more user-defined key-value pairs to be added to the stack
* attributes.
*/
public fun attributes(attributes: IResolvable) {
cdkBuilder.attributes(attributes)
}
/**
* @param chefConfiguration A `ChefConfiguration` object that specifies whether to enable
* Berkshelf and the Berkshelf version on Chef 11.10 stacks. For more information, see
* [Create a New Stack](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html)
* .
*/
public fun chefConfiguration(chefConfiguration: IResolvable) {
cdkBuilder.chefConfiguration(chefConfiguration)
}
/**
* @param chefConfiguration A `ChefConfiguration` object that specifies whether to enable
* Berkshelf and the Berkshelf version on Chef 11.10 stacks. For more information, see
* [Create a New Stack](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html)
* .
*/
public fun chefConfiguration(chefConfiguration: CfnStack.ChefConfigurationProperty) {
cdkBuilder.chefConfiguration(chefConfiguration)
}
/**
* @param cloneAppIds If you're cloning an AWS OpsWorks stack, a list of AWS OpsWorks
* application stack IDs from the source stack to include in the cloned stack.
*/
public fun cloneAppIds(vararg cloneAppIds: String) {
_cloneAppIds.addAll(listOf(*cloneAppIds))
}
/**
* @param cloneAppIds If you're cloning an AWS OpsWorks stack, a list of AWS OpsWorks
* application stack IDs from the source stack to include in the cloned stack.
*/
public fun cloneAppIds(cloneAppIds: Collection<String>) {
_cloneAppIds.addAll(cloneAppIds)
}
/**
* @param clonePermissions If you're cloning an AWS OpsWorks stack, indicates whether to clone
* the source stack's permissions.
*/
public fun clonePermissions(clonePermissions: Boolean) {
cdkBuilder.clonePermissions(clonePermissions)
}
/**
* @param clonePermissions If you're cloning an AWS OpsWorks stack, indicates whether to clone
* the source stack's permissions.
*/
public fun clonePermissions(clonePermissions: IResolvable) {
cdkBuilder.clonePermissions(clonePermissions)
}
/**
* @param configurationManager The configuration manager. When you create a stack we recommend
* that you use the configuration manager to specify the Chef version: 12, 11.10, or 11.4 for
* Linux stacks, or 12.2 for Windows stacks. The default value for Linux stacks is
* currently 12.
*/
public fun configurationManager(configurationManager: IResolvable) {
cdkBuilder.configurationManager(configurationManager)
}
/**
* @param configurationManager The configuration manager. When you create a stack we recommend
* that you use the configuration manager to specify the Chef version: 12, 11.10, or 11.4 for
* Linux stacks, or 12.2 for Windows stacks. The default value for Linux stacks is
* currently 12.
*/
public fun configurationManager(
configurationManager: CfnStack.StackConfigurationManagerProperty
) {
cdkBuilder.configurationManager(configurationManager)
}
/**
* @param customCookbooksSource Contains the information required to retrieve an app or cookbook
* from a repository. For more information, see
* [Adding Apps](https://docs.aws.amazon.com/opsworks/latest/userguide/workingapps-creating.html)
* or
* [Cookbooks and Recipes](https://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook.html)
* .
*/
public fun customCookbooksSource(customCookbooksSource: IResolvable) {
cdkBuilder.customCookbooksSource(customCookbooksSource)
}
/**
* @param customCookbooksSource Contains the information required to retrieve an app or cookbook
* from a repository. For more information, see
* [Adding Apps](https://docs.aws.amazon.com/opsworks/latest/userguide/workingapps-creating.html)
* or
* [Cookbooks and Recipes](https://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook.html)
* .
*/
public fun customCookbooksSource(customCookbooksSource: CfnStack.SourceProperty) {
cdkBuilder.customCookbooksSource(customCookbooksSource)
}
/**
* @param customJson A string that contains user-defined, custom JSON. It can be used to
* override the corresponding default stack configuration attribute values or to pass data to
* recipes. The string should be in the following format:
*
* `"{\"key1\": \"value1\", \"key2\": \"value2\",...}"`
*
* For more information about custom JSON, see
* [Use Custom JSON to Modify the Stack Configuration Attributes](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html)
* .
*/
public fun customJson(customJson: MapBuilder.() -> Unit = {}) {
val builder = MapBuilder()
builder.apply(customJson)
cdkBuilder.customJson(builder.map)
}
/**
* @param customJson A string that contains user-defined, custom JSON. It can be used to
* override the corresponding default stack configuration attribute values or to pass data to
* recipes. The string should be in the following format:
*
* `"{\"key1\": \"value1\", \"key2\": \"value2\",...}"`
*
* For more information about custom JSON, see
* [Use Custom JSON to Modify the Stack Configuration Attributes](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html)
* .
*/
public fun customJson(customJson: Any) {
cdkBuilder.customJson(customJson)
}
/**
* @param defaultAvailabilityZone The stack's default Availability Zone, which must be in the
* specified region. For more information, see
* [Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html) . If you
* also specify a value for `DefaultSubnetId` , the subnet must be in the same zone. For more
* information, see the `VpcId` parameter description.
*/
public fun defaultAvailabilityZone(defaultAvailabilityZone: String) {
cdkBuilder.defaultAvailabilityZone(defaultAvailabilityZone)
}
/**
* @param defaultInstanceProfileArn The Amazon Resource Name (ARN) of an IAM profile that is the
* default profile for all of the stack's EC2 instances. For more information about IAM ARNs,
* see
* [Using Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html)
* .
*/
public fun defaultInstanceProfileArn(defaultInstanceProfileArn: String) {
cdkBuilder.defaultInstanceProfileArn(defaultInstanceProfileArn)
}
/**
* @param defaultOs The stack's default operating system, which is installed on every instance
* unless you specify a different operating system when you create the instance. You can
* specify one of the following.
* * A supported Linux operating system: An Amazon Linux version, such as `Amazon Linux 2` ,
* `Amazon Linux 2018.03` , `Amazon Linux 2017.09` , `Amazon Linux 2017.03` , `Amazon Linux
* 2016.09` , `Amazon Linux 2016.03` , `Amazon Linux 2015.09` , or `Amazon Linux 2015.03` .
* * A supported Ubuntu operating system, such as `Ubuntu 18.04 LTS` , `Ubuntu 16.04 LTS` ,
* `Ubuntu 14.04 LTS` , or `Ubuntu 12.04 LTS` .
* * `CentOS Linux 7`
* * `Red Hat Enterprise Linux 7`
* * A supported Windows operating system, such as `Microsoft Windows Server 2012 R2 Base` ,
* `Microsoft Windows Server 2012 R2 with SQL Server Express` , `Microsoft Windows Server 2012
* R2 with SQL Server Standard` , or `Microsoft Windows Server 2012 R2 with SQL Server Web` .
* * A custom AMI: `Custom` . You specify the custom AMI you want to use when you create
* instances. For more information, see
* [Using Custom AMIs](https://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html)
* .
*
* The default option is the current Amazon Linux version. Not all operating systems are
* supported with all versions of Chef. For more information about supported operating systems,
* see
* [AWS OpsWorks Stacks Operating Systems](https://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html)
* .
*/
public fun defaultOs(defaultOs: String) {
cdkBuilder.defaultOs(defaultOs)
}
/**
* @param defaultRootDeviceType The default root device type. This value is the default for all
* instances in the stack, but you can override it when you create an instance. The default
* option is `instance-store` . For more information, see
* [Storage for the Root Device](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device)
* .
*/
public fun defaultRootDeviceType(defaultRootDeviceType: String) {
cdkBuilder.defaultRootDeviceType(defaultRootDeviceType)
}
/**
* @param defaultSshKeyName A default Amazon EC2 key pair name. The default value is none. If
* you specify a key pair name, AWS OpsWorks installs the public key on the instance and you
* can use the private key with an SSH client to log in to the instance. For more information,
* see
* [Using SSH to Communicate with an Instance](https://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-ssh.html)
* and
* [Managing SSH Access](https://docs.aws.amazon.com/opsworks/latest/userguide/security-ssh-access.html)
* . You can override this setting by specifying a different key pair, or no key pair, when
* you
* [create an instance](https://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-add.html)
* .
*/
public fun defaultSshKeyName(defaultSshKeyName: String) {
cdkBuilder.defaultSshKeyName(defaultSshKeyName)
}
/**
* @param defaultSubnetId The stack's default subnet ID. All instances are launched into this
* subnet unless you specify another subnet ID when you create the instance. This parameter is
* required if you specify a value for the `VpcId` parameter. If you also specify a value for
* `DefaultAvailabilityZone` , the subnet must be in that zone.
*/
public fun defaultSubnetId(defaultSubnetId: String) {
cdkBuilder.defaultSubnetId(defaultSubnetId)
}
/**
* @param ecsClusterArn The Amazon Resource Name (ARN) of the Amazon Elastic Container Service (
* Amazon ECS ) cluster to register with the AWS OpsWorks stack.
*
* If you specify a cluster that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the cluster.
*/
public fun ecsClusterArn(ecsClusterArn: String) {
cdkBuilder.ecsClusterArn(ecsClusterArn)
}
/**
* @param elasticIps A list of Elastic IP addresses to register with the AWS OpsWorks stack.
*
* If you specify an IP address that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the IP address.
*/
public fun elasticIps(vararg elasticIps: Any) {
_elasticIps.addAll(listOf(*elasticIps))
}
/**
* @param elasticIps A list of Elastic IP addresses to register with the AWS OpsWorks stack.
*
* If you specify an IP address that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the IP address.
*/
public fun elasticIps(elasticIps: Collection<Any>) {
_elasticIps.addAll(elasticIps)
}
/**
* @param elasticIps A list of Elastic IP addresses to register with the AWS OpsWorks stack.
*
* If you specify an IP address that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the IP address.
*/
public fun elasticIps(elasticIps: IResolvable) {
cdkBuilder.elasticIps(elasticIps)
}
/**
* @param hostnameTheme The stack's host name theme, with spaces replaced by underscores. The
* theme is used to generate host names for the stack's instances. By default, `HostnameTheme`
* is set to `Layer_Dependent` , which creates host names by appending integers to the layer's
* short name. The other themes are:
* * `Baked_Goods`
* * `Clouds`
* * `Europe_Cities`
* * `Fruits`
* * `Greek_Deities_and_Titans`
* * `Legendary_creatures_from_Japan`
* * `Planets_and_Moons`
* * `Roman_Deities`
* * `Scottish_Islands`
* * `US_Cities`
* * `Wild_Cats`
*
* To obtain a generated host name, call `GetHostNameSuggestion` , which returns a host name
* based on the current theme.
*/
public fun hostnameTheme(hostnameTheme: String) {
cdkBuilder.hostnameTheme(hostnameTheme)
}
/** @param name The stack name. Stack names can be a maximum of 64 characters. */
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param rdsDbInstances The Amazon Relational Database Service ( Amazon RDS ) database instance
* to register with the AWS OpsWorks stack.
*
* If you specify a database instance that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the database instance.
*/
public fun rdsDbInstances(vararg rdsDbInstances: Any) {
_rdsDbInstances.addAll(listOf(*rdsDbInstances))
}
/**
* @param rdsDbInstances The Amazon Relational Database Service ( Amazon RDS ) database instance
* to register with the AWS OpsWorks stack.
*
* If you specify a database instance that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the database instance.
*/
public fun rdsDbInstances(rdsDbInstances: Collection<Any>) {
_rdsDbInstances.addAll(rdsDbInstances)
}
/**
* @param rdsDbInstances The Amazon Relational Database Service ( Amazon RDS ) database instance
* to register with the AWS OpsWorks stack.
*
* If you specify a database instance that's registered with another AWS OpsWorks stack, AWS
* CloudFormation deregisters the existing association before registering the database instance.
*/
public fun rdsDbInstances(rdsDbInstances: IResolvable) {
cdkBuilder.rdsDbInstances(rdsDbInstances)
}
/**
* @param serviceRoleArn The stack's IAM role, which allows AWS OpsWorks Stacks to work with AWS
* resources on your behalf. You must set this parameter to the Amazon Resource Name (ARN) for
* an existing IAM role. For more information about IAM ARNs, see
* [Using Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html)
* .
*/
public fun serviceRoleArn(serviceRoleArn: String) {
cdkBuilder.serviceRoleArn(serviceRoleArn)
}
/**
* @param sourceStackId If you're cloning an AWS OpsWorks stack, the stack ID of the source AWS
* OpsWorks stack to clone.
*/
public fun sourceStackId(sourceStackId: String) {
cdkBuilder.sourceStackId(sourceStackId)
}
/**
* @param tags A map that contains tag keys and tag values that are attached to a stack or
* layer.
* * The key cannot be empty.
* * The key can be a maximum of 127 characters, and can contain only Unicode letters, numbers,
* or separators, or the following special characters: `+ - = . _ : /`
* * The value can be a maximum 255 characters, and contain only Unicode letters, numbers, or
* separators, or the following special characters: `+ - = . _ : /`
* * Leading and trailing white spaces are trimmed from both the key and value.
* * A maximum of 40 tags is allowed for any resource.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* @param tags A map that contains tag keys and tag values that are attached to a stack or
* layer.
* * The key cannot be empty.
* * The key can be a maximum of 127 characters, and can contain only Unicode letters, numbers,
* or separators, or the following special characters: `+ - = . _ : /`
* * The value can be a maximum 255 characters, and contain only Unicode letters, numbers, or
* separators, or the following special characters: `+ - = . _ : /`
* * Leading and trailing white spaces are trimmed from both the key and value.
* * A maximum of 40 tags is allowed for any resource.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
/** @param useCustomCookbooks Whether the stack uses custom cookbooks. */
public fun useCustomCookbooks(useCustomCookbooks: Boolean) {
cdkBuilder.useCustomCookbooks(useCustomCookbooks)
}
/** @param useCustomCookbooks Whether the stack uses custom cookbooks. */
public fun useCustomCookbooks(useCustomCookbooks: IResolvable) {
cdkBuilder.useCustomCookbooks(useCustomCookbooks)
}
/**
* @param useOpsworksSecurityGroups Whether to associate the AWS OpsWorks Stacks built-in
* security groups with the stack's layers. AWS OpsWorks Stacks provides a standard set of
* built-in security groups, one for each layer, which are associated with layers by default.
* With `UseOpsworksSecurityGroups` you can instead provide your own custom security groups.
* `UseOpsworksSecurityGroups` has the following settings:
* * True - AWS OpsWorks Stacks automatically associates the appropriate built-in security group
* with each layer (default setting). You can associate additional security groups with a
* layer after you create it, but you cannot delete the built-in security group.
* * False - AWS OpsWorks Stacks does not associate built-in security groups with layers. You
* must create appropriate EC2 security groups and associate a security group with each layer
* that you create. However, you can still manually associate a built-in security group with a
* layer on creation; custom security groups are required only for those layers that need
* custom settings.
*
* For more information, see
* [Create a New Stack](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html)
* .
*/
public fun useOpsworksSecurityGroups(useOpsworksSecurityGroups: Boolean) {
cdkBuilder.useOpsworksSecurityGroups(useOpsworksSecurityGroups)
}
/**
* @param useOpsworksSecurityGroups Whether to associate the AWS OpsWorks Stacks built-in
* security groups with the stack's layers. AWS OpsWorks Stacks provides a standard set of
* built-in security groups, one for each layer, which are associated with layers by default.
* With `UseOpsworksSecurityGroups` you can instead provide your own custom security groups.
* `UseOpsworksSecurityGroups` has the following settings:
* * True - AWS OpsWorks Stacks automatically associates the appropriate built-in security group
* with each layer (default setting). You can associate additional security groups with a
* layer after you create it, but you cannot delete the built-in security group.
* * False - AWS OpsWorks Stacks does not associate built-in security groups with layers. You
* must create appropriate EC2 security groups and associate a security group with each layer
* that you create. However, you can still manually associate a built-in security group with a
* layer on creation; custom security groups are required only for those layers that need
* custom settings.
*
* For more information, see
* [Create a New Stack](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html)
* .
*/
public fun useOpsworksSecurityGroups(useOpsworksSecurityGroups: IResolvable) {
cdkBuilder.useOpsworksSecurityGroups(useOpsworksSecurityGroups)
}
/**
* @param vpcId The ID of the VPC that the stack is to be launched into. The VPC must be in the
* stack's region. All instances are launched into this VPC. You cannot change the ID later.
* * If your account supports EC2-Classic, the default value is `no VPC` .
* * If your account does not support EC2-Classic, the default value is the default VPC for the
* specified region.
*
* If the VPC ID corresponds to a default VPC and you have specified either the
* `DefaultAvailabilityZone` or the `DefaultSubnetId` parameter only, AWS OpsWorks Stacks infers
* the value of the other parameter. If you specify neither parameter, AWS OpsWorks Stacks sets
* these parameters to the first valid Availability Zone for the specified region and the
* corresponding default VPC subnet ID, respectively.
*
* If you specify a nondefault VPC ID, note the following:
* * It must belong to a VPC in your account that is in the specified region.
* * You must specify a value for `DefaultSubnetId` .
*
* For more information about how to use AWS OpsWorks Stacks with a VPC, see
* [Running a Stack in a VPC](https://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html)
* . For more information about default VPC and EC2-Classic, see
* [Supported Platforms](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html)
* .
*/
public fun vpcId(vpcId: String) {
cdkBuilder.vpcId(vpcId)
}
public fun build(): CfnStackProps {
if (_cloneAppIds.isNotEmpty()) cdkBuilder.cloneAppIds(_cloneAppIds)
if (_elasticIps.isNotEmpty()) cdkBuilder.elasticIps(_elasticIps)
if (_rdsDbInstances.isNotEmpty()) cdkBuilder.rdsDbInstances(_rdsDbInstances)
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 4 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 27,144 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/net/kodehawa/lib/imageboards/requests/RequestAction.kt | Doomsdayrs | 188,209,067 | true | {"Kotlin": 49623} | /*
* Copyright 2017 Kodehawa
*
* 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.kodehawa.lib.imageboards.requests
import net.kodehawa.lib.imageboards.entities.exceptions.QueryFailedException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.jetbrains.annotations.NotNull
import java.io.IOException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
/**
* Utility action instance that can execute a request and obtain the result
* by blocking the calling thread or using callbacks.
*
* @param <T> Return type of the request.
* @author Avarel
</T> */
class RequestAction<T> internal constructor(private val call: Call, private val transform: (Response) -> T) {
/**
* Obtain the request result by blocking the calling thread.
*
* @return Return type of the request.
*/
fun blocking(): T {
try {
call.execute().use { response ->
if (response.code != 200) {
throw QueryFailedException(response.code, call.request().url.toString())
}
return transform(response)
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
/**
* Obtain the result by submitting the task to an executor and
* returning a [promise][CompletionStage].
*
* @return Executor promise.
*/
fun submit(): CompletionStage<T> {
val future = CompletableFuture<T>()
async(
{ t: T -> future.complete(t) },
{ throwable: Throwable? -> future.completeExceptionally(throwable) }
)
return future
}
/**
* Obtain the result by submitting the task to an executor
* and forwarding the result to a success consumer.
* <br></br>
* However, if an exception occurs then the exception will forward to the
* failure consumer if set.
*
* @param failureConsumer Consumer of the exception (if it occurs).
* @param successConsumer Consumer of the response.
*/
@JvmOverloads
fun async(
@NotNull
successConsumer: (T) -> Unit, failureConsumer: ((Throwable?) -> Unit)? = null) {
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
call.cancel()
failureConsumer?.let { it(e) }
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
try {
if (response.code != 200) {
throw QueryFailedException(
response.code,
[email protected]().url.toString()
)
}
successConsumer(transform(response))
} catch (e: Throwable) {
failureConsumer?.let { it(e) }
} finally {
response.close()
}
}
})
}
} | 0 | Kotlin | 0 | 0 | aa9d0243de8d50309c7ce1e960a46083be066637 | 3,096 | imageboard-api | Apache License 2.0 |
rest/src/main/java/weather/rest/model/Wind.kt | weupz | 154,643,741 | false | null | package weather.rest.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Wind(
@Json(name = "speed")
val speed: Float,
@Json(name = "deg")
val deg: Float?
)
| 3 | Kotlin | 1 | 0 | 560272ef568c6f83d3b377a67b8c7ef4ee203673 | 242 | weather | MIT License |
bezier/src/main/java/io/channel/bezier/icon/Thread.kt | channel-io | 736,533,981 | false | {"Kotlin": 2421787, "Python": 12500} | @file:Suppress("ObjectPropertyName", "UnusedReceiverParameter")
// Auto-generated by script/generate_compose_bezier_icon.py
package io.channel.bezier.icon
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.channel.bezier.BezierIcon
import io.channel.bezier.BezierIcons
val BezierIcons.Thread: BezierIcon
get() = object : BezierIcon {
override val imageVector: ImageVector
get() = _thread ?: ImageVector.Builder(
name = "Thread",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f,
).apply {
path(
fill = SolidColor(Color(0xFF313234)),
strokeLineWidth = 1f,
) {
moveTo(16.79f, 11.27f)
arcTo(6.0f, 6.0f, 295.72382326239665f, isMoreThanHalf = false, isPositiveArc = false, 16.526999999999997f, 11.151f)
curveTo(16.372999999999998f, 8.306f, 14.818999999999997f, 6.678f, 12.207999999999998f, 6.661f)
lineTo(12.172999999999998f, 6.661f)
curveTo(10.610999999999999f, 6.661f, 9.312999999999999f, 7.327999999999999f, 8.514999999999999f, 8.541f)
lineTo(9.95f, 9.525f)
curveTo(10.546999999999999f, 8.620000000000001f, 11.482999999999999f, 8.426f, 12.174f, 8.426f)
lineTo(12.197999999999999f, 8.426f)
curveTo(13.057999999999998f, 8.431000000000001f, 13.704999999999998f, 8.681000000000001f, 14.124999999999998f, 9.169f)
quadTo(14.583999999999998f, 9.703000000000001f, 14.734999999999998f, 10.632000000000001f)
quadTo(13.591999999999997f, 10.437000000000001f, 12.268999999999998f, 10.514000000000001f)
curveTo(9.786999999999999f, 10.656f, 8.192999999999998f, 12.104000000000001f, 8.298999999999998f, 14.114f)
curveTo(8.352999999999998f, 15.134f, 8.860999999999997f, 16.012f, 9.729999999999997f, 16.585f)
curveTo(10.464999999999996f, 17.07f, 11.409999999999997f, 17.307000000000002f, 12.392999999999997f, 17.253f)
curveTo(13.690999999999997f, 17.183f, 14.707999999999997f, 16.686f, 15.418999999999997f, 15.781f)
curveTo(15.958999999999996f, 15.094000000000001f, 16.298999999999996f, 14.203000000000001f, 16.449999999999996f, 13.081f)
curveTo(17.068999999999996f, 13.453f, 17.526999999999994f, 13.945f, 17.779999999999994f, 14.535f)
curveTo(18.209999999999994f, 15.539f, 18.234999999999992f, 17.189f, 16.889999999999993f, 18.533f)
curveTo(15.709999999999994f, 19.711000000000002f, 14.292999999999994f, 20.221f, 12.150999999999993f, 20.236f)
curveTo(9.774999999999993f, 20.219f, 7.977999999999993f, 19.457f, 6.808999999999993f, 17.972f)
curveTo(5.715999999999993f, 16.582f, 5.149999999999993f, 14.572000000000001f, 5.128999999999993f, 12.001000000000001f)
curveTo(5.149999999999993f, 9.431000000000001f, 5.715999999999993f, 7.421000000000001f, 6.808999999999993f, 6.0310000000000015f)
curveTo(7.978999999999993f, 4.545000000000002f, 9.774999999999993f, 3.7830000000000013f, 12.150999999999993f, 3.7660000000000013f)
curveTo(14.543999999999993f, 3.7830000000000013f, 16.372999999999994f, 4.549000000000001f, 17.584999999999994f, 6.042000000000002f)
curveTo(18.179999999999993f, 6.774000000000002f, 18.627999999999993f, 7.694000000000002f, 18.923999999999992f, 8.767000000000001f)
lineTo(20.60599999999999f, 8.317000000000002f)
curveTo(20.24799999999999f, 6.997000000000002f, 19.68399999999999f, 5.858000000000002f, 18.91599999999999f, 4.915000000000002f)
curveTo(17.364f, 3.0f, 15.089f, 2.02f, 12.158f, 2.0f)
lineTo(12.147f, 2.0f)
curveTo(9.22f, 2.02f, 6.972f, 3.004f, 5.46f, 4.925f)
curveTo(4.117f, 6.635f, 3.423f, 9.012f, 3.4f, 11.993f)
lineTo(3.4f, 12.007f)
curveTo(3.423f, 14.989f, 4.117f, 17.367f, 5.461f, 19.075f)
curveTo(6.971f, 20.994999999999997f, 9.221f, 21.979f, 12.146f, 22.0f)
lineTo(12.157f, 22.0f)
curveTo(14.757f, 21.982f, 16.59f, 21.301f, 18.1f, 19.793f)
curveTo(20.075000000000003f, 17.819f, 20.016000000000002f, 15.346f, 19.365000000000002f, 13.826999999999998f)
curveTo(18.898000000000003f, 12.738999999999997f, 18.007f, 11.853999999999997f, 16.790000000000003f, 11.269999999999998f)
moveTo(12.300000000000002f, 15.489999999999998f)
curveTo(11.212000000000003f, 15.551999999999998f, 10.082000000000003f, 15.062999999999999f, 10.027000000000003f, 14.017999999999999f)
curveTo(9.985000000000003f, 13.242999999999999f, 10.579000000000002f, 12.377999999999998f, 12.367000000000003f, 12.274f)
quadTo(12.674000000000003f, 12.257f, 12.970000000000002f, 12.255999999999998f)
curveTo(13.620000000000003f, 12.255999999999998f, 14.227000000000002f, 12.319999999999999f, 14.780000000000003f, 12.439999999999998f)
curveTo(14.573000000000002f, 15.012999999999998f, 13.365000000000002f, 15.429999999999998f, 12.300000000000002f, 15.488999999999997f)
close()
}
}.build().also {
_thread = it
}
}
private var _thread: ImageVector? = null
@Preview(showBackground = true)
@Composable
private fun ThreadIconPreview() {
Icon(
modifier = Modifier.size(128.dp),
imageVector = BezierIcons.Thread.imageVector,
contentDescription = null,
)
}
| 7 | Kotlin | 3 | 6 | 39cd58b0dd4a1543d54f0c1ce7c605f33ce135c6 | 6,431 | bezier-compose | MIT License |
problems/2021adventofcode01b/submissions/accepted/StefanDelegatedProperty.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/** Provides an [ArrayDeque] that is capped to a maximum size while reading. */
class CapacityConstrainedDeque<T>(private val maxSize: Int) : ReadOnlyProperty<Nothing?, ArrayDeque<T>> {
private var deque: ArrayDeque<T> = ArrayDeque(maxSize)
override fun getValue(thisRef: Nothing?, property: KProperty<*>): ArrayDeque<T> {
while (deque.size > maxSize) {
deque.removeFirst()
}
return deque
}
}
fun main() {
val s = Scanner(System.`in`)
val compareDistance = 1
val history: ArrayDeque<Int> by CapacityConstrainedDeque(compareDistance + 1)
var increases = 0
while (s.hasNext()) {
history.add(s.nextInt())
if (history.size == compareDistance + 1 && history.last() > history.first()) {
increases++
}
}
println(increases)
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 909 | competitive-programming | MIT License |
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/repository/behandling/introduksjonsprogrammet/IntroVilkårDbJson.kt | navikt | 487,246,438 | false | {"Kotlin": 979138, "Shell": 1318, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.vedtak.repository.behandling.introduksjonsprogrammet
import no.nav.tiltakspenger.libs.periodisering.Periode
import no.nav.tiltakspenger.saksbehandling.domene.vilkår.introduksjonsprogrammet.IntroSaksopplysning
import no.nav.tiltakspenger.saksbehandling.domene.vilkår.introduksjonsprogrammet.IntroVilkår
import no.nav.tiltakspenger.vedtak.repository.behandling.felles.PeriodisertUtfallDbJson
import no.nav.tiltakspenger.vedtak.repository.behandling.felles.toDbJson
import no.nav.tiltakspenger.vedtak.repository.behandling.felles.toDomain
/**
* Har ansvar for å serialisere/deserialisere IntroVilkår til og fra json for lagring i database.
*/
internal data class IntroVilkårDbJson(
val søknadSaksopplysning: IntroSaksopplysningDbJson,
val saksbehandlerSaksopplysning: IntroSaksopplysningDbJson?,
val avklartSaksopplysning: IntroSaksopplysningDbJson,
val utfallsperioder: List<PeriodisertUtfallDbJson>,
) {
fun toDomain(vurderingsperiode: Periode): IntroVilkår =
IntroVilkår.fromDb(
vurderingsperiode = vurderingsperiode,
søknadSaksopplysning = søknadSaksopplysning.toDomain() as IntroSaksopplysning.Søknad,
saksbehandlerSaksopplysning = saksbehandlerSaksopplysning?.toDomain() as IntroSaksopplysning.Saksbehandler?,
avklartSaksopplysning = avklartSaksopplysning.toDomain(),
utfall = utfallsperioder.toDomain(),
)
}
internal fun IntroVilkår.toDbJson(): IntroVilkårDbJson =
IntroVilkårDbJson(
søknadSaksopplysning = søknadSaksopplysning.toDbJson(),
saksbehandlerSaksopplysning = saksbehandlerSaksopplysning?.toDbJson(),
avklartSaksopplysning = avklartSaksopplysning.toDbJson(),
utfallsperioder = utfall.toDbJson(),
)
| 3 | Kotlin | 0 | 1 | c23890a313eac464b2eae8d6e6f143b47a4b693e | 1,782 | tiltakspenger-vedtak | MIT License |
app/src/main/java/com/circle/w3s/sample/wallet/pwcustom/MyViewSetterProvider.kt | circlefin | 660,783,570 | false | null | package com.circle.w3s.sample.wallet.pwcustom
// Copyright (c) 2023, Circle Technologies, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import android.content.Context
import circle.programmablewallet.sdk.presentation.IImageViewSetter
import circle.programmablewallet.sdk.presentation.IToolbarSetter
import circle.programmablewallet.sdk.presentation.RemoteImageSetter
import circle.programmablewallet.sdk.presentation.RemoteToolbarImageSetter
import circle.programmablewallet.sdk.presentation.Resource
import circle.programmablewallet.sdk.presentation.Resource.ToolbarIcon
import circle.programmablewallet.sdk.presentation.ViewSetterProvider
import com.circle.w3s.sample.wallet.R
class MyViewSetterProvider(context: Context) : ViewSetterProvider() {
var context: Context = context
override fun getToolbarImageSetter(type: ToolbarIcon): IToolbarSetter? {
when (type) {
ToolbarIcon.back -> return RemoteToolbarImageSetter(
R.drawable.ic_back,
"https://path/ic_back"
)
ToolbarIcon.close -> return RemoteToolbarImageSetter(
R.drawable.ic_close,
"https://path/ic_close"
)
else -> {}
}
return super.getToolbarImageSetter(type)
}
override fun getImageSetter(type: Resource.Icon): IImageViewSetter? {
when (type) {
Resource.Icon.securityIntroMain -> return RemoteImageSetter(
R.drawable.ic_intro_main_icon,
"https://path/ic_intro_main_icon"
)
Resource.Icon.selectCheckMark -> return RemoteImageSetter(
R.drawable.ic_checkmark,
"https://path/ic_checkmark"
)
Resource.Icon.dropdownArrow -> return RemoteImageSetter(
R.drawable.ic_dropdown_arrow,
"https://path/ic_dropdown_arrow"
)
Resource.Icon.errorInfo -> return RemoteImageSetter(
R.drawable.ic_error_info,
"https://path/ic_error_info"
)
Resource.Icon.securityConfirmMain -> return RemoteImageSetter(
R.drawable.ic_confirm_main_icon,
"https://path/ic_confirm_main_icon"
)
else -> {}
}
return super.getImageSetter(type)
}
} | 1 | null | 18 | 7 | bfd3b27bd0176bbb94eeb09aa11f153dadbc8575 | 2,898 | w3s-android-sample-app-wallets | Apache License 2.0 |
src/main/kotlin/no/nav/familie/oppdrag/rest/AvstemmingController.kt | navikt | 204,882,382 | false | null | package no.nav.familie.oppdrag.rest
import no.nav.familie.kontrakter.felles.Ressurs
import no.nav.familie.kontrakter.felles.oppdrag.GrensesnittavstemmingRequest
import no.nav.familie.kontrakter.felles.oppdrag.KonsistensavstemmingRequestV2
import no.nav.familie.kontrakter.felles.oppdrag.KonsistensavstemmingUtbetalingsoppdrag
import no.nav.familie.oppdrag.common.RessursUtils.illegalState
import no.nav.familie.oppdrag.common.RessursUtils.ok
import no.nav.familie.oppdrag.service.GrensesnittavstemmingService
import no.nav.familie.oppdrag.service.KonsistensavstemmingService
import no.nav.security.token.support.core.api.ProtectedWithClaims
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api")
@ProtectedWithClaims(issuer = "azuread")
@Validated
class AvstemmingController(@Autowired val grensesnittavstemmingService: GrensesnittavstemmingService,
@Autowired val konsistensavstemmingService: KonsistensavstemmingService) {
@PostMapping(path = ["/grensesnittavstemming"])
fun grensesnittavstemming(@RequestBody request: GrensesnittavstemmingRequest): ResponseEntity<Ressurs<String>> {
LOG.info("Grensesnittavstemming: Kjører for ${request.fagsystem}-oppdrag fra ${request.fra} til ${request.til}")
return Result.runCatching { grensesnittavstemmingService.utførGrensesnittavstemming(request) }
.fold(onFailure = { illegalState("Grensesnittavstemming feilet", it) },
onSuccess = { ok("Grensesnittavstemming sendt ok") })
}
@PostMapping(path = ["/v2/konsistensavstemming"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun konsistensavstemming(@RequestBody request: KonsistensavstemmingRequestV2): ResponseEntity<Ressurs<String>> {
LOG.info("Konsistensavstemming: Kjører for ${request.fagsystem}-oppdrag for ${request.avstemmingstidspunkt} " +
"med ${request.perioderForBehandlinger.sumOf { it.perioder.size }} antall periodeIder")
return Result.runCatching {
konsistensavstemmingService.utførKonsistensavstemming(request)
}.fold(onFailure = { illegalState("Konsistensavstemming feilet", it) },
onSuccess = { ok("Konsistensavstemming sendt ok") })
}
@PostMapping(path = ["/konsistensavstemming"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun konsistensavstemming(@RequestBody request: KonsistensavstemmingUtbetalingsoppdrag): ResponseEntity<Ressurs<String>> {
LOG.info("Konsistensavstemming: Kjører for ${request.fagsystem}-oppdrag for ${request.avstemmingstidspunkt} " +
"med ${request.utbetalingsoppdrag.size} antall oppdrag")
return Result.runCatching {
konsistensavstemmingService.utførKonsistensavstemming(request)
}.fold(onFailure = { illegalState("Konsistensavstemming feilet", it) },
onSuccess = { ok("Konsistensavstemming sendt ok") })
}
companion object {
val LOG: Logger = LoggerFactory.getLogger(AvstemmingController::class.java)
}
} | 4 | Kotlin | 0 | 0 | bf73cf599e09da8f052338a034dc1b53f7edbe7e | 3,530 | familie-oppdrag | MIT License |
app/src/main/java/com/shadowshiftstudio/jobcentre/app/employer/view/main_screens/Vacancies.kt | DarlingInSteam | 688,039,830 | false | {"Kotlin": 110274} | package com.shadowshiftstudio.jobcentre.app.employer.view.main_screens
import androidx.compose.runtime.Composable
@Composable
fun Vacancies() {
} | 16 | Kotlin | 0 | 0 | 5fecaf2864b701d0caf79f94d5b5f4e803c71c70 | 148 | job-centre-frontend | Apache License 2.0 |
app/src/main/kotlin/dev/cherryd/unibot/Main.kt | Tema-man | 744,223,241 | false | {"Kotlin": 45054, "Dockerfile": 605} | package dev.cherryd.unibot
import dev.cherryd.unibot.di.RelaysModule
import dev.cherryd.unibot.di.RouterModule
import io.github.oshai.kotlinlogging.KotlinLogging
fun main(args: Array<String>) {
val logger = KotlinLogging.logger { }
logger.info { "Starting UniBot Application" }
val unibot = Unibot(
relays = RelaysModule.provideRelays(),
router = RouterModule.provideRouter()
)
unibot.start()
while (true) {
val input = readln()
if (input.equals("q", ignoreCase = true)) {
logger.info { "Quiting the app" }
unibot.stop()
break
}
}
}
| 0 | Kotlin | 0 | 0 | 7870f284ce2993f4da9590e4d84211e623e1878e | 644 | unibot | MIT License |
src/integrationTest/kotlin/io/github/endzeitbegins/nifi/flowovertcp/nifi/gateways/NiFiApiGateway.kt | EndzeitBegins | 562,531,219 | false | {"Kotlin": 129527} | package io.github.endzeitbegins.nifi.flowovertcp.nifi.gateways
import io.github.endzeitbegins.nifi.flowovertcp.nifi.flow.models.*
interface NiFiApiGateway {
fun createProcessGroup(
parentProcessGroupId: String,
name: String,
position: Position = defaultPosition,
): ProcessGroup
fun startProcessGroup(id: String)
fun stopProcessGroup(id: String)
fun createProcessor(
parentProcessGroupId: String,
type: String,
name: String,
properties: Map<String, String>,
position: Position = defaultPosition,
autoTerminatedRelationships: Set<String> = emptySet(),
): Processor
fun startProcessor(id: String): Unit
fun stopProcessor(id: String): Unit
fun createConnection(
parentProcessGroupId: String,
source: ConnectionSource,
destination: ConnectionDestination,
): Connection
fun updateConnectionBackPressure(
id: String,
backPressureDataSizeThreshold: String? = null,
backPressureObjectThreshold: String? = null,
): Connection
}
| 2 | Kotlin | 1 | 2 | eb86d568839530dac691a1dc336748a803974a18 | 1,098 | nifi-flow-over-tcp | Apache License 2.0 |
app/src/main/java/com/zoosumzoosum/zoosumx2/SettingActivity.kt | ZOOSUMX2 | 330,588,016 | false | null | package com.zoosumzoosum.zoosumx2
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.Toast
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.zoosumzoosum.zoosumx2.dialog.RevokeDialog
class SettingActivity : AppCompatActivity() {
//var auth: FirebaseAuth? = null
private lateinit var auth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
var fbFirestore: FirebaseFirestore? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setting)
fbFirestore = FirebaseFirestore.getInstance()
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
val button = findViewById<ImageButton>(R.id.imagebutton_back_setting)
button.setOnClickListener {
// back button 클릭 시 현재 activity 종료하고 이전 화면(마이페이지)으로 돌아감
finish()
}
//initializing firebase authentication object
auth = FirebaseAuth.getInstance()
// 로그아웃
val logout = findViewById<LinearLayout>(R.id.linearlayout_logout_setting)
logout.setOnClickListener {
// firebase 로그아웃
auth.signOut()
// Google 로그아웃 -> 재로그인 시에 예전에 로그인 이력이 있는 Google 계정으로 자동 로그인되는 것을 방지
googleSignInClient.signOut().addOnCompleteListener(this) {
}
Toast.makeText(this, "로그아웃 되었습니다", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, LoginActivity::class.java))
//finish()
}
// 회원탈퇴
val withdrawal = findViewById<LinearLayout>(R.id.linearlayout_withdrawal_setting)
withdrawal.setOnClickListener {
// 회원 탈퇴 다이얼로그
val dlg = RevokeDialog(this)
dlg.start()
}
// 문의하기
val ask = findViewById<LinearLayout>(R.id.linearlayout_ask_setting)
ask.setOnClickListener {
val email = Intent(Intent.ACTION_SEND)
email.type = "plain/text"
val address = arrayOf("<EMAIL>")
email.putExtra(Intent.EXTRA_EMAIL, address)
email.putExtra(Intent.EXTRA_SUBJECT, "주섬주섬 문의사항")
email.putExtra(Intent.EXTRA_TEXT, "문의사항을 자세하게 입력해주세요\n\n")
startActivity(email)
}
// 개발자 정보
val about = findViewById<LinearLayout>(R.id.linearlayout_about_dev_setting)
about.setOnClickListener {
val url = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://www.notion.so/zoosum_zoosum-cea1eb0ac124472596699860543562ea")
)
startActivity(url)
}
// 개인정보 처리방침
val policy = findViewById<LinearLayout>(R.id.linearlayout_policy_setting)
policy.setOnClickListener {
val url = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://www.notion.so/3ad045e053a44d43b28b08880820bbe1")
)
startActivity(url)
}
// 서비스 이용약관
val terms = findViewById<LinearLayout>(R.id.linearlayout_terms_setting)
terms.setOnClickListener {
val url = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://www.notion.so/2b9fb2ee9c1445de83447ebd5c4737d9")
)
startActivity(url)
}
}
}
| 0 | Kotlin | 0 | 2 | 1397f49669513fb2778fbdc09d30841f4edb073b | 3,951 | ZOOSUMX2_Android | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/VehicleCarParking.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.VehicleCarParking: ImageVector
get() {
if (_vehicleCarParking != null) {
return _vehicleCarParking!!
}
_vehicleCarParking = fluentIcon(name = "Regular.VehicleCarParking") {
fluentPath {
moveTo(17.25f, 2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
lineTo(22.0f, 1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(5.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(14.25f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
lineTo(19.5f, 8.0f)
horizontalLineToRelative(-1.25f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
lineTo(17.25f, 2.0f)
close()
moveTo(15.8f, 3.0f)
lineToRelative(0.45f, 0.03f)
verticalLineToRelative(1.53f)
curveToRelative(-0.14f, -0.04f, -0.3f, -0.06f, -0.45f, -0.06f)
lineTo(8.2f, 4.5f)
curveToRelative(-0.8f, 0.0f, -1.5f, 0.55f, -1.7f, 1.33f)
lineTo(5.71f, 9.0f)
lineTo(18.5f, 9.0f)
verticalLineToRelative(1.5f)
lineTo(5.25f, 10.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, 0.75f)
lineTo(4.5f, 17.0f)
horizontalLineToRelative(14.0f)
verticalLineToRelative(1.5f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(1.25f)
curveToRelative(0.0f, 0.13f, 0.11f, 0.25f, 0.25f, 0.25f)
horizontalLineToRelative(0.75f)
verticalLineToRelative(1.5f)
horizontalLineToRelative(-0.75f)
curveToRelative(-0.97f, 0.0f, -1.75f, -0.79f, -1.75f, -1.75f)
lineTo(16.0f, 18.5f)
lineTo(8.0f, 18.5f)
verticalLineToRelative(1.25f)
curveToRelative(0.0f, 0.96f, -0.78f, 1.75f, -1.75f, 1.75f)
horizontalLineToRelative(-1.5f)
curveTo(3.78f, 21.5f, 3.0f, 20.7f, 3.0f, 19.75f)
verticalLineToRelative(-8.5f)
curveToRelative(0.0f, -0.81f, 0.43f, -1.53f, 1.08f, -1.92f)
lineToRelative(0.2f, -0.83f)
horizontalLineToRelative(-0.53f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.74f, -0.65f)
lineTo(3.0f, 7.75f)
curveToRelative(0.0f, -0.38f, 0.28f, -0.7f, 0.65f, -0.74f)
lineToRelative(0.1f, -0.01f)
horizontalLineToRelative(0.91f)
lineToRelative(0.39f, -1.54f)
arcTo(3.25f, 3.25f, 0.0f, false, true, 8.2f, 3.0f)
horizontalLineToRelative(7.6f)
close()
moveTo(6.5f, 18.5f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(1.25f)
curveToRelative(0.0f, 0.13f, 0.11f, 0.25f, 0.25f, 0.25f)
horizontalLineToRelative(1.5f)
curveToRelative(0.14f, 0.0f, 0.25f, -0.12f, 0.25f, -0.25f)
lineTo(6.5f, 18.5f)
close()
moveTo(10.25f, 14.0f)
horizontalLineToRelative(3.5f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f)
horizontalLineToRelative(-3.6f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f)
horizontalLineToRelative(0.1f)
close()
moveTo(17.0f, 12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 0.0f, 2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
close()
moveTo(7.0f, 12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, 0.0f, 2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
close()
}
}
return _vehicleCarParking!!
}
private var _vehicleCarParking: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 4,544 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/example/bloder/rxmvp/home/representers/fragments/FoodFragmentRepresenter.kt | bloderxd | 91,920,056 | false | null | package com.example.bloder.rxmvp.home.representers.fragments
import com.example.bloder.rxmvp.data.Food
import com.example.bloder.rxmvp.rx.Cloud
/**
* Created by bloder on 23/05/17.
*/
sealed class FoodFragmentRepresenter : Cloud.Representer {
data class FoodFetched(var foods: List<Food> = listOf()) : FoodFragmentRepresenter()
} | 0 | Kotlin | 1 | 9 | b1faa68c491058ffc358715ca7381517bee92b50 | 338 | kloud | MIT License |
app/src/main/java/com/goldenraven/padawanwallet/theme/Fonts.kt | thunderbiscuit | 308,999,831 | false | null | package com.goldenraven.padawanwallet.theme
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import com.goldenraven.padawanwallet.R
val ShareTechMono = FontFamily(
Font(R.font.share_tech_mono, FontWeight.Normal),
)
val SofiaPro: FontFamily = FontFamily(
Font(R.font.sofia_pro_regular, FontWeight.Normal),
Font(R.font.sofia_pro_regular_italic, FontWeight.Normal, FontStyle.Italic),
Font(R.font.sofia_pro_light, FontWeight.Light),
Font(R.font.sofia_pro_light_italic, FontWeight.Light, FontStyle.Italic)
)
| 39 | Kotlin | 14 | 47 | 87a9150f1e1a7eadcbdac3f585355b36e98f177b | 662 | padawan-wallet | Apache License 2.0 |
src/Day02.kt | strindberg | 572,685,170 | false | {"Kotlin": 15804} | import Result.DRAW
import Result.LOSS
import Result.WIN
sealed interface Move {
val points: Int
fun beats(other: Move): Result
fun askedFor(result: Result): Move
}
enum class Result { WIN, DRAW, LOSS }
object Rock : Move {
override val points = 1
override fun beats(other: Move) =
when (other) {
is Scissor -> WIN
is Rock -> DRAW
else -> LOSS
}
override fun askedFor(result: Result) =
when (result) {
WIN -> Paper
DRAW -> Rock
LOSS -> Scissor
}
}
object Paper : Move {
override val points = 2
override fun beats(other: Move) =
when (other) {
is Rock -> WIN
is Paper -> DRAW
else -> LOSS
}
override fun askedFor(result: Result) =
when (result) {
WIN -> Scissor
DRAW -> Paper
LOSS -> Rock
}
}
object Scissor : Move {
override val points = 3
override fun beats(other: Move) =
when (other) {
is Paper -> WIN
is Scissor -> DRAW
else -> LOSS
}
override fun askedFor(result: Result) =
when (result) {
WIN -> Rock
DRAW -> Scissor
LOSS -> Paper
}
}
fun getFirstMove(first: Char) =
if (first == 'A') Rock else if (first == 'B') Paper else if (first == 'C') Scissor else throw RuntimeException()
fun getSecondMove(b: Char) =
if (b == 'X') Rock else if (b == 'Y') Paper else if (b == 'Z') Scissor else throw RuntimeException()
fun getSecondResult(second: Char) =
if (second == 'X') LOSS else if (second == 'Y') DRAW else if (second == 'Z') WIN else throw RuntimeException()
fun main() {
fun part1(input: List<String>): Int =
input.sumOf { line ->
val first = getFirstMove(line[0])
val second = getSecondMove(line[2])
when (second.beats(first)) {
WIN -> second.points + 6
DRAW -> second.points + 3
LOSS -> second.points
}
}
fun part2(input: List<String>): Int =
input.sumOf { line ->
val first = getFirstMove(line[0])
val result = getSecondResult(line[2])
val second = first.askedFor(result)
when (result) {
WIN -> second.points + 6
DRAW -> second.points + 3
LOSS -> second.points
}
}
val input = readInput("Day02")
val part1 = part1(input)
println(part1)
check(part1 == 8933)
val part2 = part2(input)
println(part2)
check(part2 == 11998)
}
| 0 | Kotlin | 0 | 0 | c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8 | 2,899 | aoc-2022 | Apache License 2.0 |
app/src/main/java/com/dramtar/billscollecting/presenter/utils/composedatepicker/CalendarHeader.kt | MaxBuriak | 544,515,289 | false | {"Kotlin": 131241} | package com.dramtar.billscollecting.presenter.utils.composedatepicker
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun CalendarHeader(
selectedMonth: MonthData,
selectedYear: Int,
showMonths: Boolean,
setShowMonths: (Boolean) -> Unit,
title: String,
showOnlyMonth: Boolean,
showOnlyYear: Boolean,
themeColor: Color,
monthViewType: MonthViewType?
) {
val monthAsNumber = String.format("%02d", selectedMonth.index.plus(1))
val monthText =
if (monthViewType == MonthViewType.ONLY_MONTH) selectedMonth.name.uppercase() else monthAsNumber
Column(
modifier = Modifier
.fillMaxWidth()
.background(themeColor),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = title,
fontSize = 16.sp,
modifier = Modifier.padding(top = 16.dp),
color = Color.White
)
Row {
if (!showOnlyYear) {
Text(
text = monthText,
fontSize = 35.sp,
modifier = Modifier
.padding(
bottom = 20.dp,
start = if (showOnlyMonth) 0.dp else 30.dp,
end = if (showOnlyMonth) 0.dp else 10.dp
)
.clickable { setShowMonths(true) },
color = if (showMonths) Color.White else Color.LightGray
)
}
if (!showOnlyMonth && !showOnlyYear) {
Text(text = "/", fontSize = 35.sp, color = Color.White)
}
if (!showOnlyMonth) {
Text(
text = selectedYear.toString(),
fontSize = 35.sp,
modifier = Modifier
.padding(
bottom = 20.dp,
start = if (showOnlyYear) 0.dp else 10.dp,
end = if (showOnlyYear) 0.dp else 30.dp
)
.clickable { setShowMonths(false) },
color = if (showMonths) Color.LightGray else Color.White
)
}
}
}
} | 0 | Kotlin | 0 | 1 | 6f5f94dec8455def198626ffb1e279d6c71bc50b | 2,802 | Bills-Collecting | Apache License 2.0 |
app/src/main/java/ir/mahdighanbarpour/khwarazmiapp/MyApp.kt | MahdiGhanbarpour | 735,064,418 | false | {"Kotlin": 708590} | package ir.mahdighanbarpour.khwarazmiapp
import android.app.Application
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import ir.mahdighanbarpour.khwarazmiapp.di.myModules
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
// Application class
class MyApp : Application() {
private lateinit var analytics: FirebaseAnalytics
override fun onCreate() {
super.onCreate()
analytics = Firebase.analytics
// Koin
val modules = myModules
startKoin {
androidContext(this@MyApp)
modules(modules)
}
}
} | 0 | Kotlin | 0 | 0 | 6fd6104330e500b9afee6f7f09fa1f80890e3c63 | 716 | Emtehanak | MIT License |
ERMSManager/src/main/java/com/kust/ermsmanager/data/repositories/ChatRepositoryImpl.kt | sabghat90 | 591,653,827 | false | {"Kotlin": 583902, "HTML": 87217} | package com.kust.ermsmanager.data.repositories
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.kust.ermslibrary.models.Message
import com.kust.ermslibrary.utils.FirebaseRealtimeDatabaseConstants
import com.kust.ermslibrary.utils.UiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ChatRepositoryImpl(
private val database: FirebaseDatabase,
private val auth: FirebaseAuth
) : ChatRepository {
override suspend fun sendMessage(
message: Message,
receiverId: String,
result: (UiState<String>) -> Unit
) {
try {
val senderId = auth.currentUser?.uid ?: return
val senderRoom = receiverId + senderId
val senderReference = database.reference.child(FirebaseRealtimeDatabaseConstants.CHAT).child(senderRoom).child(FirebaseRealtimeDatabaseConstants.CHAT_MESSAGES).push()
val messageId = senderReference.key ?: return
message.id = messageId
senderReference.setValue(message)
.addOnSuccessListener {
val receiverRoom = senderId + receiverId
val receiverReference = database.reference.child(FirebaseRealtimeDatabaseConstants.CHAT).child(receiverRoom).child(FirebaseRealtimeDatabaseConstants.CHAT_MESSAGES).push()
receiverReference.setValue(message)
.addOnSuccessListener {
result(UiState.Success(messageId))
}
.addOnFailureListener {
result(UiState.Error(it.localizedMessage ?: "Unknown error"))
}
}
} catch (e: Exception) {
result(UiState.Error(e.localizedMessage ?: "Unknown error"))
}
}
override suspend fun getMessages(receiverId: String, result: (List<Message>) -> Unit): Unit = withContext(Dispatchers.IO) {
try {
val senderId = auth.currentUser?.uid ?: return@withContext
val senderRoom = receiverId + senderId
val receiverRoom = senderId + receiverId
val senderReference = database.reference.child(FirebaseRealtimeDatabaseConstants.CHAT).child(senderRoom).child(FirebaseRealtimeDatabaseConstants.CHAT_MESSAGES)
val receiverReference = database.reference.child(FirebaseRealtimeDatabaseConstants.CHAT).child(receiverRoom).child(FirebaseRealtimeDatabaseConstants.CHAT_MESSAGES)
senderReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val messages = mutableListOf<Message>()
for (data in snapshot.children) {
val message = data.getValue(Message::class.java) ?: continue
messages.add(message)
}
result(messages)
}
override fun onCancelled(error: DatabaseError) {
result(emptyList())
}
})
receiverReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val messages = mutableListOf<Message>()
for (data in snapshot.children) {
val message = data.getValue(Message::class.java) ?: continue
messages.add(message)
}
result(messages)
}
override fun onCancelled(error: DatabaseError) {
result(emptyList())
}
})
} catch (e: Exception) {
result(emptyList())
}
}
} | 1 | Kotlin | 0 | 2 | 56497f553ddcbbe2bdbafb987caa40cb44d552e8 | 4,003 | ERMS | MIT License |
health/health-services-client/src/main/java/androidx/health/services/client/ListenableFutureExtension.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2022 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.health.services.client
import android.os.RemoteException
import androidx.concurrent.futures.await
import com.google.common.util.concurrent.ListenableFuture
import kotlin.jvm.Throws
/**
* Extension function on ListenableFuture performs [ListenableFuture.await] operation and if any
* exception thrown by the asynchronous API, converts [android.os.RemoteException] into
* [HealthServicesException]
*
* @throws HealthServicesException if remote operation fails
*/
@Throws(HealthServicesException::class)
suspend fun <T> ListenableFuture<T>.awaitWithException(): T {
val t: T =
try {
await()
} catch (e: RemoteException) {
if (e.message != null) throw HealthServicesException(e.message!!)
else throw HealthServicesException("An unknown error has occurred")
}
return t
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 1,476 | androidx | Apache License 2.0 |
idea/tests/testData/compiler/loadJava/compiledKotlin/platformTypes/nullableTypeArgument.kt | JetBrains | 278,369,660 | false | null | // TARGET_BACKEND: JVM
// FULL_JDK
// JAVAC_EXPECTED_FILE
// NO_CHECK_SOURCE_VS_BINARY
package test
class C: java.util.ArrayList<String?>()
| 181 | null | 5748 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 142 | intellij-kotlin | Apache License 2.0 |
financial-connections/src/test/java/com/stripe/android/financialconnections/domain/NativeAuthFlowRouterTest.kt | stripe | 6,926,049 | false | null | package com.stripe.android.financialconnections.domain
import com.google.common.truth.Truth.assertThat
import com.stripe.android.financialconnections.ApiKeyFixtures
import com.stripe.android.financialconnections.analytics.FinancialConnectionsAnalyticsTracker
import com.stripe.android.financialconnections.analytics.FinancialConnectionsEvent
import com.stripe.android.financialconnections.debug.DebugConfiguration
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
internal class NativeAuthFlowRouterTest {
private val eventTracker = mock<FinancialConnectionsAnalyticsTracker>()
private val debugConfiguration = mock<DebugConfiguration>()
private val router = NativeAuthFlowRouter(
eventTracker,
debugConfiguration
)
init {
whenever(debugConfiguration.overriddenNative).thenReturn(null)
}
@Test
fun `nativeAuthFlowEnabled - true if experiment is treatment and no kill switch`() {
val syncResponse = syncWithAssignments(
assignments = mapOf(
"connections_mobile_native" to "treatment"
),
features = mapOf()
)
val nativeAuthFlowEnabled = router.nativeAuthFlowEnabled(syncResponse.manifest)
assertThat(nativeAuthFlowEnabled).isTrue()
}
@Test
fun `nativeAuthFlowEnabled - false if experiment is treatment but kill switch is on`() {
val syncResponse = syncWithAssignments(
assignments = mapOf(
"connections_mobile_native" to "treatment"
),
features = mapOf(
"bank_connections_mobile_native_version_killswitch" to true
)
)
val nativeAuthFlowEnabled = router.nativeAuthFlowEnabled(syncResponse.manifest)
assertThat(nativeAuthFlowEnabled).isFalse()
}
@Test
fun `nativeAuthFlowEnabled - false if experiment is control`() {
val syncResponse = syncWithAssignments(
assignments = mapOf(
"connections_mobile_native" to "control"
),
features = mapOf(
"bank_connections_mobile_native_version_killswitch" to false
)
)
val nativeAuthFlowEnabled = router.nativeAuthFlowEnabled(syncResponse.manifest)
assertThat(nativeAuthFlowEnabled).isFalse()
}
@Test
fun `logExposure - logs if experiment present and kill switch is off`() = runTest {
val syncResponse = syncWithAssignments(
assignments = mapOf(
"connections_mobile_native" to "random"
),
features = mapOf(
"bank_connections_mobile_native_version_killswitch" to false
)
)
router.logExposure(syncResponse.manifest)
verify(eventTracker).track(
FinancialConnectionsEvent.Exposure(
experimentName = "connections_mobile_native",
assignmentEventId = "id",
accountHolderId = "token"
)
)
}
@Test
fun `logExposure - does not log if experiment present and kill switch is on`() = runTest {
val syncResponse = syncWithAssignments(
assignments = mapOf(
"connections_mobile_native" to "random"
),
features = mapOf(
"bank_connections_mobile_native_version_killswitch" to true
)
)
router.logExposure(syncResponse.manifest)
verifyNoInteractions(eventTracker)
}
private fun syncWithAssignments(
assignments: Map<String, String>,
features: Map<String, Boolean>
) = ApiKeyFixtures.syncResponse().copy(
manifest = ApiKeyFixtures.sessionManifest().copy(
assignmentEventId = "id",
accountholderToken = "token",
experimentAssignments = assignments,
features = features
)
)
}
| 86 | null | 621 | 1,208 | 2f395065d4655723f82b03665521b88bea7fc742 | 4,067 | stripe-android | MIT License |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/api/variant/impl/PackagingImpl.kt | jomof | 502,039,754 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 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 com.android.build.api.variant.impl
import com.android.build.api.variant.Packaging
import com.android.build.api.variant.ResourcesPackaging
import com.android.build.gradle.internal.services.VariantPropertiesApiServices
open class PackagingImpl(
dslPackagingOptions: com.android.build.gradle.internal.dsl.PackagingOptions,
variantPropertiesApiServices: VariantPropertiesApiServices
) : Packaging {
override val jniLibs =
JniLibsPackagingImpl(dslPackagingOptions, variantPropertiesApiServices)
override val resources =
ResourcesPackagingImpl(dslPackagingOptions, variantPropertiesApiServices)
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 1,256 | CppBuildCacheWorkInProgress | Apache License 2.0 |
app/src/main/java/com/rmoralf/roomcleanarchitectureapp/di/AppModule.kt | rmoralf | 485,126,636 | false | null | package com.rmoralf.roomcleanarchitectureapp.di
import android.content.Context
import androidx.room.Room
import com.rmoralf.roomcleanarchitectureapp.core.utils.Constants.ROOM_DB_NAME
import com.rmoralf.roomcleanarchitectureapp.data.database.WeightDatabase
import com.rmoralf.roomcleanarchitectureapp.data.database.dao.WeightDao
import com.rmoralf.roomcleanarchitectureapp.data.repositories.RoomRepositoryImpl
import com.rmoralf.roomcleanarchitectureapp.domain.repository.RoomRepository
import com.rmoralf.roomcleanarchitectureapp.domain.usecases.ClearWeights
import com.rmoralf.roomcleanarchitectureapp.domain.usecases.GetDailyWeights
import com.rmoralf.roomcleanarchitectureapp.domain.usecases.StoreNewWeight
import com.rmoralf.roomcleanarchitectureapp.domain.usecases.UseCases
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import javax.inject.Singleton
@Module
@ExperimentalCoroutinesApi
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideRoom(@ApplicationContext context: Context) =
Room.databaseBuilder(context, WeightDatabase::class.java, ROOM_DB_NAME).build()
@Singleton
@Provides
fun provideWeightDao(db: WeightDatabase) = db.getWeightDao()
@Provides
fun provideRoomRepository(weightDao: WeightDao): RoomRepository = RoomRepositoryImpl(weightDao)
@Provides
fun provideUseCases(
roomRepository: RoomRepository
) = UseCases(
getDailyWeights = GetDailyWeights(roomRepository),
storeNewWeight = StoreNewWeight(roomRepository),
clearWeights = ClearWeights(roomRepository)
)
} | 0 | Kotlin | 0 | 0 | 4f1f9b5246b5edd7b1e98ecb8a5fdda3808ee165 | 1,794 | RoomCleanArchitectureApp | Apache License 2.0 |
src/main/kotlin/no/nav/faktureringskomponenten/domain/models/Faktura.kt | navikt | 554,076,848 | false | {"Kotlin": 196893, "Shell": 229, "Dockerfile": 199} | package no.nav.faktureringskomponenten.domain.models
import com.fasterxml.jackson.annotation.JsonIgnore
import jakarta.persistence.*
import java.math.BigDecimal
import java.time.LocalDate
@Entity
@Table(name = "faktura")
class Faktura(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@Column(name = "dato_bestilt", nullable = false)
val datoBestilt: LocalDate = LocalDate.now(),
@Column(name = "sist_oppdatert", nullable = false)
var sistOppdatert: LocalDate = LocalDate.now(),
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
var status: FakturaStatus = FakturaStatus.OPPRETTET,
@OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "faktura_id", nullable = false)
val fakturaLinje: List<FakturaLinje> = mutableListOf(),
@ManyToOne
@JoinColumn(name = "fakturaserie_id", nullable = false, insertable = false, updatable = false)
var fakturaserie: Fakturaserie? = null,
@OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "faktura_id")
var eksternFakturaStatus: MutableList<EksternFakturaStatus> = mutableListOf(),
) {
override fun toString(): String {
return "id: $id, datoBestilt: $datoBestilt, status: $status"
}
fun getPeriodeFra(): LocalDate {
return fakturaLinje.minOf { it.periodeFra }
}
fun getPeriodeTil(): LocalDate {
return fakturaLinje.maxOf { it.periodeTil }
}
fun getFakturaserieId(): Long?{
return fakturaserie?.id
}
fun totalbeløp(): BigDecimal {
return fakturaLinje.sumOf(FakturaLinje::belop)
}
fun erAvregningsfaktura() : Boolean {
return fakturaLinje.any { it.referertFakturaVedAvregning != null }
}
}
| 5 | Kotlin | 0 | 0 | f28ff9ae64893411a9a70b747db3db19e28f33a1 | 1,863 | faktureringskomponenten | MIT License |
src/integrationMain/kotlin/com/liftric/apt/ContainerBase.kt | Liftric | 649,623,052 | false | null | package com.liftric.apt
import io.minio.*
import org.testcontainers.containers.GenericContainer
import org.testcontainers.utility.DockerImageName
import io.minio.errors.MinioException
import org.testcontainers.containers.Network
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
/**
* This is an abstract base class upon which all test classes are built.
* This class sets up a simulated AWS S3 environment by starting a Minio container.
* It prepares the environment for each test by creating dedicated buckets.
* This includes initializing test buckets, creating the Minio client, and
* preparing the buckets by ensuring they exist and have the correct policies.
* Additionally, it provides a method to upload objects to these buckets.
*/
abstract class ContainerBase {
companion object {
private val testBuckets =
listOf(
UPLOAD_PACKAGE_TEST_BUCKET,
UPLOAD_PACKAGE_TEST_BUCKET_2,
REMOVE_PACKAGE_TEST_BUCKET,
CLEAN_PACKAGES_TEST_BUCKET
)
val network: Network = Network.newNetwork()
val MINIO_CONTAINER: GenericContainer<*> =
GenericContainer(DockerImageName.parse("quay.io/minio/minio:RELEASE.2023-06-02T23-17-26Z"))
.withPrivilegedMode(true)
.withNetwork(network)
.withNetworkAliases("minio")
.withEnv("MINIO_ROOT_USER", MINIO_ACCESS_KEY)
.withEnv("MINIO_ROOT_PASSWORD", MINIO_SECRET_KEY)
.withCommand("server", "--console-address", ":9090", "/data")
.withExposedPorts(MINIO_PORT, 9090)
.apply { start() }
lateinit var minioClient: MinioClient
init {
try {
minioClient = MinioClient.Builder()
.endpoint("http://localhost:${MINIO_CONTAINER.getMappedPort(MINIO_PORT)}")
.credentials(MINIO_ACCESS_KEY, MINIO_SECRET_KEY)
.build()
testBuckets.forEach {
val found = minioClient.bucketExists(
BucketExistsArgs.builder()
.bucket(it)
.build()
)
if (found) {
minioClient.removeBucket(
RemoveBucketArgs.builder()
.bucket(it)
.build()
)
}
minioClient.makeBucket(
MakeBucketArgs.builder()
.bucket(it)
.region(MINIO_BUCKET_REGION)
.build()
)
minioClient.setBucketPolicy(
SetBucketPolicyArgs.builder()
.bucket(it)
.config(
"""
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::$it/*"
]
}
]
}
""".trimIndent()
)
.build()
)
}
} catch (e: MinioException) {
println("Error occurred: $e")
}
}
fun uploadObjects(bucket: String, objects: Map<String, String>) {
objects.forEach { (key, value) ->
minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucket)
.filename(key)
.`object`(value)
.build()
)
}
}
fun getFileFromBucket(path: String, bucket: String): File {
val stream: InputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucket)
.`object`(path)
.build()
)
return File.createTempFile(path.substringAfterLast("/"), null).apply {
deleteOnExit()
FileOutputStream(this).use { output ->
stream.copyTo(output)
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | bbd083f230bded6bb4395a94d7ddc8b643428fd8 | 5,065 | s3-apt-repository-plugin | MIT License |
src/main/kotlin/grd/kotlin/authapi/dto/AUserDto.kt | gardehal | 708,548,046 | false | {"Kotlin": 54861, "Shell": 612, "HTML": 331} | package grd.kotlin.authapi.dto
import grd.kotlin.authapi.enums.UserRole
import io.swagger.v3.oas.annotations.media.Schema
data class AUserDto(
@Schema(description = "ID")
var id: String? = null,
@Schema(description = "Email")
var email: String? = null,
@Schema(description = "Username to display")
var username: String? = null,
@Schema(description = "A short summary about the user")
var about: String? = null,
@Schema(description = "Users designated role")
var role: UserRole? = null,
@Schema(description = "Datetime until account is permanently closed")
var expirationTime: String? = null,
@Schema(description = "Number of other users this user has recruited")
var usersRecruited: Int? = null,
@Schema(description = "DateTime user last active")
var lastActiveTime: String? = null,
@Schema(description = "Datetime account is banned until")
var lockedUntilTime: String? = null,
@Schema(description = "A map of DateTime username changed and from what username")
var previousUsernames: MutableMap<String, String>? = null,
@Schema(description = "Users profile picture as Base64")
var profilePicture: String? = null,
)
| 0 | Kotlin | 0 | 0 | e4be0bf711bdd8dbd3dad876bd20babd88559aca | 1,215 | kotlin-auth-api | MIT License |
core/data/src/commonMain/kotlin/in/surajsau/jisho/data/GetSentencesForWord.kt | surajsau | 489,927,815 | false | null | package `in`.surajsau.jisho.data
import `in`.surajsau.jisho.data.db.Jisho
import `in`.surajsau.jisho.utils.DispatcherProvider
import `in`.surajsau.jisho.model.Sentence
import `in`.surajsau.jisho.model.SentenceQuery
import `in`.surajsau.jisho.model.SentenceResult
import kotlinx.coroutines.withContext
public class GetSentencesForWord constructor(
private val db: Jisho,
private val dispatcherProvider: DispatcherProvider
) {
public suspend operator fun invoke(query: SentenceQuery, count: Int): List<SentenceResult> = withContext(dispatcherProvider.io) {
val sentences = when (count) {
-1 -> getAllSentencesFor(query = query.query)
else -> getSentencesFor(query = query.query, limit = count)
}
return@withContext sentences.map { (id, jp, en, _) ->
SentenceResult(id = id, japanese = jp, english = en)
}
}
private fun getAllSentencesFor(query: String): List<Sentence> {
return db.sentenceQueries.getAllSentencesWithKeyword(query) { id, jp, en ->
Sentence(id, jp!!.replace("\n", ""), en!!, null)
}.executeAsList()
}
private fun getSentencesFor(query: String, limit: Int): List<Sentence> {
return db.sentenceQueries.getLimitedSentencesWithKeyword(query, limit.toLong()) { id, jp, en ->
Sentence(id, jp!!.replace("\n", ""), en!!, null)
}.executeAsList()
}
} | 0 | Kotlin | 0 | 1 | 83de51c9040d748b06651d8dbeb1a367d98ea362 | 1,415 | Multiplatform-Jisho | Apache License 2.0 |
app/src/main/java/com/tarripoha/android/data/model/User.kt | rajatsangrame | 340,683,468 | false | null | package com.tarripoha.android.data.model
data class User(
val id: String,
val name: String,
val phone: String,
val email: String,
val password: String? = null,
var emailVerified: Boolean? = null,
val city: String? = null,
var dirty: Boolean? = null,
val admin: Boolean = false,
val timestamp: Long,
var fcmToken: String? = null,
var lastSessionTime: Long? = null,
) {
constructor() : this(
id = "", name = "", phone = "", email = "", timestamp = 0L
)
constructor(
id: String,
name: String,
phone: String,
email: String,
timestamp: Long,
) : this(
id = id, name = name, phone = phone, email = email, timestamp = timestamp, dirty = false
)
}
| 0 | Kotlin | 0 | 0 | ad05c8f210b7d2c641b4d14fceba55fb02f0801c | 766 | tarripoha-android | MIT License |
device/src/main/java/com/sedsoftware/yaptalker/device/settings/DefaultHomeScreen.kt | djkovrik | 98,050,611 | false | null | package com.sedsoftware.yaptalker.device.settings
object DefaultHomeScreen {
const val MAIN = "MAIN"
const val FORUMS = "FORUMS"
const val ACTIVE_TOPICS = "ACTIVE_TOPICS"
const val INCUBATOR = "INCUBATOR"
}
| 0 | null | 4 | 9 | 465c34c3dc0dd0488b637073fddf6cd797e78613 | 224 | YapTalker | Apache License 2.0 |
lib/src/main/kotlin/tools.kt | markmckenna | 42,368,179 | false | null | package org.lantopia.kstream
fun Any.unit() = Unit
fun expr(value: Any): Boolean = true
operator fun Boolean.and(action: () -> Unit) = if (this) action() else unit()
infix fun Boolean.or(action: () -> Unit) = if (this) unit() else action()
| 0 | Kotlin | 0 | 0 | e4d7e6645ad99792acb1f00f818cda3cdcc9ab58 | 243 | lib-kotlin | MIT License |
bbfgradle/tmp/results/BACKUP_JVM-Xuse-ir/BACKEND_rzgkhgc_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM -Xuse-ir
//File: tmp/tmp0.kt
val uintSet = mutableSetOf(1u)
.contains{{}!!}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 99 | kotlinWithFuzzer | Apache License 2.0 |
src/test/kotlin/no/nav/fo/veilarbregistrering/registrering/ordinaer/resources/OrdinaerBrukerRegistreringResourceTest.kt | navikt | 131,013,336 | false | null | package no.nav.fo.veilarbregistrering.registrering.ordinaer.resources
import io.getunleash.Unleash
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.verify
import javax.servlet.http.HttpServletRequest
import no.nav.common.auth.context.AuthContextHolder
import no.nav.fo.veilarbregistrering.autorisasjon.TilgangskontrollService
import no.nav.fo.veilarbregistrering.besvarelse.Besvarelse
import no.nav.fo.veilarbregistrering.besvarelse.HelseHinderSvar
import no.nav.fo.veilarbregistrering.bruker.AktorId
import no.nav.fo.veilarbregistrering.bruker.Bruker
import no.nav.fo.veilarbregistrering.bruker.Foedselsnummer
import no.nav.fo.veilarbregistrering.bruker.FoedselsnummerTestdataBuilder
import no.nav.fo.veilarbregistrering.bruker.Gruppe
import no.nav.fo.veilarbregistrering.bruker.Ident
import no.nav.fo.veilarbregistrering.bruker.Identer
import no.nav.fo.veilarbregistrering.bruker.PdlOppslagGateway
import no.nav.fo.veilarbregistrering.bruker.UserService
import no.nav.fo.veilarbregistrering.config.RequestContext
import no.nav.fo.veilarbregistrering.registrering.ordinaer.BrukerRegistreringService
import no.nav.fo.veilarbregistrering.registrering.ordinaer.OrdinaerBrukerRegistreringTestdataBuilder
import no.nav.fo.veilarbregistrering.registrering.veileder.NavVeilederService
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.post
@AutoConfigureMockMvc
@Disabled
@WebMvcTest
@ContextConfiguration(classes = [OrdinaerBrukerRegistreringResourceConfig::class])
class OrdinaerBrukerRegistreringResourceTest(
@Autowired private val mvc: MockMvc,
@Autowired private val ordinaerBrukerRegistreringResource: OrdinaerBrukerRegistreringResource,
@Autowired private val tilgangskontrollService: TilgangskontrollService,
@Autowired private val authContextHolder: AuthContextHolder,
@Autowired private val pdlOppslagGateway: PdlOppslagGateway,
@Autowired private val brukerRegistreringService: BrukerRegistreringService
) {
private lateinit var request: HttpServletRequest
@BeforeEach
fun setup() {
clearAllMocks()
mockkStatic(RequestContext::class)
request = mockk(relaxed = true)
every { RequestContext.servletRequest() } returns request
every { tilgangskontrollService.erVeileder() } returns true
every { authContextHolder.erEksternBruker() } returns false
}
@Test
fun `Fullfoer ordinaer registrering ok`() {
every { request.getParameter("fnr") } returns IDENT.stringValue()
every { pdlOppslagGateway.hentIdenter(any<Foedselsnummer>()) } returns IDENTER
val responseString = mvc.post("/api/fullfoerordinaerregistrering") {
contentType = MediaType.APPLICATION_JSON
content = REGISTRERING_REQUEST
}.andExpect {
status { isOk() }
}.andReturn().response.contentAsString
println(responseString)
}
@Test
fun skalSjekkeTilgangTilBrukerVedRegistreringAvBruker() {
val ordinaerBrukerRegistrering = OrdinaerBrukerRegistreringTestdataBuilder.gyldigBrukerRegistrering(
besvarelse = Besvarelse(helseHinder = HelseHinderSvar.NEI)
)
every { request.getParameter("fnr") } returns IDENT.stringValue()
every { pdlOppslagGateway.hentIdenter(any<Foedselsnummer>()) } returns IDENTER
every {
brukerRegistreringService.registrerBrukerUtenOverforing(
ordinaerBrukerRegistrering,
Bruker(FoedselsnummerTestdataBuilder.aremark(), AktorId("1234")),
null
)
} returns ordinaerBrukerRegistrering
ordinaerBrukerRegistreringResource.registrerBruker(ordinaerBrukerRegistrering)
verify(exactly = 1) { tilgangskontrollService.sjekkSkrivetilgangTilBruker(any(), any()) }
}
companion object {
private val IDENT = Foedselsnummer("10108000398") //Aremark fiktivt fnr.";
private val IDENTER = Identer(
mutableListOf(
Ident(IDENT.stringValue(), false, Gruppe.FOLKEREGISTERIDENT),
Ident("22222222222", false, Gruppe.AKTORID)
)
)
private const val REGISTRERING_REQUEST =
"{\"sisteStilling\":{\"label\":\"Annen stilling\",\"styrk08\":\"-1\",\"konseptId\":-1},\"besvarelse\":{\"sisteStilling\":\"INGEN_SVAR\",\"utdanning\":\"INGEN_UTDANNING\",\"utdanningBestatt\":\"INGEN_SVAR\",\"utdanningGodkjent\":\"INGEN_SVAR\",\"dinSituasjon\":\"MISTET_JOBBEN\",\"helseHinder\":\"NEI\",\"andreForhold\":\"NEI\"},\"teksterForBesvarelse\":[{\"sporsmalId\":\"sisteStilling\",\"sporsmal\":\"Hva er din siste jobb?\",\"svar\":\"Annen stilling\"},{\"sporsmalId\":\"utdanning\",\"sporsmal\":\"Hva er din høyeste fullførte utdanning?\",\"svar\":\"Ingen utdanning\"},{\"sporsmalId\":\"utdanningBestatt\",\"sporsmal\":\"Er utdanningen din bestått?\",\"svar\":\"Ikke aktuelt\"},{\"sporsmalId\":\"utdanningGodkjent\",\"sporsmal\":\"Er utdanningen din godkjent i Norge?\",\"svar\":\"Ikke aktuelt\"},{\"sporsmalId\":\"dinSituasjon\",\"sporsmal\":\"Velg den situasjonen som passer deg best\",\"svar\":\"Har mistet eller kommer til å miste jobben\"},{\"sporsmalId\":\"helseHinder\",\"sporsmal\":\"Har du helseproblemer som hindrer deg i å søke eller være i jobb?\",\"svar\":\"Nei\"},{\"sporsmalId\":\"andreForhold\",\"sporsmal\":\"Har du andre problemer med å søke eller være i jobb?\",\"svar\":\"Nei\"}]}"
}
}
@Configuration
private class OrdinaerBrukerRegistreringResourceConfig {
@Bean
fun ordinaerBrukerRegistreringResource(
tilgangskontrollService: TilgangskontrollService,
userService: UserService,
brukerRegistreringService: BrukerRegistreringService,
navVeilederService: NavVeilederService,
unleashClient: Unleash
) = OrdinaerBrukerRegistreringResource(
tilgangskontrollService,
userService,
brukerRegistreringService,
navVeilederService,
unleashClient
)
@Bean
fun tilgangskontrollService(): TilgangskontrollService = mockk(relaxed = true)
@Bean
fun navVeilederService(tilgangskontrollService: TilgangskontrollService, userService: UserService): NavVeilederService {
return NavVeilederService(tilgangskontrollService, userService)
}
@Bean
fun unleashClient(): Unleash = mockk(relaxed = true)
@Bean
fun pdlOppslagGateway(): PdlOppslagGateway = mockk()
@Bean
fun brukerRegistreringService(): BrukerRegistreringService = mockk(relaxed = true)
@Bean
fun authContextHolder(): AuthContextHolder = mockk()
@Bean
fun userService(pdlOppslagGateway: PdlOppslagGateway, authContextHolder: AuthContextHolder): UserService =
UserService(pdlOppslagGateway, authContextHolder)
}
| 18 | null | 8 | 6 | b608c00bb1a2d1fce4fa7703b24f51e692ad5860 | 7,394 | veilarbregistrering | MIT License |
server/src/main/kotlin/org/reckful/archive/twitter/server/mapper/DateTimeMapper.kt | ReckfulArchive | 632,190,129 | false | null | package org.reckful.archive.twitter.server.dto.mapper
import org.reckful.archive.twitter.server.dto.DateTimeDTO
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@Component
class DateTimeMapper {
fun map(localDate: LocalDate): DateTimeDTO {
return map(localDate.atTime(0, 0, 0))
}
fun map(localDateTime: LocalDateTime): DateTimeDTO {
return DateTimeDTO(
iso = DateTimeFormatter.ISO_DATE_TIME.format(localDateTime),
dayOfMonthFormatted = DAY_OF_MONTH_FORMATTER.format(localDateTime),
monthOfYearFormatted = MONTH_OF_YEAR_FORMATTER.format(localDateTime),
dateFormatted = DATE_FORMATTER.format(localDateTime),
dateTimeFormatted = DATE_TIME_FORMATTER.format(localDateTime)
)
}
companion object {
private val DAY_OF_MONTH_FORMATTER = DateTimeFormatter.ofPattern("MMM d")
private val MONTH_OF_YEAR_FORMATTER = DateTimeFormatter.ofPattern("MMM yyyy")
private val DATE_FORMATTER = DateTimeFormatter.ofPattern("MMM d, yyyy")
private val DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")
}
}
| 8 | Kotlin | 0 | 0 | 118e8785c1c82afe934c17ba4be45fa03edac51b | 1,248 | twitter-server | MIT License |
app/src/main/java/com/gstormdev/urbandictionary/ui/main/DefinitionAdapter.kt | geoffstorm | 276,220,454 | false | null | package com.gstormdev.urbandictionary.ui.main
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.gstormdev.urbandictionary.databinding.DefinitionListItemBinding
import com.gstormdev.urbandictionary.entity.Definition
class DefinitionAdapter : RecyclerView.Adapter<DefinitionViewHolder>() {
private var definitions: List<Definition> = emptyList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefinitionViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return DefinitionViewHolder(DefinitionListItemBinding.inflate(layoutInflater, parent, false))
}
override fun getItemCount() = definitions.size
override fun onBindViewHolder(holder: DefinitionViewHolder, position: Int) {
holder.bind(definitions[position])
}
fun setData(definitions: List<Definition>) {
val diffResult = DiffUtil.calculateDiff(DefinitionDiffCallback(definitions, this.definitions))
diffResult.dispatchUpdatesTo(this)
this.definitions = definitions
}
}
class DefinitionViewHolder(private val binding: DefinitionListItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(model: Definition) {
binding.tvWord.text = model.word
binding.tvDefinition.text = model.getDisplayFormattedDefinition()
binding.tvThumbsUpCount.text = model.thumbs_up.toString()
binding.tvThumbsDownCount.text = model.thumbs_down.toString()
}
}
class DefinitionDiffCallback(private val newData: List<Definition>, private val data: List<Definition>) : DiffUtil.Callback() {
override fun getOldListSize() = data.size
override fun getNewListSize() = newData.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// Check IDs to see if the items are the same
return data[oldItemPosition].defid == newData[newItemPosition].defid
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// Check deeper contents to see if the data within the item is the same
return data[oldItemPosition] == newData[newItemPosition]
}
} | 0 | Kotlin | 0 | 0 | bab7d5e6babb69cbb909ff16bb4bedac551588b5 | 2,270 | UrbanDictionary | MIT License |
idea/testData/quickfix/createFromUsage/createVariable/property/memberVarDelegateRuntime.kt | JakeWharton | 99,388,807 | true | null | // "Create property 'foo'" "true"
// ERROR: Property must be initialized or be abstract
// ERROR: Variable 'foo' must be initialized
class A<T> {
var x: A<Int> by <caret>foo
}
| 1 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 181 | kotlin | Apache License 2.0 |
fragmenttracer-navigation/src/main/java/com/atsuya046/fragmenttracer/navigation/FragmentTracerNavigation.kt | atsuya046 | 333,294,621 | false | null | package com.atsuya046.fragmenttracer.navigation
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.fragment.NavHostFragment
import com.atsuya046.fragmenttracer.FragmentPerformanceTracer
fun Fragment.attachPerformanceTracer() {
val fragmentTracer = FragmentPerformanceTracer()
this.lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) = when(event) {
Lifecycle.Event.ON_CREATE -> fragmentTracer.start(childFragmentManager)
Lifecycle.Event.ON_DESTROY -> fragmentTracer.stop(childFragmentManager)
else -> {
// nothing to do
}
}
})
}
open class FragmentTraceableNavHostFragment: NavHostFragment() {
init {
this.attachPerformanceTracer()
}
}
| 0 | Kotlin | 0 | 0 | 3f2dcb620663cb876d1564870ba0f4441da3f6a1 | 967 | FragmentTracer | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/PlaceholderCubemap.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1482791, "GDScript": 533983, "C++": 491643, "C": 12468, "C#": 10278, "Shell": 7406, "Java": 2153, "CMake": 939, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import kotlin.Boolean
import kotlin.Int
import kotlin.Suppress
/**
* A [godot.Cubemap] without image data.
*
* This class replaces a [godot.Cubemap] or a [godot.Cubemap]-derived class in 2 conditions:
*
* - In dedicated server mode, where the image data shouldn't affect game logic. This allows reducing the exported PCK's size significantly.
*
* - When the [godot.Cubemap]-derived class is missing, for example when using a different engine version.
*
* **Note:** This class is not intended for rendering or for use in shaders. Operations like calculating UV are not guaranteed to work.
*/
@GodotBaseType
public open class PlaceholderCubemap : PlaceholderTextureLayered() {
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_PLACEHOLDERCUBEMAP, scriptIndex)
return true
}
public companion object
internal object MethodBindings
}
| 63 | Kotlin | 39 | 571 | 39dc30230a30d2a6ab4ec3277eb3bc270995ab23 | 1,346 | godot-kotlin-jvm | MIT License |
src/main/kotlin/com/masdiq/plugins/Koin.kt | nickdferrara | 651,884,974 | false | null | package com.masdiq.plugins
import com.masdiq.di.koinModule
import io.ktor.server.application.*
import org.koin.ktor.plugin.Koin
import org.koin.logger.slf4jLogger
fun Application.configureKoin() {
install(Koin) {
slf4jLogger()
modules(koinModule)
}
} | 0 | Kotlin | 1 | 0 | 57d49ef031600916b9fb28c474386d5981b90816 | 276 | server-ktor-heroapp | MIT License |
app/src/main/java/com/phil/airinkorea/ui/home/HomeRoute.kt | wonhaeseong | 574,473,916 | false | {"Kotlin": 198684} | package com.phil.airinkorea.ui.home
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.phil.airinkorea.data.model.Page
import com.phil.airinkorea.viewmodel.DrawerUiState
import com.phil.airinkorea.viewmodel.HomeUiState
import com.phil.airinkorea.viewmodel.HomeViewModel
@Composable
fun HomeRoute(
onManageLocationClick: () -> Unit,
onParticulateMatterInfoClick: () -> Unit,
onAppInfoClick: () -> Unit,
homeViewModel: HomeViewModel = hiltViewModel(LocalContext.current as ComponentActivity),
) {
val context = LocalContext.current
val packageName = context.packageName
val homeUiState: HomeUiState by homeViewModel.homeUiState.collectAsStateWithLifecycle()
val drawerUiState: DrawerUiState by homeViewModel.drawerUiState.collectAsStateWithLifecycle()
val locationPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
homeViewModel.onLocationPermissionGranted()
} else {
homeViewModel.onLocationPermissionDenied()
}
}
val enableLocationSettingLauncher =
rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) { result ->
if (result.resultCode == AppCompatActivity.RESULT_OK) {
homeViewModel.onLocationSettingGranted()
} else {
homeViewModel.onLocationSettingDenied()
}
}
HomeScreen(
onRefresh = { homeViewModel.onRefreshHomeScreen() },
onSettingButtonClick = {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.data = Uri.fromParts("package", packageName, null)
context.startActivity(intent)
},
onManageLocationClick = onManageLocationClick,
onParticulateMatterInfoClick = onParticulateMatterInfoClick,
onAppInfoClick = onAppInfoClick,
onDrawerGPSClick = { homeViewModel.onDrawerLocationClick(Page.GPS) },
onDrawerBookmarkClick = { homeViewModel.onDrawerLocationClick(Page.Bookmark) },
onDrawerCustomLocationClick = { homeViewModel.onDrawerLocationClick(Page.CustomLocation(it)) },
homeUiState = homeUiState,
drawerUiState = drawerUiState
)
LaunchedEffect(homeUiState.requestLocationPermission) {
if (homeUiState.requestLocationPermission) {
locationPermissionLauncher.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
}
}
LaunchedEffect(homeUiState.resolvableApiException) {
if (homeUiState.resolvableApiException != null) {
val intentSenderRequest =
IntentSenderRequest.Builder(homeUiState.resolvableApiException!!.resolution)
.build()
enableLocationSettingLauncher.launch(intentSenderRequest)
}
}
}
| 1 | Kotlin | 0 | 1 | c6f204fffb3e9a35067bb8afdfacb63628a58453 | 3,567 | AirInKorea | Apache License 2.0 |
core/src/main/kotlin/materialui/components/button/ButtonElementBuilder.kt | subroh0508 | 167,797,152 | false | null | package materialui.components.button
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import materialui.components.button.enums.ButtonColor
import materialui.components.button.enums.ButtonSize
import materialui.components.button.enums.ButtonStyle
import materialui.components.button.enums.ButtonVariant
import materialui.components.buttonbase.ButtonBaseElementBuilder
import materialui.components.getValue
import materialui.components.setValue
import react.RBuilder
import react.RClass
import react.ReactElement
import react.buildElement
class ButtonElementBuilder<T: Tag> internal constructor(
type: RClass<ButtonProps>,
classMap: List<Pair<Enum<*>, String>>,
factory: (TagConsumer<Unit>) -> T
) : ButtonBaseElementBuilder<T, ButtonProps>(type, classMap, factory) {
fun Tag.classes(vararg classMap: Pair<ButtonStyle, String>) {
classes(classMap.map { it.first to it.second })
}
var Tag.color: ButtonColor? by materialProps
var Tag.endIcon: ReactElement? by materialProps
var Tag.fullWidth: Boolean? by materialProps
var Tag.href: String? by materialProps
var Tag.size: ButtonSize? by materialProps
var Tag.startIcon: ReactElement? by materialProps
var Tag.variant: ButtonVariant? by materialProps
fun Tag.endIcon(builder: RBuilder.() -> Unit) { endIcon = buildElement(builder) }
fun Tag.startIcon(builder: RBuilder.() -> Unit) { startIcon = buildElement(builder) }
} | 14 | null | 27 | 81 | a959a951ace3b9bd49dc5405bea150d4d53cf162 | 1,442 | kotlin-material-ui | MIT License |
feature/randomcards/src/main/kotlin/com/donghanx/randomcards/navigation/RandomCardsNavigation.kt | DonghanX | 697,115,187 | false | {"Kotlin": 185893} | package com.donghanx.randomcards.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.donghanx.randomcards.RandomCardsScreen
const val RANDOM_CARDS_GRAPH_ROUTE = "RandomCardsGraph"
const val RANDOM_CARDS_ROUTE = "RandomCards"
fun NavGraphBuilder.randomCardsGraph(
onCardClick: (cardId: String, parentRoute: String) -> Unit,
nestedGraphs: NavGraphBuilder.(parentRoute: String) -> Unit,
onShowSnackbar: suspend (message: String) -> Unit,
) {
navigation(startDestination = RANDOM_CARDS_ROUTE, route = RANDOM_CARDS_GRAPH_ROUTE) {
composable(
route = RANDOM_CARDS_ROUTE,
) {
RandomCardsScreen(
onCardClick = { cardId -> onCardClick(cardId, RANDOM_CARDS_ROUTE) },
onShowSnackbar = onShowSnackbar
)
}
nestedGraphs(RANDOM_CARDS_ROUTE)
}
}
| 0 | Kotlin | 0 | 0 | eb34db7c412e65f639cf2c1caaf7fc37736c2b06 | 951 | nowinmtg | MIT License |
src/test/kotlin/name/valery1707/problem/e/olymp/Problem2863KTest.kt | valery1707 | 541,970,894 | false | null | package name.valery1707.problem.e.olymp
import name.valery1707.problem.TestUtilsJ.withinConsole
import name.valery1707.problem.junit.Implementation
import name.valery1707.problem.junit.ImplementationSource
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
internal class Problem2863KTest {
@ParameterizedTest
@ImplementationSource(
implementation = [Problem2863K.Implementation::class],
csv = [CsvSource(
"1,1",
"2,1",
"3,1|3",
"12,1|3",
)]
)
internal fun test1(variant: Implementation<Problem2863K>, input: String, expected: String) {
assertThat(withinConsole("|", input, variant.get()::main)).isEqualTo(expected)
}
}
| 3 | null | 1 | 1 | 55f9cb65499168735277131e2fbe44a918ec86ca | 822 | problem-solving | MIT License |
comm/src/main/java/dev/franco/comm/DiscoveryService.kt | frank240889 | 647,016,046 | false | null | package dev.franco.comm
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.nsd.NsdManager
import android.net.nsd.NsdManager.DiscoveryListener
import android.net.nsd.NsdManager.FAILURE_INTERNAL_ERROR
import android.net.nsd.NsdManager.ResolveListener
import android.net.nsd.NsdServiceInfo
import android.net.wifi.WifiManager
import android.os.Binder
import android.text.format.Formatter
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class DiscoveryService : Service() {
private var nsdManager: NsdManager? = null
private var serviceInfo: NsdServiceInfo? = null
// For testing
var serviceStarted = false
var serviceStopped = false
private var discoveryListener: DiscoveryListener? = null
private var resolveListener: ResolveListener? = null
private val timeOutJob: Job = Job()
private val serviceCoroutineScope = CoroutineScope(timeOutJob)
private lateinit var myIp: String
private var serviceType: String = ""
private var serviceName: String = ""
override fun onBind(intent: Intent?) = LocalBinder()
override fun onCreate() {
super.onCreate()
serviceStarted = true
myIp = getSelfWiFiIp()
Log.e("my ip", myIp)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
nsdManager = getSystemService(NSD_SERVICE) as NsdManager
serviceType = getServiceType(intent)
serviceName = getServiceName(intent)
discoveryListener = provideDiscoveryListener()
discoverServices(serviceType, discoveryListener)
return START_NOT_STICKY
}
override fun stopService(name: Intent?): Boolean {
serviceStopped = true
stopDiscoverServices(discoveryListener)
resolveListener = null
discoveryListener = null
return super.stopService(name)
}
private fun getServiceType(intent: Intent?) = intent?.getStringExtra(SERVICE_TYPE).orEmpty()
private fun getServiceName(intent: Intent?) = intent?.getStringExtra(SERVICE_NAME).orEmpty()
private fun discoverServices(
serviceType: String,
listener: DiscoveryListener?,
protocolType: Int = NsdManager.PROTOCOL_DNS_SD,
) {
if (serviceType.isEmpty()) {
Log.e("discoverServices", serviceType)
sendBroadcast(
Intent(INTENT_FILTER_INVALID_SERVICE_TYPE).apply {
putExtra(NSD_ERROR_CODE, INVALID_SERVICE.toString())
},
)
stopDiscoveryService(this)
} else {
tryStartDiscovery(serviceType, protocolType, listener)
}
}
private fun tryStartDiscovery(
serviceType: String,
protocolType: Int,
listener: DiscoveryListener?,
) {
try {
listener?.let {
Log.e("tryStartDiscovery", serviceType)
nsdManager!!.discoverServices(serviceType, protocolType, it)
dispatchTimeoutNsdDiscoveryAt()
} ?: run {
}
} catch (_: IllegalArgumentException) {
listener?.let {
nsdManager!!.stopServiceDiscovery(it)
}
sendBroadcast(
Intent(INTENT_FILTER_START_DISCOVERY_FAILED).apply {
putExtra(SERVICE_NAME, serviceInfo)
putExtra(NSD_ERROR_CODE, FAILURE_INTERNAL_ERROR.toString())
},
)
stopDiscoveryService(this)
}
}
private fun stopDiscoverServices(discoveryListener: DiscoveryListener?) {
try {
discoveryListener?.let {
nsdManager?.stopServiceDiscovery(it)
}
} catch (_: IllegalArgumentException) {
}
}
private fun dispatchTimeoutNsdDiscoveryAt(timeout: Long = 30000L) {
serviceCoroutineScope.launch {
delay(timeout)
sendBroadcastTimeout()
Log.e("discoverServicesTimeOut", "discoverServicesTimeOut")
stopDiscoveryService(this@DiscoveryService)
cancel()
}
}
private fun cancelTimeoutNsdDiscovery() {
if (timeOutJob.isActive) {
timeOutJob.cancel()
}
}
private fun sendBroadcastTimeout() {
sendBroadcast(
Intent(INTENT_FILTER_DISCOVERY_TIMEOUT).apply {
putExtra(SERVICE_TYPE, serviceInfo?.serviceType)
putExtra(SERVICE_NAME, serviceInfo?.serviceName)
putExtra(NSD_ERROR_CODE, SERVICE_DISCOVERY_TIMEOUT.toString())
},
)
}
private fun provideDiscoveryListener(): DiscoveryListener {
return object : DiscoveryListener {
override fun onDiscoveryStarted(service: String?) {
Log.e("onDiscoveryStarted", service.toString())
sendBroadcast(
Intent(INTENT_FILTER_DISCOVERY_STARTED).apply {
putExtra(SERVICE_NAME, service)
},
)
}
override fun onDiscoveryStopped(service: String?) {
Log.e("onDiscoveryStopped", service.toString())
sendBroadcast(
Intent(INTENT_FILTER_DISCOVERY_STOPPED).apply {
putExtra(SERVICE_NAME, service)
},
)
cancelTimeoutNsdDiscovery()
stopDiscoveryService(this@DiscoveryService)
}
override fun onStartDiscoveryFailed(service: String?, code: Int) {
Log.e("onStartDiscoveryFailed", "service $service - code: $code")
sendBroadcast(
Intent(INTENT_FILTER_START_DISCOVERY_FAILED).apply {
putExtra(SERVICE_NAME, service)
putExtra(NSD_ERROR_CODE, code.toString())
},
)
cancelTimeoutNsdDiscovery()
stopDiscoveryService(this@DiscoveryService)
}
override fun onStopDiscoveryFailed(service: String?, code: Int) {
Log.e("onStopDiscoveryFailed", "service $service - code: $code")
sendBroadcast(
Intent(INTENT_FILTER_STOP_DISCOVERY_FAILED).apply {
putExtra(SERVICE_NAME, service)
putExtra(NSD_ERROR_CODE, code.toString())
},
)
cancelTimeoutNsdDiscovery()
stopDiscoveryService(this@DiscoveryService)
}
override fun onServiceFound(service: NsdServiceInfo?) {
Log.e("onServiceFound", "$service")
if (service?.serviceType == [email protected] &&
service.serviceName != [email protected] &&
service.serviceName?.contains("NsdChat") == true
) {
Log.e("Filtered service", "$service")
serviceInfo = service
sendBroadcast(
Intent(INTENT_FILTER_SERVICE_FOUND).apply {
putExtra(SERVICE_TYPE, service.serviceType)
putExtra(SERVICE_NAME, service.serviceName)
},
)
stopDiscoverServices(discoveryListener)
resolveListener = provideResolveListener()
nsdManager?.resolveService(serviceInfo, resolveListener)
}
}
override fun onServiceLost(service: NsdServiceInfo?) {
Log.e("onServiceLost", "service $service")
sendBroadcast(
Intent(INTENT_FILTER_SERVICE_LOST).apply {
putExtra(HOST_IP, service?.host)
putExtra(PORT, service?.port)
putExtra(SERVICE_TYPE, service?.serviceType)
putExtra(SERVICE_NAME, service?.serviceName)
},
)
cancelTimeoutNsdDiscovery()
stopDiscoveryService(this@DiscoveryService)
}
}
}
private fun provideResolveListener(): ResolveListener {
return object : ResolveListener {
override fun onResolveFailed(service: NsdServiceInfo?, code: Int) {
Log.e("onResolveFailed", "service $service - code: $code")
cancelTimeoutNsdDiscovery()
if (service?.serviceType == [email protected] &&
service.serviceName != [email protected] &&
service.serviceName?.contains("NsdChat") == true
) {
Log.e("filtered onResolveFailed", "service $service - code: $code")
sendBroadcast(
Intent(INTENT_FILTER_FAILED_RESOLVED).apply {
putExtra(SERVICE_TYPE, service.serviceType)
putExtra(SERVICE_NAME, service.serviceName)
putExtra(NSD_ERROR_CODE, code.toString())
},
)
}
}
override fun onServiceResolved(service: NsdServiceInfo?) {
Log.e("onServiceResolved", "service $service")
if (service?.serviceName != [email protected] &&
service?.serviceName?.contains("NsdChat") == true
) {
Log.e("filtered onServiceResolved", "service $service")
Log.e("sendBroadcast", INTENT_FILTER_SERVICE_RESOLVED)
sendBroadcast(
Intent(INTENT_FILTER_SERVICE_RESOLVED).apply {
putExtra(HOST_IP, service.host?.hostAddress)
putExtra(PORT, service.port.toString())
putExtra(SERVICE_TYPE, service.serviceType)
putExtra(SERVICE_NAME, service.serviceName)
},
)
cancelTimeoutNsdDiscovery()
stopDiscoveryService(this@DiscoveryService)
}
}
}
}
private fun getSelfWiFiIp(): String {
val wifiMgr = getSystemService(WIFI_SERVICE) as WifiManager
val wifiInfo = wifiMgr.connectionInfo
val ip = wifiInfo.ipAddress
return Formatter.formatIpAddress(ip)
}
companion object {
const val INTENT_FILTER_DISCOVERY_STARTED = "intent_filter_discovery_started"
const val INTENT_FILTER_DISCOVERY_STOPPED = "intent_filter_discovery_stopped"
const val INTENT_FILTER_START_DISCOVERY_FAILED = "intent_filter_start_discovery_failed"
const val INTENT_FILTER_STOP_DISCOVERY_FAILED = "intent_filter_stop_discovery_failed"
const val INTENT_FILTER_SERVICE_FOUND = "intent_filter_service_found"
const val INTENT_FILTER_SERVICE_LOST = "intent_filter_service_lost"
const val INTENT_FILTER_SERVICE_RESOLVED = "intent_filter_service_resolved"
const val INTENT_FILTER_FAILED_RESOLVED = "intent_filter_failed_resolved"
const val INTENT_FILTER_DISCOVERY_TIMEOUT = "intent_filter_discovery_timeout"
const val INTENT_FILTER_INVALID_SERVICE_TYPE = "intent_filter_invalid_service_type"
const val SERVICE_TYPE = "service_type"
const val HOST_IP = "host_ip"
const val PORT = "port"
const val NSD_ERROR_CODE = "nsd_error_code"
const val SERVICE_NAME = "service_name"
const val INVALID_SERVICE = 10
// Occur when request to NSD last so much for connection issues.
const val SERVICE_DISCOVERY_TIMEOUT = 20
const val ACTION = "action"
fun startDiscoveryService(context: Context, serviceType: String, serviceName: String?) {
val intent = Intent(context, DiscoveryService::class.java).apply {
putExtra(SERVICE_TYPE, serviceType)
putExtra(SERVICE_NAME, serviceName)
}
context.startService(intent)
}
fun stopDiscoveryService(context: Context) {
context.stopService(
Intent(context, DiscoveryService::class.java),
)
}
fun extractDiscoveryData(intent: Intent?): MutableMap<String, String?> {
return mutableMapOf(
ACTION to intent?.action,
HOST_IP to intent?.getStringExtra(HOST_IP),
PORT to intent?.getStringExtra(PORT),
SERVICE_NAME to intent?.getStringExtra(SERVICE_NAME),
NSD_ERROR_CODE to intent?.getStringExtra(NSD_ERROR_CODE),
)
}
}
// For testing
inner class LocalBinder : Binder() {
fun getService(): DiscoveryService = this@DiscoveryService
}
}
| 0 | Kotlin | 0 | 0 | 270d447c685201af024c2d7b15d1501ae34006e4 | 13,161 | SecureChat | MIT License |
ktor-io/jvm/src/io/ktor/utils/io/jvm/nio/Reading.kt | ktorio | 40,136,600 | false | null | package kotlinx.coroutines.io.jvm.nio
import kotlinx.coroutines.io.*
import java.nio.*
import java.nio.channels.*
/**
* Copies up to [limit] bytes from blocking NIO channel to CIO [ch]. It does suspend if no space available for writing
* in the destination channel but may block if source NIO channel blocks.
*
* @return number of bytes were copied
*/
suspend fun ReadableByteChannel.copyTo(ch: ByteWriteChannel, limit: Long = Long.MAX_VALUE): Long {
require(limit >= 0L) { "Limit shouldn't be negative: $limit" }
if (this is SelectableChannel && !isBlocking) {
throw IllegalArgumentException("Non-blocking channels are not supported")
}
var copied = 0L
var eof = false
val copy: (ByteBuffer) -> Unit = { bb ->
val rem = limit - copied
if (rem < bb.remaining()) {
val l = bb.limit()
bb.limit(bb.position() + rem.toInt())
val rc = read(bb)
if (rc == -1) eof = true
else copied += rc
bb.limit(l)
} else {
val rc = read(bb)
if (rc == -1) eof = true
else copied += rc
}
}
val needFlush = !ch.autoFlush
while (copied < limit && !eof) {
ch.write(1, copy)
if (needFlush) ch.flush()
}
return copied
}
/**
* Copies up to [limit] bytes from a blocking NIO pipe to CIO [ch]. A shortcut to copyTo with
* NIO readable channel receiver
*
* @return number of bytes copied
*/
suspend fun Pipe.copyTo(ch: ByteWriteChannel, limit: Long = Long.MAX_VALUE): Long = source().copyTo(ch, limit)
| 269 | null | 806 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 1,596 | ktor | Apache License 2.0 |
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/persistence/models/firestore/grammarrule/GrammarRuleListModel.kt | MihailsKuzmins | 240,947,625 | false | null | package jp.mihailskuzmins.sugoinihongoapp.persistence.models.firestore.grammarrule
import jp.mihailskuzmins.sugoinihongoapp.persistence.models.HasId
class GrammarRuleListModel(override val id: String) : HasId {
var header: String = ""
var body: String = ""
} | 1 | null | 1 | 1 | 57e19b90b4291dc887a92f6d57f9be349373a444 | 263 | sugoi-nihongo-android | Apache License 2.0 |
common/src/main/java/com/kms/common/storage/User.kt | flymrc | 345,905,394 | false | null | package com.kms.common.storage
import cn.leancloud.AVException
import cn.leancloud.AVFile
import cn.leancloud.AVObject
import cn.leancloud.AVUser
import cn.leancloud.annotation.AVClassName
@AVClassName("_User")
class User : AVUser() {
companion object {
const val KEY_NICKNAME = "name"
const val KEY_AVATAR_FILE = "avatarFile"
fun newPointer(objectId: String): AVUser {
return AVObject.createWithoutData(AVUser::class.java, objectId)
}
}
val defaultNickname get() = "kms${getObjectId().substring(0, 8)}"
var nickname: String
get() {
val value = get(KEY_NICKNAME)
return if (value is String) {
value
} else {
throw AVException(AVException.INCORRECT_TYPE, "Invalid value, expect kotlin.String, got ${value.javaClass}")
}
}
set(value) = put(KEY_NICKNAME, value)
var avatarFile: AVFile
get() {
val value = get(KEY_AVATAR_FILE)
return if (value is AVFile) {
value
} else {
throw AVException(AVException.INCORRECT_TYPE, "Invalid value, expect AVFile, got ${value.javaClass}")
}
}
set(value) = put(KEY_AVATAR_FILE, value)
}
| 4 | Kotlin | 0 | 0 | 1ee479d0d6ba9203a651076e5141632b718f9797 | 1,295 | kid-management-system | MIT License |
src/main/kotlin/structures/GraphWithWeights.kt | DmitryTsyvtsyn | 418,166,620 | false | {"Kotlin": 228861} | package structures
/**
*
* Graph is a non-linear data structure consisting of vertices and edges.
*
* The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph.
*
* More formally a Graph is composed of a set of vertices V and a set of edges E. The graph is denoted by G(E, V).
*
* Directed graph with weights is a type of graph where the edges have specified direction and weights assigned to the them.
*
*/
class GraphWithWeights<T> {
private val data = linkedMapOf<Vertex<T>, MutableList<VertexConnection<T>>>()
// Complexity: O(1)
fun addVertex(value: T) {
data.putIfAbsent(Vertex(value), mutableListOf())
}
// Complexity: O(n)
fun removeVertex(value: T) {
val removingVertex = Vertex(value)
data.values.forEach { connections ->
connections.removeIf { it.vertex == removingVertex }
}
data.remove(removingVertex)
}
// Complexity: O(1)
fun addEdge(value1: T, value2: T, cost: Int) {
val vertex1 = Vertex(value1)
val vertex2 = Vertex(value2)
data[vertex1]?.add(VertexConnection(vertex2, cost))
}
// Complexity: O(n)
fun removeEdge(value1: T, value2: T) {
val vertex1 = Vertex(value1)
val vertex2 = Vertex(value2)
data[vertex1]?.removeIf { it.vertex == vertex2 }
}
// returns the associated vertices and their weights with the given vertex value
fun connectedVertexesWithWeights(value: T) = data[Vertex(value)]?.map { it.toString() } ?: emptyList()
/**
*
* Dijkstra's algorithm,
*
* returns pairs of a vertex and the minimum weight needed to get to that vertex,
*
* the starting vertex is the first added
*
*/
fun dijkstraAlgorithm(): Map<T, Int> {
if (data.isEmpty()) return emptyMap()
val unvisitedVertexes = linkedMapOf<Vertex<T>, Int>()
data.keys.forEach { vertex ->
unvisitedVertexes[vertex] = Int.MAX_VALUE
}
val visitedVertexes = linkedMapOf<T, Int>()
var minimumCost = 0
var currentVertex = unvisitedVertexes.keys.first()
while(unvisitedVertexes.isNotEmpty()) {
val neighbourVertexConnections = data[currentVertex] ?: emptyList()
for (neighbourVertexConnection in neighbourVertexConnections) {
val neighbourVertex = neighbourVertexConnection.vertex
if (!unvisitedVertexes.contains(neighbourVertex)) continue
val newCost = minimumCost + neighbourVertexConnection.cost
val neighbourVertexCost = unvisitedVertexes[neighbourVertex] ?: Int.MAX_VALUE
if (neighbourVertexCost > newCost) {
unvisitedVertexes[neighbourVertex] = newCost
}
}
visitedVertexes[currentVertex.value] = minimumCost
unvisitedVertexes.remove(currentVertex)
val nextUnvisitedEntry = unvisitedVertexes.entries
.filter { it.value != Int.MAX_VALUE }
.minByOrNull { it.value } ?: return visitedVertexes
currentVertex = nextUnvisitedEntry.key
minimumCost = nextUnvisitedEntry.value
}
return visitedVertexes
}
private data class Vertex<T>(val value: T)
// helper class for defining graph weights
private data class VertexConnection<T>(val vertex: Vertex<T>, val cost: Int) {
override fun toString(): String = "vertex -> ${vertex.value}, cost -> $cost"
}
} | 0 | Kotlin | 135 | 788 | 1f89f062a056e24cc289ffdd0c6e23cadf8df887 | 3,587 | Kotlin-Algorithms-and-Design-Patterns | MIT License |
app/src/main/java/com/spf/app/data/RouteInfo.kt | arshdeepdhillon | 467,025,478 | false | null | package com.spf.app.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.NO_ACTION
import androidx.room.PrimaryKey
// Not using ForeignKey.CASCADE on child table in case we need to manipulate data on delete (ie: Recycle Bin)
@Entity(tableName = "routeInfo", foreignKeys = [ForeignKey(
entity = RouteGroup::class,
parentColumns = ["groupId"],
childColumns = ["groupId"],
onDelete = NO_ACTION)]
)
data class RouteInfo(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "routeId")
val routeId: Long,
@ColumnInfo(name = "groupId")
val groupId: Long,
@ColumnInfo(name = "address")
val address: String,
@ColumnInfo(name = "optimalIndex", defaultValue = "0")
val optIndex: Long,
@ColumnInfo(name = "dragState", defaultValue = "false")
val dragState: Boolean,
)
/** To manage the state of RouteInfo item on swipe */
enum class DataState {
/** Item can be shown in UI */
SHOW,
/** Item has been removed/swiped from UI by user so hide it until user's final action */
HIDE,
/** Ready to be delete */
DELETE
} | 0 | Kotlin | 0 | 0 | 3a4ef605cf193c552364406a96296cbae1050290 | 1,164 | SPF | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.