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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/tonnoz/errorhandling/ErrorhandlingApplication.kt | tonnoz | 710,644,819 | false | {"Kotlin": 21473} | package com.tonnoz.errorhandling
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ErrorhandlingApplication
fun main(args: Array<String>) {
runApplication<ErrorhandlingApplication>(*args)
}
| 0 | Kotlin | 0 | 0 | 5413e5a47f363cb0bf6f733b2e4b46e811e8c8ae | 288 | functional-errors-kotlin | MIT License |
src/me/anno/io/base/BaseReader.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.io.base
import me.anno.Build
import me.anno.io.Saveable
import me.anno.utils.types.Strings.isBlank2
import org.apache.logging.log4j.LogManager
import java.io.IOException
abstract class BaseReader {
private val withPtr = ArrayList<Saveable>()
private val withoutPtr = ArrayList<Saveable>()
val allInstances = ArrayList<Saveable>()
val sortedContent: List<Saveable> get() = (withPtr + withoutPtr).filter { it !== UnitSaveable }
// for debugging
var sourceName = ""
private val missingReferences = HashMap<Int, ArrayList<Pair<Saveable, String>>>()
fun getByPointer(ptr: Int, warnIfMissing: Boolean): Saveable? {
val index = ptr - 1
when {
index in withPtr.indices -> return withPtr[index]
warnIfMissing -> {
if (sourceName.isBlank2()) {
LOGGER.warn("Missing object *$ptr, only ${withPtr.size} available")
} else {
LOGGER.warn("Missing object *$ptr, only ${withPtr.size} available by '$sourceName'")
}
}
}
return null
}
private fun setContent(ptr: Int, saveable: Saveable) {
// LOGGER.info("SetContent($ptr, ${Saveable.className})")
if (ptr < 0) withoutPtr.add(saveable)
else {
// add missing instances
val index = ptr - 1
for (i in withPtr.size..index) {
withPtr.add(UnitSaveable)
}
withPtr[index] = saveable
}
}
fun register(value: Saveable, ptr: Int) {
if (ptr != 0) {
setContent(ptr, value)
val missingReferences = missingReferences[ptr]
if (missingReferences != null) {
for ((obj, name) in missingReferences) {
obj.setProperty(name, value)
}
}
} else LOGGER.warn("Got object with uuid 0: $value, it will be ignored")
}
fun addMissingReference(owner: Saveable, name: String, childPtr: Int) {
missingReferences
.getOrPut(childPtr) { ArrayList() }
.add(owner to name)
}
fun start(): Int = allInstances.size
fun finish(start: Int = 0) {
for (i in start until allInstances.size) {
allInstances[i].onReadingEnded()
}
}
abstract fun readObject(): Saveable
abstract fun readAllInList()
companion object {
private val UnitSaveable = Saveable()
private val LOGGER = LogManager.getLogger(BaseReader::class)
fun <V> assertEquals(a: V, b: V, msg: String) {
if (a != b) throw IOException("$msg, $a != $b")
}
fun <V> assertEquals(a: V, b: V) {
if (a != b) throw IOException("$a != $b")
}
fun error(msg: String): Nothing = throw InvalidFormatException("[BaseReader] $msg")
fun error(msg: String, appended: Any?): Nothing = throw InvalidFormatException("[BaseReader] $msg $appended")
fun getNewClassInstance(className: String): Saveable {
val type = Saveable.objectTypeRegistry[className]
if (type == null) {
if (Build.isDebug) debugInfo(className)
throw UnknownClassException(className)
}
val instance = type.generate()
instance.onReadingStarted()
return instance
}
fun debugInfo(className: String) {
LOGGER.info(
"Looking for $className:${className.hashCode()}, " +
"available: ${Saveable.objectTypeRegistry.keys.joinToString { "${it}:${it.hashCode()}:${if (it == className) 1 else 0}" }}"
)
}
}
} | 0 | null | 3 | 23 | 69aa0fd02cd06ce4106542e902fa57df80c0d4cf | 3,736 | RemsEngine | Apache License 2.0 |
tools/api-classes-generator/src/main/kotlin/Graph.kt | JustinMullin | 238,797,090 | true | {"Kotlin": 310490, "C": 6051, "Shell": 1900} | class Graph<T>(elements: List<T>, sortFun: (T, T) -> Boolean) {
val nodes = mutableListOf<Node<T>>()
init {
for (vertex in elements)
nodes.add(Node(vertex))
for (v1 in nodes)
for (v2 in nodes)
if (sortFun(v1.value, v2.value)) {
v2.childs.add(v1)
v1.parent = v2
}
}
class Node<T>(val value: T) {
var parent: Node<T>? = null
var childs = mutableListOf<Node<T>>()
}
}
fun List<Class>.buildTree(): Graph<Class> {
return Graph(this) { child, parent -> child.baseClass == parent.name }
}
fun Graph<Class>.getMethodFromAncestor(cl: Class, method: Method): Method? {
fun check(m: Method): Boolean {
if (m.name == method.name && m.arguments.size == method.arguments.size) {
var flag = true
for (i in m.arguments.indices) {
if (m.arguments[i].type != method.arguments[i].type) flag = false
}
if (flag) return true
}
return false
}
fun Graph.Node<Class>.findMethodInHierarchy(): Method? {
value.methods.forEach {
if (check(it)) return it
}
return parent?.findMethodInHierarchy()
}
return nodes.find { it.value.name == cl.name }?.parent?.findMethodInHierarchy()
}
fun Graph<Class>.doAncestorsHaveMethod(cl: Class, method: Method): Boolean {
if (method.name == "toString") return true
if (cl.baseClass == "") return false
return getMethodFromAncestor(cl, method) != null
}
fun Graph<Class>.doAncestorsHaveProperty(cl: Class, prop: Property): Boolean {
if (cl.baseClass == "") return false
fun Graph.Node<Class>.findPropertyInHierarchy(): Boolean {
value.properties.forEach {
if (it.name == prop.name) return true
}
return parent?.findPropertyInHierarchy() ?: false
}
return nodes.find { it.value.name == cl.name }!!.parent!!.findPropertyInHierarchy()
}
fun Graph<Class>.getSanitisedArgumentName(method: Method, index: Int, cl: Class): String {
val parentMethod = getMethodFromAncestor(cl, method)
return (parentMethod ?: method).arguments[index].name
} | 0 | Kotlin | 0 | 0 | debe14101a48ca926477ac333cd465e60a6aebc0 | 2,224 | godot-kotlin | Apache License 2.0 |
graphql/src/test/kotlin/com/joe/quizzy/graphql/groupme/GroupMeServiceTest.kt | josephlbarnett | 257,994,447 | false | null | package com.joe.quizzy.graphql.groupme
import assertk.assertFailure
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import assertk.assertions.messageContains
import com.fasterxml.jackson.databind.ObjectMapper
import com.joe.quizzy.persistence.api.GroupMeInfo
import com.joe.quizzy.persistence.api.GroupMeInfoDAO
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.toByteArray
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.http.headersOf
import io.ktor.serialization.jackson.jackson
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import org.testng.annotations.Test
import java.io.ByteArrayInputStream
import java.util.UUID
class GroupMeServiceTest {
@Test
fun testService() = runBlocking {
val goodUUID = UUID.randomUUID()
val dao = mockk<GroupMeInfoDAO>()
every {
dao.get(any())
} returns null
every {
dao.get(goodUUID)
} returns GroupMeInfo(goodUUID, "groupId", "apiKey")
val jsonResponse = ObjectMapper().writeValueAsString(UploadResponse(UploadUrls("https://blah.com/image", "")))
val client = HttpClient(MockEngine) {
engine {
addHandler {
if (it.url.toString() == "https://image.groupme.com/pictures") {
respond(jsonResponse, headers = headersOf("Content-Type", "application/json"))
} else {
respond("pong")
}
}
}
install(ContentNegotiation) {
jackson()
}
}
assertFailure {
GroupMeService(dao, client, UUID.randomUUID())
}.messageContains("No groupme configured for instance")
val service = GroupMeService(dao, client, goodUUID)
service.postMessage("testMessage")
val requestHistory = (client.engine as MockEngine).requestHistory
assertThat(requestHistory).hasSize(1)
assertThat(requestHistory[0].url.toString()).isEqualTo("https://api.groupme.com/v3/groups/groupId/messages")
assertThat(String(requestHistory[0].body.toByteArray())).contains("testMessage")
assertThat(service.uploadImage(ByteArrayInputStream("lksdjf".toByteArray()))).isEqualTo(
"https://blah.com/image",
)
}
}
| 3 | Kotlin | 0 | 2 | d3cd4e2e100c253c57ac5b3ee2f8e9a9f113492d | 2,560 | quizzy | Apache License 2.0 |
src/main/kotlin/matt/gui/app/app.kt | mgroth0 | 365,616,809 | false | null | package matt.gui.app
import javafx.application.Platform
import javafx.stage.Screen
import javafx.stage.Window
import matt.async.thread.daemon
import matt.exec.app.App
import matt.file.MFile
import matt.file.commons.LogContext
import matt.file.commons.mattLogContext
import matt.fx.control.fxapp.DEFAULT_THROW_ON_APP_THREAD_THROWABLE
import matt.fx.control.fxapp.runFXAppBlocking
import matt.fx.control.wrapper.wrapped.wrapped
import matt.fx.graphics.fxthread.ensureInFXThreadInPlace
import matt.fx.graphics.fxthread.runLaterReturn
import matt.fx.graphics.mag.NEW_MAC_NOTCH_ESTIMATE
import matt.fx.graphics.mag.NEW_MAX_MENU_Y_ESTIMATE_SECONDARY
import matt.fx.graphics.wrapper.FXNodeWrapperDSL
import matt.fx.graphics.wrapper.node.NodeWrapper
import matt.fx.graphics.wrapper.node.parent.ParentWrapper
import matt.fx.graphics.wrapper.node.parent.ParentWrapperImpl
import matt.fx.graphics.wrapper.pane.vbox.VBoxW
import matt.fx.graphics.wrapper.pane.vbox.VBoxWrapperImpl
import matt.gui.app.threadinspectordaemon.ThreadInspectorDaemon
import matt.gui.bindgeom.bindGeometry
import matt.gui.exception.showExceptionPopup
import matt.gui.interact.WindowConfig
import matt.gui.mscene.MScene
import matt.gui.mstage.MStage
import matt.gui.mstage.WMode
import matt.gui.mstage.WMode.NOTHING
import matt.lang.sysprop.props.Monocle
import matt.log.logger.Logger
import matt.log.profile.err.ExceptionResponse
import matt.log.profile.err.ExceptionResponse.EXIT
import matt.log.reporter.TracksTime
import matt.log.warn.warn
import matt.model.code.report.Reporter
import matt.model.flowlogic.singlerunlambda.SingleRunLambda
import matt.rstruct.modID
import kotlin.reflect.full.createInstance
fun startFXWidget(rootOp: VBoxW.() -> Unit) {
runFXAppBlocking {
root<VBoxW> {
rootOp()
}
}
}
fun runFXWidgetBlocking(rootOp: VBoxW.() -> Unit) {
runFXAppBlocking {
root<VBoxW> {
rootOp()
}
}
}
fun runFXAppBlocking(
decorated: Boolean = WindowConfig.DEFAULT.decorated,
fxThread: GuiApp.(args: List<String>) -> Unit
) {
GuiApp(fxThread = fxThread, decorated = decorated).runBlocking()
}
@FXNodeWrapperDSL
open class GuiApp(
args: Array<String> = arrayOf(),
val screenIndex: Int? = null,
decorated: Boolean = WindowConfig.DEFAULT.decorated,
wMode: WMode = NOTHING,
escClosable: Boolean = false,
enterClosable: Boolean = false,
requiresBluetooth: Boolean = false,
private val fxThread: GuiApp.(args: List<String>) -> Unit,
) : App<GuiApp>(args, requiresBluetooth = requiresBluetooth) {
var alwaysOnTop
get() = stage.isAlwaysOnTop
set(value) {
stage.isAlwaysOnTop = value
}
fun requestFocus() = scene!!.root.requestFocus()
var scene: MScene<ParentWrapper<*>>? = null
val fxThreadW: GuiApp.(List<String>) -> Unit = {
// val t = tic("fxThreadW", enabled = false)
// t.toc(0)
fxThread(it)
// t.toc(1)
if (!Monocle.isEnabledInThisRuntime()) {
println("running window fixer daemon")
daemon(name = "Window Fixer Daemon") {
while (true) {
Window.getWindows().map { it.wrapped() }.forEach {
if (it.isShowing && it.screen == null && it.pullBackWhenOffScreen) {
warn("resetting offscreen window")
runLaterReturn {
it.x = 0.0
it.y = 0.0
it.width = 500.0
it.height = 500.0
}
}
}
Thread.sleep(5000)
}
}
} else {
println("did not run window fixer daemon")
}
// t.toc(2)
if (scene != null) {
stage.apply {
scene = [email protected]!!
// t.toc(2.5)
if (!Monocle.isEnabledInThisRuntime()) {
if ([email protected] != null && [email protected] < Screen.getScreens().size) {
val screen = Screen.getScreens()[[email protected]]
val menuY =
if (screen == Screen.getPrimary()) NEW_MAC_NOTCH_ESTIMATE else NEW_MAX_MENU_Y_ESTIMATE_SECONDARY
x = screen.bounds.minX
y = screen.bounds.minY + menuY
width = screen.bounds.width
height = screen.bounds.height - menuY
}
}
// t.toc(2.6)
}.show()
// t.toc(2.7)
}
// t.toc(3)
}
fun scene(op: MScene<ParentWrapper<*>>.() -> Unit) {
scene = MScene<ParentWrapper<*>>(VBoxWrapperImpl<NodeWrapper>()).apply(op) /*vbox is placeholder*/
}
fun initRoot(n: ParentWrapper<*>) {
scene = MScene(n)
}
inline fun <reified N : ParentWrapperImpl<*, *>> root(op: N.() -> Unit = {}): N {
val r = N::class.createInstance()
initRoot(r.apply(op))
return r
}
fun runBlocking(
implicitExit: Boolean = true,
preFX: (App<*>.() -> Unit)? = null,
shutdown: (App<*>.() -> Unit)? = null,
usePreloaderApp: Boolean = false,
logContext: LogContext = mattLogContext,
t: Reporter? = null,
throwOnApplicationThreadThrowable: Boolean = DEFAULT_THROW_ON_APP_THREAD_THROWABLE
) {
(t as? TracksTime)?.toc("starting GuiApp")
(t as? TracksTime)?.toc("installed WrapperService")
val singleRunShutdown = SingleRunLambda {
shutdown?.invoke(this)
}
main(
{
singleRunShutdown.invoke()
},
preFX,
logContext = logContext,
t = t,
enableExceptionAndShutdownHandlers = !throwOnApplicationThreadThrowable
)
(t as? TracksTime)?.toc("ran main")
Platform.setImplicitExit(implicitExit)
(t as? TracksTime)?.toc("about to run FX app blocking")
(t as? Logger)?.info("launching app (mypid = ${matt.lang.myPid})")
runFXAppBlocking(
args = args,
usePreloaderApp = usePreloaderApp,
reporter = t,
throwOnApplicationThreadThrowable = throwOnApplicationThreadThrowable
) {
fxThreadW(args.toList())
}
singleRunShutdown()
ThreadInspectorDaemon.start()
}
override fun extraShutdownHook(
t: Thread,
e: Throwable,
shutdown: (App<*>.() -> Unit)?,
st: String,
exceptionFile: MFile
): ExceptionResponse {
/*don't delete .. I find source of disappearing exceptions*/
println("in extraShutdownHook")
var r = EXIT
try {
ensureInFXThreadInPlace {
println("showing exception popup for t=$t, e=$e")
r = showExceptionPopup(t, e, shutdown, st)
}
} catch (e: Exception) {
println("exception in DefaultUncaughtExceptionHandler Exception Dialog:")
e.printStackTrace()
return EXIT
}
return r
}
val stage by lazy {
MStage(
decorated = decorated, wMode = wMode, EscClosable = escClosable, EnterClosable = enterClosable
).apply {
bindGeometry(modID.appName)
}
}
} | 0 | Kotlin | 0 | 0 | fa89cf699f29059ed63f64d1ac67ef74ad404bdc | 7,559 | gui | MIT License |
coil-compose-base/src/main/java/coil/compose/ImagePainter.kt | yschimke | 423,768,439 | true | {"Kotlin": 668482, "Shell": 1324} | @file:SuppressLint("ComposableNaming")
@file:Suppress("unused")
package coil.compose
import android.annotation.SuppressLint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.RememberObserver
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.isSpecified
import androidx.compose.ui.geometry.isUnspecified
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.compose.ImagePainter.ExecuteCallback
import coil.compose.ImagePainter.State
import coil.decode.DataSource
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.SuccessResult
import coil.size.OriginalSize
import coil.size.Precision
import coil.size.Scale
import coil.transition.CrossfadeTransition
import com.google.accompanist.drawablepainter.DrawablePainter
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Return an [ImagePainter] that will execute an [ImageRequest] using [imageLoader].
*
* @param data The [ImageRequest.data] to load.
* @param imageLoader The [ImageLoader] that will be used to execute the request.
* @param onExecute Called immediately before the [ImagePainter] launches an image request.
* Return 'true' to proceed with the request. Return 'false' to skip executing the request.
* @param builder An optional lambda to configure the request.
*/
@Composable
inline fun rememberImagePainter(
data: Any?,
imageLoader: ImageLoader,
onExecute: ExecuteCallback = ExecuteCallback.Lazy,
builder: ImageRequest.Builder.() -> Unit = {},
): ImagePainter {
val request = ImageRequest.Builder(LocalContext.current)
.apply(builder)
.data(data)
.build()
return rememberImagePainter(request, imageLoader, onExecute)
}
/**
* Return an [ImagePainter] that will execute the [request] using [imageLoader].
*
* @param request The [ImageRequest] to execute.
* @param imageLoader The [ImageLoader] that will be used to execute [request].
* @param onExecute Called immediately before the [ImagePainter] launches an image request.
* Return 'true' to proceed with the request. Return 'false' to skip executing the request.
*/
@Composable
fun rememberImagePainter(
request: ImageRequest,
imageLoader: ImageLoader,
onExecute: ExecuteCallback = ExecuteCallback.Lazy,
): ImagePainter {
requireSupportedData(request.data)
require(request.target == null) { "request.target must be null." }
val scope = rememberCoroutineScope { Dispatchers.Main.immediate + EMPTY_COROUTINE_EXCEPTION_HANDLER }
val imagePainter = remember(scope) { ImagePainter(scope, request, imageLoader) }
imagePainter.request = request
imagePainter.imageLoader = imageLoader
imagePainter.onExecute = onExecute
imagePainter.isPreview = LocalInspectionMode.current
updatePainter(imagePainter, request, imageLoader)
return imagePainter
}
/**
* A [Painter] that asynchronously executes [ImageRequest]s and draws the result.
* Instances can only be created with [rememberImagePainter].
*/
@Stable
class ImagePainter internal constructor(
private val parentScope: CoroutineScope,
request: ImageRequest,
imageLoader: ImageLoader
) : Painter(), RememberObserver {
private var rememberScope: CoroutineScope? = null
private var requestJob: Job? = null
private var drawSize: Size by mutableStateOf(Size.Zero)
private var alpha: Float by mutableStateOf(1f)
private var colorFilter: ColorFilter? by mutableStateOf(null)
internal var painter: Painter? by mutableStateOf(null)
internal var onExecute = ExecuteCallback.Lazy
internal var isPreview = false
/** The current [ImagePainter.State]. */
var state: State by mutableStateOf(State.Empty)
private set
/** The current [ImageRequest]. */
var request: ImageRequest by mutableStateOf(request)
internal set
/** The current [ImageLoader]. */
var imageLoader: ImageLoader by mutableStateOf(imageLoader)
internal set
override val intrinsicSize: Size
get() = painter?.intrinsicSize ?: Size.Unspecified
override fun DrawScope.onDraw() {
// Update the draw scope's current size.
drawSize = size
// Draw the current painter.
painter?.apply { draw(size, alpha, colorFilter) }
}
override fun applyAlpha(alpha: Float): Boolean {
this.alpha = alpha
return true
}
override fun applyColorFilter(colorFilter: ColorFilter?): Boolean {
this.colorFilter = colorFilter
return true
}
override fun onRemembered() {
if (isPreview) return
// Create a new scope to observe state and execute requests while we're remembered.
rememberScope?.cancel()
val context = parentScope.coroutineContext
val scope = CoroutineScope(context + SupervisorJob(context.job))
rememberScope = scope
// Observe the current request + request size and launch new requests as necessary.
scope.launch {
var snapshot: Snapshot? = null
combine(
snapshotFlow { request },
snapshotFlow { drawSize },
transform = ::Pair
).collect { (request, size) ->
val previous = snapshot
val current = Snapshot(state, request, size)
snapshot = current
// Launch a new image request if necessary.
if (onExecute(previous, current)) {
requestJob?.cancel()
requestJob = launch {
state = imageLoader
.execute(updateRequest(current.request, current.size))
.toState()
}
}
}
}
}
override fun onForgotten() {
rememberScope?.cancel()
rememberScope = null
requestJob?.cancel()
requestJob = null
}
override fun onAbandoned() = onForgotten()
/** Update the [request] to work with [ImagePainter]. */
private fun updateRequest(request: ImageRequest, size: Size): ImageRequest {
return request.newBuilder()
.target(
onStart = { placeholder ->
state = State.Loading(painter = placeholder?.toPainter())
}
)
.apply {
// Set the size unless it has been set explicitly.
if (request.defined.sizeResolver == null) {
if (size.isSpecified) {
val (width, height) = size
if (width >= 0.5f && height >= 0.5f) {
size(size.width.roundToInt(), size.height.roundToInt())
} else {
size(OriginalSize)
}
} else {
size(OriginalSize)
}
}
// Set the scale to fill unless it has been set explicitly.
// We do this since it's not possible to auto-detect the scale type like with `ImageView`s.
if (request.defined.scale == null) {
scale(Scale.FILL)
}
// Set inexact precision unless exact precision has been set explicitly.
if (request.defined.precision != Precision.EXACT) {
precision(Precision.INEXACT)
}
}
.build()
}
/**
* Invoked immediately before the [ImagePainter] executes a new image request.
* Return 'true' to proceed with the request. Return 'false' to skip executing the request.
*/
fun interface ExecuteCallback {
operator fun invoke(previous: Snapshot?, current: Snapshot): Boolean
companion object {
/**
* Proceeds with the request if the painter is empty or the request has changed.
*
* Additionally, this callback only proceeds if the image request has an explicit
* size or [ImagePainter.onDraw] has been called with the draw canvas' dimensions.
*/
@JvmField val Lazy = ExecuteCallback { previous, current ->
(current.state == State.Empty || previous?.request != current.request) &&
(current.request.defined.sizeResolver != null ||
current.size.isUnspecified ||
(current.size.width >= 0.5f && current.size.height >= 0.5f))
}
/**
* Proceeds with the request if the painter is empty or the request has changed.
*
* Unlike [Lazy], this callback will execute the request immediately. Typically,
* this will load the image at its original size unless [ImageRequest.Builder.size]
* has been set.
*/
@JvmField val Immediate = ExecuteCallback { previous, current ->
current.state == State.Empty || previous?.request != current.request
}
@Deprecated(
message = "Migrate to `Lazy`.",
replaceWith = ReplaceWith(
expression = "ExecuteCallback.Lazy",
imports = ["coil.compose.ImagePainter.ExecuteCallback"]
),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
@JvmField val Default = Lazy
}
}
/**
* A snapshot of the [ImagePainter]'s properties.
*/
@ExperimentalCoilApi
data class Snapshot(
val state: State,
val request: ImageRequest,
val size: Size,
)
/**
* The current state of the [ImagePainter].
*/
@ExperimentalCoilApi
sealed class State {
/** The current painter being drawn by [ImagePainter]. */
abstract val painter: Painter?
/** The request has not been started. */
object Empty : State() {
override val painter: Painter? get() = null
}
/** The request is in-progress. */
data class Loading(
override val painter: Painter?,
) : State()
/** The request was successful. */
data class Success(
override val painter: Painter,
val result: SuccessResult,
) : State()
/** The request failed due to [ErrorResult.throwable]. */
data class Error(
override val painter: Painter?,
val result: ErrorResult,
) : State()
}
}
/**
* Allows us to observe the current [ImagePainter.painter]. This function allows us to
* minimize the amount of recomposition needed such that this function only needs to be restarted
* when the [ImagePainter.state] changes.
*/
@Composable
private fun updatePainter(
imagePainter: ImagePainter,
request: ImageRequest,
imageLoader: ImageLoader
) {
// If we're in inspection mode (preview) and we have a placeholder, just draw
// that without executing an image request.
if (imagePainter.isPreview) {
imagePainter.painter = request.placeholder?.toPainter()
return
}
// This may look like a useless remember, but this allows any Painter instances
// to receive remember events (if it implements RememberObserver). Do not remove.
val state = imagePainter.state
val painter = remember(state) { state.painter }
// Short circuit if the crossfade transition isn't set.
// Check `imageLoader.defaults.transitionFactory` specifically as the default isn't set
// until the request is executed.
val transition = request.defined.transitionFactory ?: imageLoader.defaults.transitionFactory
if (transition !is CrossfadeTransition.Factory) {
imagePainter.painter = painter
return
}
// Keep track of the most recent loading painter to crossfade from it.
val loading = remember(request) { ValueHolder<Painter?>(null) }
if (state is State.Loading) loading.value = state.painter
// Short circuit if the request isn't successful or if it's returned by the memory cache.
if (state !is State.Success || state.result.dataSource == DataSource.MEMORY_CACHE) {
imagePainter.painter = painter
return
}
// Set the crossfade painter.
imagePainter.painter = rememberCrossfadePainter(
key = state,
start = loading.value,
end = painter,
scale = request.scale,
durationMillis = transition.durationMillis,
fadeStart = !state.result.isPlaceholderCached
)
}
private fun requireSupportedData(data: Any?) = when (data) {
is ImageBitmap -> unsupportedData("ImageBitmap")
is ImageVector -> unsupportedData("ImageVector")
is Painter -> unsupportedData("Painter")
else -> data
}
private fun unsupportedData(name: String): Nothing {
throw IllegalArgumentException(
"Unsupported type: $name. If you wish to display this $name, " +
"use androidx.compose.foundation.Image."
)
}
private fun ImageResult.toState() = when (this) {
is SuccessResult -> State.Success(
painter = drawable.toPainter(),
result = this
)
is ErrorResult -> State.Error(
painter = drawable?.toPainter(),
result = this
)
}
/** Convert this [Drawable] into a [Painter] using Compose primitives if possible. */
private fun Drawable.toPainter(): Painter {
return when (this) {
is BitmapDrawable -> BitmapPainter(bitmap.asImageBitmap())
is ColorDrawable -> ColorPainter(Color(color))
else -> DrawablePainter(mutate())
}
}
/** A simple mutable value holder that avoids recomposition. */
private class ValueHolder<T>(@JvmField var value: T)
/** An exception handler that ignores any uncaught exceptions. */
private val EMPTY_COROUTINE_EXCEPTION_HANDLER = CoroutineExceptionHandler { _, _ -> }
| 0 | null | 0 | 0 | 7d1cf331a6287b896882ab9a5aab1201c62f9773 | 15,389 | coil | Apache License 2.0 |
app/src/main/java/com/luuu/seven/module/news/ComicNewsFragment.kt | oteher | 288,484,684 | false | {"Kotlin": 223873} | package com.luuu.seven.module.news
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentTransaction
import com.luuu.seven.R
import com.luuu.seven.WebActivity
import com.luuu.seven.base.BaseFragment
import com.luuu.seven.bean.ComicNewsPicBean
import com.luuu.seven.util.BarUtils
import com.luuu.seven.util.GlideImageLoader
import com.luuu.seven.util.addTo
import com.luuu.seven.util.obtainViewModel
import kotlinx.android.synthetic.main.fra_news_layout.*
/**
* author : dell
* e-mail :
* time : 2017/08/01
* desc :
* version:资讯
*/
class ComicNewsFragment : BaseFragment() {
private lateinit var fm: FragmentManager
private var mNewsListFragment: ComicNewsListFragment? = null
private var mNewsFlashFragment: ComicNewsFlashFragment? = null
private lateinit var viewModel: NewsViewModel
override fun onFirstUserVisible() {
}
override fun onUserInvisible() {
}
override fun onUserVisible() {
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden) {
BarUtils.setTranslucentForCoordinatorLayout(activity!!, 0)
}
}
override fun initViews() {
BarUtils.setTranslucentForCoordinatorLayout(activity!!, 0)
viewModel = obtainViewModel().apply {
getComicNewsPic(false).addTo(mSubscription)
}.apply {
newsPicData.observe(viewLifecycleOwner, Observer { data ->
data?.let {
updateComicList(it)
}
})
}
fm = childFragmentManager
showFragment(0)
rg_group.setOnCheckedChangeListener { _, i ->
when (i) {
R.id.rb_news -> showFragment(0)
R.id.rb_flash -> showFragment(1)
}
}
appbar_layout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
if (verticalOffset == 0) {
news_banner.startAutoPlay()
} else {
news_banner.stopAutoPlay()
}
})
}
override fun getContentViewLayoutID(): Int = R.layout.fra_news_layout
override fun onFirstUserInvisible() {
}
private fun updateComicList(data: ComicNewsPicBean) {
val urls = ArrayList<String>()
data.data.mapTo(urls) { it.picUrl }
news_banner.setOnBannerListener { position ->
val mBundle = Bundle()
mBundle.putString("url", data.data[position].objectUrl)
startNewActivity(WebActivity::class.java, mBundle)
}
news_banner.setImages(urls).setImageLoader(GlideImageLoader()).start()
}
private fun showFragment(id: Int) {
val ft = fm.beginTransaction()
hideAllFragment(ft)
when (id) {
0 -> if (mNewsListFragment != null) {
ft.show(mNewsListFragment!!)
} else {
mNewsListFragment = ComicNewsListFragment()
ft.add(R.id.content, mNewsListFragment!!)
}
1 -> if (mNewsFlashFragment != null) {
ft.show(mNewsFlashFragment!!)
} else {
mNewsFlashFragment = ComicNewsFlashFragment()
ft.add(R.id.content, mNewsFlashFragment!!)
}
}
ft.commit()
}
private fun hideAllFragment(ft: FragmentTransaction) {
if (mNewsListFragment != null) ft.hide(mNewsListFragment!!)
if (mNewsFlashFragment != null) ft.hide(mNewsFlashFragment!!)
}
private fun obtainViewModel(): NewsViewModel = obtainViewModel(NewsViewModel::class.java)
} | 0 | null | 0 | 0 | 56d8fc35e2cd2281e9b96806f0d35d9e0c02f3e1 | 3,817 | Seven | MIT License |
app/app/src/main/java/com/example/genshin_wiki/repository/interfaces/IWeaponRepository.kt | SlavaPerryAyeKruchkovenko | 600,055,723 | false | null | package com.example.genshin_wiki.repository.interfaces
import com.example.genshin_wiki.data.converters.WeaponConverter
interface IWeaponRepository {
suspend fun getAllWeapons(): List<WeaponConverter>
suspend fun getWeaponById(id: String): WeaponConverter
suspend fun updateWeapon(weapon:WeaponConverter): WeaponConverter
suspend fun getLikedWeapons(): List<WeaponConverter>
suspend fun dislikeWeapons(): Boolean
} | 0 | Kotlin | 0 | 0 | bd98b658211d3a73f12c96a356af3ad95f18ddd4 | 435 | Genshin_Wiki | MIT License |
presentation/src/main/java/com/anytypeio/anytype/presentation/home/HomeScreenViewModel.kt | anyproto | 647,371,233 | false | null | package com.anytypeio.anytype.presentation.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.anytypeio.anytype.analytics.base.Analytics
import com.anytypeio.anytype.analytics.base.EventsDictionary
import com.anytypeio.anytype.core_models.Block
import com.anytypeio.anytype.core_models.Config
import com.anytypeio.anytype.core_models.DVFilter
import com.anytypeio.anytype.core_models.DVFilterCondition
import com.anytypeio.anytype.core_models.Event
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_models.ObjectType
import com.anytypeio.anytype.core_models.ObjectTypeUniqueKeys
import com.anytypeio.anytype.core_models.ObjectView
import com.anytypeio.anytype.core_models.ObjectWrapper
import com.anytypeio.anytype.core_models.Payload
import com.anytypeio.anytype.core_models.Position
import com.anytypeio.anytype.core_models.Relations
import com.anytypeio.anytype.core_models.WidgetLayout
import com.anytypeio.anytype.core_models.WidgetSession
import com.anytypeio.anytype.core_models.ext.process
import com.anytypeio.anytype.core_models.multiplayer.SpaceMemberPermissions
import com.anytypeio.anytype.core_models.primitives.SpaceId
import com.anytypeio.anytype.core_models.primitives.TypeKey
import com.anytypeio.anytype.core_utils.ext.cancel
import com.anytypeio.anytype.core_utils.ext.replace
import com.anytypeio.anytype.core_utils.ext.withLatestFrom
import com.anytypeio.anytype.domain.base.AppCoroutineDispatchers
import com.anytypeio.anytype.domain.base.Resultat
import com.anytypeio.anytype.domain.base.fold
import com.anytypeio.anytype.domain.bin.EmptyBin
import com.anytypeio.anytype.domain.block.interactor.Move
import com.anytypeio.anytype.domain.event.interactor.InterceptEvents
import com.anytypeio.anytype.domain.launch.GetDefaultObjectType
import com.anytypeio.anytype.domain.library.StoreSearchByIdsParams
import com.anytypeio.anytype.domain.library.StorelessSubscriptionContainer
import com.anytypeio.anytype.domain.misc.AppActionManager
import com.anytypeio.anytype.domain.misc.DeepLinkResolver
import com.anytypeio.anytype.domain.misc.Reducer
import com.anytypeio.anytype.domain.misc.UrlBuilder
import com.anytypeio.anytype.domain.multiplayer.UserPermissionProvider
import com.anytypeio.anytype.domain.`object`.GetObject
import com.anytypeio.anytype.domain.`object`.OpenObject
import com.anytypeio.anytype.domain.`object`.SetObjectDetails
import com.anytypeio.anytype.domain.objects.ObjectWatcher
import com.anytypeio.anytype.domain.objects.StoreOfObjectTypes
import com.anytypeio.anytype.domain.page.CloseBlock
import com.anytypeio.anytype.domain.page.CreateObject
import com.anytypeio.anytype.domain.search.SearchObjects
import com.anytypeio.anytype.domain.spaces.GetSpaceView
import com.anytypeio.anytype.domain.types.GetPinnedObjectTypes
import com.anytypeio.anytype.domain.widgets.CreateWidget
import com.anytypeio.anytype.domain.widgets.DeleteWidget
import com.anytypeio.anytype.domain.widgets.GetWidgetSession
import com.anytypeio.anytype.domain.widgets.SaveWidgetSession
import com.anytypeio.anytype.domain.widgets.SetWidgetActiveView
import com.anytypeio.anytype.domain.widgets.UpdateWidget
import com.anytypeio.anytype.domain.workspace.SpaceManager
import com.anytypeio.anytype.presentation.BuildConfig
import com.anytypeio.anytype.presentation.extension.sendAddWidgetEvent
import com.anytypeio.anytype.presentation.extension.sendAnalyticsObjectCreateEvent
import com.anytypeio.anytype.presentation.extension.sendAnalyticsObjectTypeSelectOrChangeEvent
import com.anytypeio.anytype.presentation.extension.sendDeleteWidgetEvent
import com.anytypeio.anytype.presentation.extension.sendEditWidgetsEvent
import com.anytypeio.anytype.presentation.extension.sendReorderWidgetEvent
import com.anytypeio.anytype.presentation.extension.sendSelectHomeTabEvent
import com.anytypeio.anytype.presentation.home.Command.ChangeWidgetType.Companion.UNDEFINED_LAYOUT_CODE
import com.anytypeio.anytype.presentation.navigation.DeepLinkToObjectDelegate
import com.anytypeio.anytype.presentation.navigation.NavigationViewModel
import com.anytypeio.anytype.presentation.objects.SupportedLayouts
import com.anytypeio.anytype.presentation.objects.getCreateObjectParams
import com.anytypeio.anytype.presentation.profile.ProfileIconView
import com.anytypeio.anytype.presentation.profile.profileIcon
import com.anytypeio.anytype.presentation.search.Subscriptions
import com.anytypeio.anytype.presentation.spaces.SpaceGradientProvider
import com.anytypeio.anytype.presentation.util.Dispatcher
import com.anytypeio.anytype.presentation.widgets.BundledWidgetSourceIds
import com.anytypeio.anytype.presentation.widgets.CollapsedWidgetStateHolder
import com.anytypeio.anytype.presentation.widgets.DataViewListWidgetContainer
import com.anytypeio.anytype.presentation.widgets.DropDownMenuAction
import com.anytypeio.anytype.presentation.widgets.LinkWidgetContainer
import com.anytypeio.anytype.presentation.widgets.ListWidgetContainer
import com.anytypeio.anytype.presentation.widgets.SpaceWidgetContainer
import com.anytypeio.anytype.presentation.widgets.TreePath
import com.anytypeio.anytype.presentation.widgets.TreeWidgetBranchStateHolder
import com.anytypeio.anytype.presentation.widgets.TreeWidgetContainer
import com.anytypeio.anytype.presentation.widgets.Widget
import com.anytypeio.anytype.presentation.widgets.WidgetActiveViewStateHolder
import com.anytypeio.anytype.presentation.widgets.WidgetContainer
import com.anytypeio.anytype.presentation.widgets.WidgetDispatchEvent
import com.anytypeio.anytype.presentation.widgets.WidgetSessionStateHolder
import com.anytypeio.anytype.presentation.widgets.WidgetView
import com.anytypeio.anytype.presentation.widgets.collection.Subscription
import com.anytypeio.anytype.presentation.widgets.parseActiveViews
import com.anytypeio.anytype.presentation.widgets.parseWidgets
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import timber.log.Timber
/**
* TODO
* Corner cases to handle:
* close object object session if it was opened by one of widgets containers and not used by another.
* - if it was deleted
* - when leaving this screen
*
* Change subscription IDs for bundled widgets?
*/
class HomeScreenViewModel(
private val openObject: OpenObject,
private val closeObject: CloseBlock,
private val createWidget: CreateWidget,
private val deleteWidget: DeleteWidget,
private val updateWidget: UpdateWidget,
private val storelessSubscriptionContainer: StorelessSubscriptionContainer,
private val getObject: GetObject,
private val appCoroutineDispatchers: AppCoroutineDispatchers,
private val widgetEventDispatcher: Dispatcher<WidgetDispatchEvent>,
private val objectPayloadDispatcher: Dispatcher<Payload>,
private val interceptEvents: InterceptEvents,
private val widgetSessionStateHolder: WidgetSessionStateHolder,
private val widgetActiveViewStateHolder: WidgetActiveViewStateHolder,
private val collapsedWidgetStateHolder: CollapsedWidgetStateHolder,
private val urlBuilder: UrlBuilder,
private val createObject: CreateObject,
private val move: Move,
private val emptyBin: EmptyBin,
private val unsubscriber: Unsubscriber,
private val getDefaultObjectType: GetDefaultObjectType,
private val appActionManager: AppActionManager,
private val analytics: Analytics,
private val getWidgetSession: GetWidgetSession,
private val saveWidgetSession: SaveWidgetSession,
private val spaceGradientProvider: SpaceGradientProvider,
private val storeOfObjectTypes: StoreOfObjectTypes,
private val objectWatcher: ObjectWatcher,
private val spaceManager: SpaceManager,
private val spaceWidgetContainer: SpaceWidgetContainer,
private val setWidgetActiveView: SetWidgetActiveView,
private val setObjectDetails: SetObjectDetails,
private val getSpaceView: GetSpaceView,
private val searchObjects: SearchObjects,
private val getPinnedObjectTypes: GetPinnedObjectTypes,
private val userPermissionProvider: UserPermissionProvider,
private val deepLinkToObjectDelegate: DeepLinkToObjectDelegate
) : NavigationViewModel<HomeScreenViewModel.Navigation>(),
Reducer<ObjectView, Payload>,
WidgetActiveViewStateHolder by widgetActiveViewStateHolder,
WidgetSessionStateHolder by widgetSessionStateHolder,
CollapsedWidgetStateHolder by collapsedWidgetStateHolder,
DeepLinkToObjectDelegate by deepLinkToObjectDelegate,
Unsubscriber by unsubscriber {
private val jobs = mutableListOf<Job>()
private val mutex = Mutex()
val views = MutableStateFlow<List<WidgetView>>(emptyList())
val commands = MutableSharedFlow<Command>()
val mode = MutableStateFlow<InteractionMode>(InteractionMode.Default)
private var isWidgetSessionRestored = false
private val isEmptyingBinInProgress = MutableStateFlow(false)
private val objectViewState = MutableStateFlow<ObjectViewState>(ObjectViewState.Idle)
private val widgets = MutableStateFlow<Widgets>(null)
private val containers = MutableStateFlow<Containers>(null)
private val treeWidgetBranchStateHolder = TreeWidgetBranchStateHolder()
// Bundled widget containing archived objects
private val bin = WidgetView.Bin(Subscriptions.SUBSCRIPTION_ARCHIVED)
private val spaceWidgetView = spaceWidgetContainer.view
val icon = MutableStateFlow<ProfileIconView>(ProfileIconView.Loading)
private val widgetObjectPipelineJobs = mutableListOf<Job>()
private val openWidgetObjectsHistory : MutableSet<Id> = LinkedHashSet()
private val userPermissions = MutableStateFlow<SpaceMemberPermissions?>(null)
val hasEditAccess = userPermissions.map { it?.isOwnerOrEditor() == true }
private val widgetObjectPipeline = spaceManager
.observe()
.onEach { currentConfig ->
// Closing previously opened widget object when switching spaces without leaving home screen
proceedWithClearingObjectSessionHistory(currentConfig)
}
.flatMapLatest { config ->
openObject.stream(
OpenObject.Params(
obj = config.widgets,
saveAsLastOpened = false,
spaceId = SpaceId(config.space)
)
)
}
.onEach { result ->
result.fold(
onSuccess = { objectView ->
onSessionStarted().also {
mutex.withLock { openWidgetObjectsHistory.add(objectView.root) }
}
},
onFailure = { e ->
onSessionFailed().also {
Timber.e(e, "Error while opening object.")
}
}
)
}
.map { result ->
when (result) {
is Resultat.Failure -> ObjectViewState.Failure(result.exception)
is Resultat.Loading -> ObjectViewState.Loading
is Resultat.Success -> ObjectViewState.Success(obj = result.value)
}
}
init {
proceedWithUserPermissions()
proceedWithObservingProfileIcon()
proceedWithLaunchingUnsubscriber()
proceedWithObjectViewStatePipeline()
proceedWithWidgetContainerPipeline()
proceedWithRenderingPipeline()
proceedWithObservingDispatches()
proceedWithSettingUpShortcuts()
}
private fun proceedWithUserPermissions() {
viewModelScope.launch {
spaceManager
.observe()
.flatMapLatest { config ->
userPermissionProvider.observe(SpaceId(config.space))
}.collect { permission ->
userPermissions.value = permission
when(permission) {
SpaceMemberPermissions.WRITER,
SpaceMemberPermissions.OWNER -> {
if (mode.value == InteractionMode.ReadOnly) {
mode.value = InteractionMode.Default
}
}
else -> {
mode.value = InteractionMode.ReadOnly
}
}
}
}
}
private suspend fun proceedWithClearingObjectSessionHistory(currentConfig: Config) {
mutex.withLock {
val closed = mutableSetOf<Id>()
openWidgetObjectsHistory.forEach { previouslyOpenedWidgetObject ->
if (previouslyOpenedWidgetObject != currentConfig.widgets) {
closeObject
.async(params = previouslyOpenedWidgetObject)
.fold(
onSuccess = { closed.add(previouslyOpenedWidgetObject) },
onFailure = {
Timber.e(it, "Error while closing object from history: $previouslyOpenedWidgetObject")
}
)
}
}
if (closed.isNotEmpty()) {
openWidgetObjectsHistory.removeAll(closed)
}
}
}
private fun proceedWithLaunchingUnsubscriber() {
viewModelScope.launch { unsubscriber.start() }
}
private fun proceedWithRenderingPipeline() {
viewModelScope.launch {
containers.filterNotNull().flatMapLatest { list ->
if (list.isNotEmpty()) {
combine(
flows = buildList<Flow<WidgetView>> {
add(spaceWidgetView)
addAll(list.map { m -> m.view })
}
) { array ->
array.toList()
}
} else {
spaceWidgetView.map { view -> listOf(view) }
}
}.combine(hasEditAccess) { widgets, hasEditAccess ->
if (hasEditAccess) {
widgets + listOf(WidgetView.Library, bin) + actions
} else {
widgets
}
}.flowOn(appCoroutineDispatchers.io).collect {
views.value = it
}
}
}
private fun proceedWithWidgetContainerPipeline() {
viewModelScope.launch {
combine(
spaceManager.observe(),
widgets.filterNotNull()
) { config, widgets ->
widgets.map { widget ->
// TODO caching logic for containers could be implemented here.
when (widget) {
is Widget.Link -> LinkWidgetContainer(
widget = widget
)
is Widget.Tree -> TreeWidgetContainer(
widget = widget,
container = storelessSubscriptionContainer,
expandedBranches = treeWidgetBranchStateHolder.stream(widget.id),
isWidgetCollapsed = isCollapsed(widget.id),
isSessionActive = isSessionActive,
urlBuilder = urlBuilder,
space = config.space,
config = config,
objectWatcher = objectWatcher,
spaceGradientProvider = spaceGradientProvider,
getSpaceView = getSpaceView
)
is Widget.List -> if (BundledWidgetSourceIds.ids.contains(widget.source.id)) {
ListWidgetContainer(
widget = widget,
subscription = widget.source.id,
space = config.space,
storage = storelessSubscriptionContainer,
isWidgetCollapsed = isCollapsed(widget.id),
urlBuilder = urlBuilder,
spaceGradientProvider = spaceGradientProvider,
isSessionActive = isSessionActive,
objectWatcher = objectWatcher,
config = config,
getSpaceView = getSpaceView
)
} else {
DataViewListWidgetContainer(
widget = widget,
config = config,
storage = storelessSubscriptionContainer,
getObject = getObject,
activeView = observeCurrentWidgetView(widget.id),
isWidgetCollapsed = isCollapsed(widget.id),
isSessionActive = isSessionActive,
urlBuilder = urlBuilder,
gradientProvider = spaceGradientProvider
)
}
}
}
}.collect {
Timber.d("Emitting list of containers: ${it.size}")
containers.value = it
}
}
}
private fun proceedWithObjectViewStatePipeline() {
val externalChannelEvents = spaceManager.observe().flatMapLatest { config ->
interceptEvents.build(
InterceptEvents.Params(config.widgets)
).map { events ->
Payload(
context = config.widgets,
events = events
)
}
}
val internalChannelEvents = objectPayloadDispatcher.flow()
val payloads = merge(externalChannelEvents, internalChannelEvents)
viewModelScope.launch {
objectViewState.flatMapLatest { state ->
when (state) {
is ObjectViewState.Idle -> flowOf(state)
is ObjectViewState.Failure -> flowOf(state)
is ObjectViewState.Loading -> flowOf(state)
is ObjectViewState.Success -> {
payloads.scan(state) { s, p -> s.copy(obj = reduce(s.obj, p)) }
}
}
}.filterIsInstance<ObjectViewState.Success>().map { state ->
state.obj.blocks.parseWidgets(
root = state.obj.root,
details = state.obj.details
).also {
widgetActiveViewStateHolder.init(state.obj.blocks.parseActiveViews())
}
}.collect {
Timber.d("Emitting list of widgets: ${it.size}")
widgets.value = it
}
}
}
private fun proceedWithObservingProfileIcon() {
viewModelScope.launch {
spaceManager
.observe()
.flatMapLatest { config ->
storelessSubscriptionContainer.subscribe(
StoreSearchByIdsParams(
subscription = HOME_SCREEN_PROFILE_OBJECT_SUBSCRIPTION,
targets = listOf(config.profile),
keys = listOf(
Relations.ID,
Relations.NAME,
Relations.ICON_EMOJI,
Relations.ICON_IMAGE,
Relations.ICON_OPTION
)
)
).map { result ->
val obj = result.firstOrNull()
obj?.profileIcon(urlBuilder) ?: ProfileIconView.Placeholder(null)
}
}
.catch { Timber.e(it, "Error while observing space icon") }
.flowOn(appCoroutineDispatchers.io)
.collect { icon.value = it }
}
}
private suspend fun proceedWithClosingWidgetObject(widgetObject: Id) {
saveWidgetSession.async(
SaveWidgetSession.Params(
WidgetSession(
collapsed = collapsedWidgetStateHolder.get(),
widgetsToActiveViews = emptyMap()
)
)
)
val subscriptions = buildList {
addAll(
widgets.value.orEmpty().map { widget ->
if (widget.source is Widget.Source.Bundled)
widget.source.id
else
widget.id
}
)
add(SpaceWidgetContainer.SPACE_WIDGET_SUBSCRIPTION)
}
if (subscriptions.isNotEmpty()) unsubscribe(subscriptions)
closeObject.stream(widgetObject).collect { status ->
status.fold(
onFailure = {
Timber.e(it, "Error while closing widget object")
},
onSuccess = {
onSessionStopped().also {
Timber.d("Widget object closed successfully")
}
}
)
}
}
private fun proceedWithObservingDispatches() {
viewModelScope.launch {
widgetEventDispatcher
.flow()
.withLatestFrom(spaceManager.observe()) { dispatch, config ->
when (dispatch) {
is WidgetDispatchEvent.SourcePicked.Default -> {
commands.emit(
Command.SelectWidgetType(
ctx = config.widgets,
source = dispatch.source,
layout = dispatch.sourceLayout,
target = dispatch.target,
isInEditMode = isInEditMode()
)
)
}
is WidgetDispatchEvent.SourcePicked.Bundled -> {
commands.emit(
Command.SelectWidgetType(
ctx = config.widgets,
source = dispatch.source,
layout = ObjectType.Layout.SET.code,
target = dispatch.target,
isInEditMode = isInEditMode()
)
)
}
is WidgetDispatchEvent.SourceChanged -> {
proceedWithUpdatingWidget(
ctx = config.widgets,
widget = dispatch.widget,
source = dispatch.source,
type = dispatch.type
)
}
is WidgetDispatchEvent.TypePicked -> {
proceedWithCreatingWidget(
ctx = config.widgets,
source = dispatch.source,
type = dispatch.widgetType,
target = dispatch.target
)
}
}
}.collect()
}
}
private fun proceedWithCreatingWidget(
ctx: Id,
source: Id,
type: Int,
target: Id?
) {
viewModelScope.launch {
createWidget(
CreateWidget.Params(
ctx = ctx,
source = source,
type = when (type) {
Command.ChangeWidgetType.TYPE_LINK -> WidgetLayout.LINK
Command.ChangeWidgetType.TYPE_TREE -> WidgetLayout.TREE
Command.ChangeWidgetType.TYPE_LIST -> WidgetLayout.LIST
Command.ChangeWidgetType.TYPE_COMPACT_LIST -> WidgetLayout.COMPACT_LIST
else -> WidgetLayout.LINK
},
target = target,
position = if (!target.isNullOrEmpty()) Position.BOTTOM else Position.NONE
)
).flowOn(appCoroutineDispatchers.io).collect { status ->
Timber.d("Status while creating widget: $status")
when (status) {
is Resultat.Failure -> {
sendToast("Error while creating widget: ${status.exception}")
Timber.e(status.exception, "Error while creating widget")
}
is Resultat.Loading -> {
// Do nothing?
}
is Resultat.Success -> {
objectPayloadDispatcher.send(status.value)
}
}
}
}
}
/**
* @param [type] type code from [Command.ChangeWidgetType]
*/
private fun proceedWithUpdatingWidget(
ctx: Id,
widget: Id,
source: Id,
type: Int
) {
viewModelScope.launch {
updateWidget(
UpdateWidget.Params(
ctx = ctx,
source = source,
widget = widget,
type = when (type) {
Command.ChangeWidgetType.TYPE_LINK -> WidgetLayout.LINK
Command.ChangeWidgetType.TYPE_TREE -> WidgetLayout.TREE
Command.ChangeWidgetType.TYPE_LIST -> WidgetLayout.LIST
Command.ChangeWidgetType.TYPE_COMPACT_LIST -> WidgetLayout.COMPACT_LIST
else -> throw IllegalStateException("Unexpected type: $type")
}
)
).flowOn(appCoroutineDispatchers.io).collect { status ->
Timber.d("Status while creating widget: $status")
when (status) {
is Resultat.Failure -> {
sendToast("Error while creating widget: ${status.exception}")
Timber.e(status.exception, "Error while creating widget")
}
is Resultat.Loading -> {
// Do nothing?
}
is Resultat.Success -> {
launch {
objectPayloadDispatcher.send(status.value)
}
}
}
}
}
}
private fun proceedWithDeletingWidget(widget: Id) {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null) {
val target = widgets.value.orEmpty().find { it.id == widget }
deleteWidget.stream(
DeleteWidget.Params(
ctx = config.widgets,
targets = listOf(widget)
)
).flowOn(appCoroutineDispatchers.io).collect { status ->
Timber.d("Status while deleting widget: $status")
when (status) {
is Resultat.Failure -> {
sendToast("Error while deleting widget: ${status.exception}")
Timber.e(status.exception, "Error while deleting widget")
}
is Resultat.Loading -> {
// Do nothing?
}
is Resultat.Success -> {
objectPayloadDispatcher.send(status.value).also {
dispatchDeleteWidgetAnalyticsEvent(target)
}
}
}
}
} else {
Timber.e("Failed to get config to delete a widget")
}
}
}
private fun proceedWithEmptyingBin() {
viewModelScope.launch {
emptyBin.stream(Unit).flowOn(appCoroutineDispatchers.io).collect { status ->
Timber.d("Status while emptying bin: $status")
when (status) {
is Resultat.Failure -> {
Timber.e(status.exception, "Error while emptying bin").also {
isEmptyingBinInProgress.value = false
}
}
is Resultat.Loading -> {
isEmptyingBinInProgress.value = true
}
is Resultat.Success -> {
when (status.value.size) {
0 -> sendToast("Bin already empty")
1 -> sendToast("One object deleted")
else -> "${status.value.size} objects deleted"
}
isEmptyingBinInProgress.value = false
}
}
}
}
}
fun onCreateWidgetClicked() {
viewModelScope.launch {
sendAddWidgetEvent(
analytics = analytics,
isInEditMode = isInEditMode()
)
commands.emit(
Command.SelectWidgetSource(
isInEditMode = isInEditMode()
)
)
}
}
fun onEditWidgets() {
viewModelScope.launch {
if (userPermissions.value?.isOwnerOrEditor() == true) {
proceedWithEnteringEditMode()
sendEditWidgetsEvent(analytics)
}
}
}
fun onExitEditMode() {
proceedWithExitingEditMode()
}
fun onExpand(path: TreePath) {
treeWidgetBranchStateHolder.onExpand(linkPath = path)
}
fun onWidgetObjectClicked(obj: ObjectWrapper.Basic) {
Timber.d("With id: ${obj.id}")
if (obj.isArchived != true) {
proceedWithOpeningObject(obj)
} else {
sendToast("Open bin to restore your archived object")
}
}
fun onObjectCheckboxClicked(id: Id, isChecked: Boolean) {
proceedWithTogglingObjectCheckboxState(id = id, isChecked = isChecked)
}
private fun proceedWithTogglingObjectCheckboxState(id: Id, isChecked: Boolean) {
viewModelScope.launch {
setObjectDetails.async(
SetObjectDetails.Params(
ctx = id,
details = mapOf(
Relations.DONE to !isChecked
)
)
).fold(
onSuccess = {
Timber.d("Updated checkbox state")
},
onFailure = {
Timber.e(it, "Error while toggling object checkbox state")
}
)
}
}
fun onWidgetSourceClicked(source: Widget.Source) {
when (source) {
is Widget.Source.Bundled.Favorites -> {
viewModelScope.sendSelectHomeTabEvent(
analytics = analytics,
bundled = source
)
// TODO switch to bundled widgets id
viewModelScope.launch {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Favorites,
space = spaceManager.get()
)
)
}
}
is Widget.Source.Bundled.Sets -> {
viewModelScope.sendSelectHomeTabEvent(
analytics = analytics,
bundled = source
)
// TODO switch to bundled widgets id
viewModelScope.launch {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Sets,
space = spaceManager.get()
)
)
}
}
is Widget.Source.Bundled.Recent -> {
viewModelScope.sendSelectHomeTabEvent(
analytics = analytics,
bundled = source
)
// TODO switch to bundled widgets id
viewModelScope.launch {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Recent,
space = spaceManager.get()
)
)
}
}
is Widget.Source.Bundled.RecentLocal -> {
viewModelScope.sendSelectHomeTabEvent(
analytics = analytics,
bundled = source
)
// TODO switch to bundled widgets id
viewModelScope.launch {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.RecentLocal,
space = spaceManager.get()
)
)
}
}
is Widget.Source.Bundled.Collections -> {
viewModelScope.sendSelectHomeTabEvent(
analytics = analytics,
bundled = source
)
// TODO switch to bundled widgets id
viewModelScope.launch {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Collections,
space = spaceManager.get()
)
)
}
}
is Widget.Source.Default -> {
if (source.obj.isArchived != true) {
dispatchSelectHomeTabCustomSourceEvent(source)
proceedWithOpeningObject(source.obj)
} else {
sendToast("Open bin to restore your archived object")
}
}
}
}
fun onDropDownMenuAction(widget: Id, action: DropDownMenuAction) {
when (action) {
DropDownMenuAction.ChangeWidgetSource -> {
proceedWithChangingSource(widget)
}
DropDownMenuAction.ChangeWidgetType -> {
proceedWithChangingType(widget)
}
DropDownMenuAction.EditWidgets -> {
proceedWithEnteringEditMode()
}
DropDownMenuAction.RemoveWidget -> {
proceedWithDeletingWidget(widget)
}
DropDownMenuAction.EmptyBin -> {
proceedWithEmptyingBin()
}
DropDownMenuAction.AddBelow -> {
proceedWithAddingWidgetBelow(widget)
}
}
}
fun onBundledWidgetClicked(widget: Id) {
viewModelScope.launch {
// TODO DROID-2341 get space from widget views for better consistency
val space = spaceManager.get()
when (widget) {
Subscriptions.SUBSCRIPTION_SETS -> {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Sets,
space = space
)
)
}
Subscriptions.SUBSCRIPTION_RECENT -> {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Recent,
space = space
)
)
}
Subscriptions.SUBSCRIPTION_ARCHIVED -> {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Bin,
space = space
)
)
}
Subscriptions.SUBSCRIPTION_FAVORITES -> {
navigation(
Navigation.ExpandWidget(
subscription = Subscription.Favorites,
space = space
)
)
}
}
}
}
private fun proceedWithAddingWidgetBelow(widget: Id) {
viewModelScope.launch {
sendAddWidgetEvent(
analytics = analytics,
isInEditMode = isInEditMode()
)
commands.emit(
Command.SelectWidgetSource(
target = widget,
isInEditMode = isInEditMode()
)
)
}
}
private fun proceedWithChangingType(widget: Id) {
Timber.d("onChangeWidgetSourceClicked, widget:[$widget]")
val curr = widgets.value.orEmpty().find { it.id == widget }
if (curr != null) {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null) {
commands.emit(
Command.ChangeWidgetType(
ctx = config.widgets,
widget = widget,
source = curr.source.id,
type = parseWidgetType(curr),
layout = when (val source = curr.source) {
is Widget.Source.Bundled -> UNDEFINED_LAYOUT_CODE
is Widget.Source.Default -> {
source.obj.layout?.code ?: UNDEFINED_LAYOUT_CODE
}
},
isInEditMode = isInEditMode()
)
)
} else {
Timber.e("Failed to get config to change widget type")
}
}
} else {
sendToast("Widget missing. Please try again later")
}
}
private fun proceedWithChangingSource(widget: Id) {
val curr = widgets.value.orEmpty().find { it.id == widget }
if (curr != null) {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null) {
commands.emit(
Command.ChangeWidgetSource(
ctx = config.widgets,
widget = widget,
source = curr.source.id,
type = parseWidgetType(curr),
isInEditMode = isInEditMode()
)
)
} else {
Timber.e("Failed to get config to change widget source")
}
}
} else {
sendToast("Widget missing. Please try again later")
}
}
private fun parseWidgetType(curr: Widget) = when (curr) {
is Widget.Link -> Command.ChangeWidgetType.TYPE_LINK
is Widget.Tree -> Command.ChangeWidgetType.TYPE_TREE
is Widget.List -> {
if (curr.isCompact)
Command.ChangeWidgetType.TYPE_COMPACT_LIST
else
Command.ChangeWidgetType.TYPE_LIST
}
}
// TODO move to a separate reducer inject into this VM's constructor
override fun reduce(state: ObjectView, event: Payload): ObjectView {
var curr = state
event.events.forEach { e ->
when (e) {
is Event.Command.AddBlock -> {
curr = curr.copy(blocks = curr.blocks + e.blocks)
}
is Event.Command.DeleteBlock -> {
interceptWidgetDeletion(e)
curr = curr.copy(
blocks = curr.blocks.filter { !e.targets.contains(it.id) }
)
}
is Event.Command.UpdateStructure -> {
curr = curr.copy(
blocks = curr.blocks.replace(
replacement = { target ->
target.copy(children = e.children)
},
target = { block -> block.id == e.id }
)
)
}
is Event.Command.Details -> {
curr = curr.copy(details = curr.details.process(e))
}
is Event.Command.LinkGranularChange -> {
curr = curr.copy(
blocks = curr.blocks.map { block ->
if (block.id == e.id) {
val content = block.content
if (content is Block.Content.Link) {
block.copy(
content = content.copy(
target = e.target
)
)
} else {
block
}
} else {
block
}
}
)
}
is Event.Command.Widgets.SetWidget -> {
Timber.d("Set widget event: $e")
curr = curr.copy(
blocks = curr.blocks.map { block ->
if (block.id == e.widget) {
val content = block.content
if (content is Block.Content.Widget) {
block.copy(
content = content.copy(
layout = e.layout ?: content.layout,
limit = e.limit ?: content.limit,
activeView = e.activeView ?: content.activeView
)
)
} else {
block
}
} else {
block
}
}
)
}
else -> {
Timber.d("Skipping event: $e")
}
}
}
return curr
}
private fun interceptWidgetDeletion(
e: Event.Command.DeleteBlock
) {
val currentWidgets = widgets.value ?: emptyList()
val deletedWidgets = currentWidgets.filter { widget ->
e.targets.contains(widget.id)
}
val expiredSubscriptions = deletedWidgets.map { widget ->
if (widget.source is Widget.Source.Bundled)
widget.source.id
else
widget.id
}
if (deletedWidgets.isNotEmpty()) {
viewModelScope.launch {
collapsedWidgetStateHolder.onWidgetDeleted(
widgets = deletedWidgets.map { it.id }
)
unsubscriber.unsubscribe(expiredSubscriptions)
}
}
}
fun onStart() {
Timber.d("onStart")
widgetObjectPipelineJobs += viewModelScope.launch {
if (!isWidgetSessionRestored) {
val session = withContext(appCoroutineDispatchers.io) {
getWidgetSession.async(Unit).getOrNull()
}
if (session != null) {
collapsedWidgetStateHolder.set(session.collapsed)
}
}
widgetObjectPipeline.collect {
objectViewState.value = it
}
}
}
fun onResume(deeplink: DeepLinkResolver.Action? = null) {
Timber.d("onResume, deeplink: ${deeplink}")
when (deeplink) {
is DeepLinkResolver.Action.Import.Experience -> {
viewModelScope.launch {
commands.emit(
Command.Deeplink.GalleryInstallation(
deepLinkType = deeplink.type,
deepLinkSource = deeplink.source
)
)
}
}
is DeepLinkResolver.Action.Invite -> {
viewModelScope.launch {
delay(1000)
commands.emit(Command.Deeplink.Invite(deeplink.link))
}
}
is DeepLinkResolver.Action.Unknown -> {
if (BuildConfig.DEBUG) {
sendToast("Could not resolve deeplink")
}
}
is DeepLinkResolver.Action.DeepLinkToObject -> {
viewModelScope.launch {
val result = onDeepLinkToObject(
obj = deeplink.obj,
space = deeplink.space,
switchSpaceIfObjectFound = true
)
when(result) {
is DeepLinkToObjectDelegate.Result.Error -> {
commands.emit(Command.Deeplink.DeepLinkToObjectNotWorking)
}
is DeepLinkToObjectDelegate.Result.Success -> {
proceedWithNavigation(result.obj.navigation())
}
}
}
}
else -> {
Timber.d("No deep link")
}
}
}
fun onStop() {
Timber.d("onStop")
// Temporary workaround for app crash when user is logged out and config storage is not initialized.
try {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null) {
proceedWithClosingWidgetObject(widgetObject = config.widgets)
}
}
} catch (e: Exception) {
Timber.e(e, "Error while closing widget object")
}
jobs.cancel()
}
private fun proceedWithExitingEditMode() {
mode.value = InteractionMode.Default
}
private fun proceedWithEnteringEditMode() {
mode.value = InteractionMode.Edit
}
private fun proceedWithOpeningObject(obj: ObjectWrapper.Basic) {
proceedWithNavigation(obj.navigation())
}
private fun proceedWithNavigation(navigation: OpenObjectNavigation) {
when(navigation) {
is OpenObjectNavigation.OpenDataView -> {
navigate(
Navigation.OpenSet(
ctx = navigation.target,
space = navigation.space
)
)
}
is OpenObjectNavigation.OpenEditor -> {
navigate(
Navigation.OpenObject(
ctx = navigation.target,
space = navigation.space
)
)
}
is OpenObjectNavigation.UnexpectedLayoutError -> {
sendToast("Unexpected layout: ${navigation.layout}")
}
}
}
fun onCreateNewObjectClicked(objType: ObjectWrapper.Type? = null) {
Timber.d("onCreateNewObjectClicked, type:[${objType?.uniqueKey}]")
val startTime = System.currentTimeMillis()
viewModelScope.launch {
val params = objType?.uniqueKey.getCreateObjectParams(objType?.defaultTemplateId)
createObject.stream(params).collect { createObjectResponse ->
createObjectResponse.fold(
onSuccess = { result ->
sendAnalyticsObjectCreateEvent(
analytics = analytics,
route = EventsDictionary.Routes.navigation,
startTime = startTime,
view = EventsDictionary.View.viewHome,
objType = objType ?: storeOfObjectTypes.getByKey(result.typeKey.key),
)
if (objType != null) {
sendAnalyticsObjectTypeSelectOrChangeEvent(
analytics = analytics,
startTime = startTime,
sourceObject = objType.sourceObject,
containsFlagType = true,
route = EventsDictionary.Routes.longTap
)
}
proceedWithOpeningObject(result.obj)
},
onFailure = {
Timber.e(it, "Error while creating object")
sendToast("Error while creating object. Please, try again later")
}
)
}
}
}
fun onCreateNewObjectLongClicked() {
viewModelScope.launch {
val space = spaceManager.get()
if (space.isNotEmpty()) {
commands.emit(Command.OpenObjectCreateDialog(SpaceId(space)))
}
}
}
fun onMove(views: List<WidgetView>, from: Int, to: Int) {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null) {
val direction = if (from < to) Position.BOTTOM else Position.TOP
val subject = views[to]
val target = if (direction == Position.TOP) views[to.inc()].id else views[to.dec()].id
move.stream(
Move.Params(
context = config.widgets,
targetId = target,
targetContext = config.widgets,
blockIds = listOf(subject.id),
position = direction
)
).collect { result ->
result.fold(
onSuccess = {
objectPayloadDispatcher.send(it).also {
dispatchReorderWidgetAnalyticEvent(subject)
}
},
onFailure = { Timber.e(it, "Error while moving blocks") }
)
}
}
else
Timber.e("Failed to get config for move operation")
}
}
private fun proceedWithSettingUpShortcuts() {
spaceManager
.observe()
.flatMapLatest { config ->
getPinnedObjectTypes.flow(
GetPinnedObjectTypes.Params(space = SpaceId(config.space))
).map { pinned ->
config to pinned
}
}
.onEach { (config, pinned) ->
val defaultObjectType = getDefaultObjectType.async(Unit).getOrNull()?.type
val keys = buildSet {
pinned.take(MAX_PINNED_TYPE_COUNT_FOR_APP_ACTIONS).forEach { typeId ->
val wrapper = storeOfObjectTypes.get(typeId.id)
val uniqueKey = wrapper?.uniqueKey
if (uniqueKey != null) {
add(wrapper.uniqueKey)
} else {
Timber.w("Could not found unique key for a pinned type: ${typeId.id}")
}
}
if (defaultObjectType != null && size < MAX_TYPE_COUNT_FOR_APP_ACTIONS && !contains(defaultObjectType.key)) {
add(defaultObjectType.key)
}
if (size < MAX_TYPE_COUNT_FOR_APP_ACTIONS && !contains(ObjectTypeUniqueKeys.NOTE)) {
add(ObjectTypeUniqueKeys.NOTE)
}
if (size < MAX_TYPE_COUNT_FOR_APP_ACTIONS && !contains(ObjectTypeUniqueKeys.PAGE)) {
add(ObjectTypeUniqueKeys.PAGE)
}
if (size < MAX_TYPE_COUNT_FOR_APP_ACTIONS && !contains(ObjectTypeUniqueKeys.TASK)) {
add(ObjectTypeUniqueKeys.TASK)
}
}
searchObjects(
SearchObjects.Params(
keys = buildList {
add(Relations.ID)
add(Relations.UNIQUE_KEY)
add(Relations.NAME)
},
filters = buildList {
add(
DVFilter(
relation = Relations.SPACE_ID,
value = config.space,
condition = DVFilterCondition.EQUAL
)
)
add(
DVFilter(
relation = Relations.LAYOUT,
value = ObjectType.Layout.OBJECT_TYPE.code.toDouble(),
condition = DVFilterCondition.EQUAL
)
)
add(
DVFilter(
relation = Relations.UNIQUE_KEY,
value = keys.toList(),
condition = DVFilterCondition.IN
)
)
}
)
).process(
success = { wrappers ->
val types = wrappers
.filter { type -> type.notDeletedNorArchived }
.map { ObjectWrapper.Type(it.map) }
.sortedBy { keys.indexOf(it.uniqueKey) }
val actions = types.map { type ->
AppActionManager.Action.CreateNew(
type = TypeKey(type.uniqueKey),
name = type.name.orEmpty()
)
}
appActionManager.setup(actions = actions)
},
failure = {
Timber.e(it, "Error while searching for types")
}
)
}
.launchIn(viewModelScope)
}
private fun dispatchDeleteWidgetAnalyticsEvent(target: Widget?) {
viewModelScope.launch {
when (val source = target?.source) {
is Widget.Source.Bundled -> {
sendDeleteWidgetEvent(
analytics = analytics,
bundled = source,
isInEditMode = isInEditMode()
)
}
is Widget.Source.Default -> {
val sourceObjectType = source.type
if (sourceObjectType != null) {
val objectTypeWrapper = storeOfObjectTypes.get(sourceObjectType)
if (objectTypeWrapper != null) {
sendDeleteWidgetEvent(
analytics = analytics,
sourceObjectTypeId = objectTypeWrapper.sourceObject.orEmpty(),
isCustomObjectType = objectTypeWrapper.sourceObject.isNullOrEmpty(),
isInEditMode = isInEditMode()
)
} else {
Timber.e("Failed to dispatch analytics: source type not found in types storage")
}
} else {
Timber.e("Failed to dispatch analytics: unknown source type")
}
}
else -> {
Timber.e("Error while dispatching analytics event: source not found")
}
}
}
}
private fun isInEditMode() = mode.value == InteractionMode.Edit
private fun dispatchSelectHomeTabCustomSourceEvent(source: Widget.Source) {
viewModelScope.launch {
val sourceObjectType = source.type
if (sourceObjectType != null) {
val objectTypeWrapper = storeOfObjectTypes.get(sourceObjectType)
if (objectTypeWrapper != null) {
sendSelectHomeTabEvent(
analytics = analytics,
sourceObjectTypeId = objectTypeWrapper.sourceObject.orEmpty(),
isCustomObjectType = objectTypeWrapper.sourceObject.isNullOrEmpty()
)
} else {
Timber.e("Failed to dispatch analytics: source type not found in types storage")
}
} else {
Timber.e("Failed to dispatch analytics: unknown source type")
}
}
}
private fun dispatchReorderWidgetAnalyticEvent(subject: WidgetView) {
viewModelScope.launch {
val source = when (subject) {
is WidgetView.Link -> subject.source
is WidgetView.ListOfObjects -> subject.source
is WidgetView.SetOfObjects -> subject.source
is WidgetView.Tree -> subject.source
else -> null
}
when(source) {
is Widget.Source.Bundled -> {
sendReorderWidgetEvent(
analytics = analytics,
bundled = source
)
}
is Widget.Source.Default -> {
val sourceObjectType = source.type
if (sourceObjectType != null) {
val objectTypeWrapper = storeOfObjectTypes.get(sourceObjectType)
if (objectTypeWrapper != null) {
sendReorderWidgetEvent(
analytics = analytics,
sourceObjectTypeId = objectTypeWrapper.sourceObject.orEmpty(),
isCustomObjectType = objectTypeWrapper.sourceObject.isNullOrEmpty()
)
} else {
Timber.e("Failed to dispatch analytics: source type not found in types storage")
}
} else {
Timber.e("Failed to dispatch analytics: unknown source type")
}
}
else -> {
// Do nothing.
}
}
}
}
override fun onChangeCurrentWidgetView(widget: Id, view: Id) {
widgetActiveViewStateHolder.onChangeCurrentWidgetView(
widget = widget,
view = view
).also {
viewModelScope.launch {
val config = spaceManager.getConfig()
if (config != null)
setWidgetActiveView.stream(
SetWidgetActiveView.Params(
ctx = config.widgets,
widget = widget,
view = view,
)
).collect { result ->
result.fold(
onSuccess = { objectPayloadDispatcher.send(it) },
onFailure = { Timber.e(it, "Error while updating active view") }
)
}
else
Timber.e("Failed to get config to set active widget view")
}
}
}
fun onSpaceShareIconClicked(spaceView: ObjectWrapper.SpaceView) {
viewModelScope.launch {
val space = spaceView.targetSpaceId
if (space != null) {
commands.emit(Command.ShareSpace(SpaceId(space)))
} else {
sendToast("Space not found")
}
}
}
fun onSpaceSettingsClicked() {
viewModelScope.launch {
commands.emit(
Command.OpenSpaceSettings(
spaceId = SpaceId(spaceManager.get())
)
)
}
}
override fun onCleared() {
super.onCleared()
viewModelScope.launch {
unsubscriber.unsubscribe(listOf(HOME_SCREEN_PROFILE_OBJECT_SUBSCRIPTION))
}
}
fun onLibraryClicked() {
viewModelScope.launch {
val space = spaceManager.get()
navigation(
Navigation.OpenLibrary(space)
)
}
}
sealed class Navigation {
data class OpenObject(val ctx: Id, val space: Id) : Navigation()
data class OpenSet(val ctx: Id, val space: Id) : Navigation()
data class ExpandWidget(val subscription: Subscription, val space: Id) : Navigation()
data class OpenLibrary(val space: Id) : Navigation()
}
class Factory @Inject constructor(
private val openObject: OpenObject,
private val closeObject: CloseBlock,
private val createObject: CreateObject,
private val createWidget: CreateWidget,
private val deleteWidget: DeleteWidget,
private val updateWidget: UpdateWidget,
private val appCoroutineDispatchers: AppCoroutineDispatchers,
private val widgetEventDispatcher: Dispatcher<WidgetDispatchEvent>,
private val objectPayloadDispatcher: Dispatcher<Payload>,
private val interceptEvents: InterceptEvents,
private val storelessSubscriptionContainer: StorelessSubscriptionContainer,
private val widgetSessionStateHolder: WidgetSessionStateHolder,
private val widgetActiveViewStateHolder: WidgetActiveViewStateHolder,
private val collapsedWidgetStateHolder: CollapsedWidgetStateHolder,
private val urlBuilder: UrlBuilder,
private val getObject: GetObject,
private val move: Move,
private val emptyBin: EmptyBin,
private val unsubscriber: Unsubscriber,
private val getDefaultObjectType: GetDefaultObjectType,
private val appActionManager: AppActionManager,
private val analytics: Analytics,
private val getWidgetSession: GetWidgetSession,
private val saveWidgetSession: SaveWidgetSession,
private val spaceGradientProvider: SpaceGradientProvider,
private val storeOfObjectTypes: StoreOfObjectTypes,
private val objectWatcher: ObjectWatcher,
private val setWidgetActiveView: SetWidgetActiveView,
private val spaceManager: SpaceManager,
private val spaceWidgetContainer: SpaceWidgetContainer,
private val setObjectDetails: SetObjectDetails,
private val getSpaceView: GetSpaceView,
private val searchObjects: SearchObjects,
private val getPinnedObjectTypes: GetPinnedObjectTypes,
private val userPermissionProvider: UserPermissionProvider,
private val deepLinkToObjectDelegate: DeepLinkToObjectDelegate
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = HomeScreenViewModel(
openObject = openObject,
closeObject = closeObject,
createObject = createObject,
createWidget = createWidget,
deleteWidget = deleteWidget,
updateWidget = updateWidget,
appCoroutineDispatchers = appCoroutineDispatchers,
widgetEventDispatcher = widgetEventDispatcher,
objectPayloadDispatcher = objectPayloadDispatcher,
interceptEvents = interceptEvents,
storelessSubscriptionContainer = storelessSubscriptionContainer,
widgetSessionStateHolder = widgetSessionStateHolder,
widgetActiveViewStateHolder = widgetActiveViewStateHolder,
collapsedWidgetStateHolder = collapsedWidgetStateHolder,
getObject = getObject,
urlBuilder = urlBuilder,
move = move,
emptyBin = emptyBin,
unsubscriber = unsubscriber,
getDefaultObjectType = getDefaultObjectType,
appActionManager = appActionManager,
analytics = analytics,
getWidgetSession = getWidgetSession,
saveWidgetSession = saveWidgetSession,
spaceGradientProvider = spaceGradientProvider,
storeOfObjectTypes = storeOfObjectTypes,
objectWatcher = objectWatcher,
setWidgetActiveView = setWidgetActiveView,
spaceManager = spaceManager,
spaceWidgetContainer = spaceWidgetContainer,
setObjectDetails = setObjectDetails,
getSpaceView = getSpaceView,
searchObjects = searchObjects,
getPinnedObjectTypes = getPinnedObjectTypes,
userPermissionProvider = userPermissionProvider,
deepLinkToObjectDelegate = deepLinkToObjectDelegate
) as T
}
companion object {
val actions = listOf(
WidgetView.Action.EditWidgets
)
const val HOME_SCREEN_PROFILE_OBJECT_SUBSCRIPTION = "subscription.home-screen.profile-object"
}
}
/**
* State representing session while working with an object.
*/
sealed class ObjectViewState {
data object Idle : ObjectViewState()
data object Loading : ObjectViewState()
data class Success(val obj: ObjectView) : ObjectViewState()
data class Failure(val e: Throwable) : ObjectViewState()
}
sealed class InteractionMode {
data object Default : InteractionMode()
data object Edit : InteractionMode()
data object ReadOnly: InteractionMode()
}
sealed class Command {
/**
* [target] optional target, below which new widget will be created
*/
data class SelectWidgetSource(
val target: Id? = null,
val isInEditMode: Boolean
) : Command()
data class OpenSpaceSettings(val spaceId: SpaceId) : Command()
data class OpenObjectCreateDialog(val space: SpaceId) : Command()
data class SelectWidgetType(
val ctx: Id,
val source: Id,
val target: Id?,
val layout: Int,
val isInEditMode: Boolean
) : Command()
data class ChangeWidgetSource(
val ctx: Id,
val widget: Id,
val source: Id,
val type: Int,
val isInEditMode: Boolean
) : Command()
data class ChangeWidgetType(
val ctx: Id,
val widget: Id,
val source: Id,
val type: Int,
val layout: Int,
val isInEditMode: Boolean
) : Command() {
companion object {
const val TYPE_TREE = 0
const val TYPE_LINK = 1
const val TYPE_LIST = 2
const val TYPE_COMPACT_LIST = 3
const val UNDEFINED_LAYOUT_CODE = -1
}
}
data class ShareSpace(val space: SpaceId) : Command()
sealed class Deeplink : Command() {
data object DeepLinkToObjectNotWorking: Deeplink()
data object CannotImportExperience : Deeplink()
data class Invite(val link: String) : Deeplink()
data class GalleryInstallation(
val deepLinkType: String,
val deepLinkSource: String
) : Deeplink()
}
}
/**
* Empty list means there are no widgets.
* Null means there are no info about widgets — due to loading or error state.
*/
typealias Widgets = List<Widget>?
/**
* Empty list means there are no containers.
* Null means there are no info about containers — due to loading or error state.
*/
typealias Containers = List<WidgetContainer>?
sealed class OpenObjectNavigation {
data class OpenEditor(val target: Id, val space: Id) : OpenObjectNavigation()
data class OpenDataView(val target: Id, val space: Id): OpenObjectNavigation()
data class UnexpectedLayoutError(val layout: ObjectType.Layout?): OpenObjectNavigation()
}
fun ObjectWrapper.Basic.navigation() : OpenObjectNavigation {
return when (layout) {
ObjectType.Layout.BASIC,
ObjectType.Layout.NOTE,
ObjectType.Layout.TODO,
ObjectType.Layout.BOOKMARK,
ObjectType.Layout.PARTICIPANT -> {
OpenObjectNavigation.OpenEditor(
target = id,
space = requireNotNull(spaceId)
)
}
in SupportedLayouts.fileLayouts -> {
OpenObjectNavigation.OpenEditor(
target = id,
space = requireNotNull(spaceId)
)
}
ObjectType.Layout.PROFILE -> {
val identityLink = getValue<Id>(Relations.IDENTITY_PROFILE_LINK)
if (identityLink.isNullOrEmpty()) {
OpenObjectNavigation.OpenEditor(
target = id,
space = requireNotNull(spaceId)
)
} else {
OpenObjectNavigation.OpenEditor(
target = identityLink,
space = requireNotNull(spaceId)
)
}
}
ObjectType.Layout.SET,
ObjectType.Layout.COLLECTION -> {
OpenObjectNavigation.OpenDataView(
target = id,
space = requireNotNull(spaceId)
)
}
else -> {
OpenObjectNavigation.UnexpectedLayoutError(layout)
}
}
}
const val MAX_TYPE_COUNT_FOR_APP_ACTIONS = 4
const val MAX_PINNED_TYPE_COUNT_FOR_APP_ACTIONS = 3 | 45 | null | 43 | 528 | c708958dcb96201ab7bb064c838ffa8272d5f326 | 71,635 | anytype-kotlin | RSA Message-Digest License |
src/main/java/com/tang/intellij/lua/index/IndexManager.kt | EmmyLua | 79,353,335 | false | null | /*
* Copyright (c) 2017. tangzx([email protected])
*
* 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.tang.intellij.lua.index
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.util.Disposer
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.messages.Topic
import com.tang.intellij.lua.ext.fileId
import com.tang.intellij.lua.lang.LuaFileType
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.ITy
import java.util.concurrent.atomic.AtomicBoolean
class LuaProjectActivity : ProjectActivity {
override suspend fun execute(project: Project) {
IndexManager.getInstance(project)
}
}
@Service(Service.Level.PROJECT)
class IndexManager(private val project: Project) : Disposable, ApplicationListener {
enum class ScanType {
None,
All,
Changed
}
private val listener: LuaIndexListener = project.messageBus.syncPublisher(TOPIC)
private val solverManager = TypeSolverManager.getInstance(project)
private val changedFiles = mutableSetOf<LuaPsiFile>()
private var scanType = ScanType.All
private val task = IndexTask(project, listener)
private val taskQueue = TaskQueue(project)
init {
solverManager.setListener(task)
setupListeners(project)
Disposer.register(this, taskQueue)
Disposer.register(this, task)
}
private fun setupListeners(project: Project) {
val treeChangeListener = LuaPsiTreeChangeListener(this)
PsiManager.getInstance(project).addPsiTreeChangeListener(treeChangeListener, this)
ApplicationManager.getApplication().addApplicationListener(this, this)
}
fun onFileUpdate(file: PsiFile) {
if (file is LuaPsiFile) {
changedFiles.add(file)
scanType = ScanType.Changed
}
}
fun remove(element: PsiElement) {
val file = element.containingFile
solverManager.cleanFile(file.fileId)
}
override fun afterWriteActionFinished(action: Any) {
runScan()
}
fun tryInfer(target: LuaTypeGuessable): ITy? {
val typeSolver = solverManager.getSolver(target)
if (typeSolver.solved)
return typeSolver.result
if (task.isRunning) {
typeSolver.request()
} else {
task.scan(target)
taskQueue.run(task::run)
}
return if (typeSolver.solved) typeSolver.result else null
}
private fun runScan() {
when (scanType) {
ScanType.None -> { }
ScanType.All -> {
listener.onStatus(LuaIndexStatus.Waiting)
// taskQueue.runAfterSmartMode("Lua indexing ...", ::scanAllProject)
taskQueue.runAfterSmartMode(::scanAllProject)
}
ScanType.Changed -> scanChangedFiles()
}
scanType = ScanType.None
}
private fun scanChangedFiles() {
changedFiles.forEach {
task.scan(it)
}
changedFiles.clear()
taskQueue.run(task::run)
}
private fun scanAllProject(indicator: ProgressIndicator) {
indicator.pushState()
indicator.text = "Collecting ..."
listener.onStatus(LuaIndexStatus.Collecting)
val startAt = System.currentTimeMillis()
runReadAction {
FileBasedIndex.getInstance().iterateIndexableFiles({ vf ->
if (vf.fileType == LuaFileType.INSTANCE) {
PsiManager.getInstance(project).findFile(vf).let {
if (it is LuaPsiFile) task.scan(it)
}
}
true
}, project, null)
}
indicator.popState()
indicator.pushState()
val dt = System.currentTimeMillis() - startAt
logger.info("Scan all lua files in project, took $dt ms.")
task.run(indicator)
indicator.popState()
}
override fun dispose() {
}
companion object {
private val logger = Logger.getInstance(IndexManager::class.java)
fun getInstance(project: Project): IndexManager = project.getService(IndexManager::class.java)
val TOPIC: Topic<LuaIndexListener> = Topic.create("lua index listener", LuaIndexListener::class.java)
}
}
enum class LuaIndexStatus {
Waiting,
Collecting,
Analyse,
Finished
}
interface LuaIndexListener {
fun onStatus(status: LuaIndexStatus, complete: Int = 0, total: Int = 0)
}
class IndexReport {
var total = 0
var finished = 0
var noSolution = 0
private val startAt = System.currentTimeMillis()
fun report() {
val dt = System.currentTimeMillis() - startAt
val message = "Took $dt ms, total = $total, no solution = $noSolution"
logger.debug(message)
}
companion object {
private val logger = Logger.getInstance(IndexReport::class.java)
}
}
class IndexTask(private val project: Project, private val listener: LuaIndexListener) : TypeSolverListener, Disposable {
private val solverManager = TypeSolverManager.getInstance(project)
private val indexers = mutableListOf<Indexer>()
private val additional = mutableListOf<Indexer>()
private var running = AtomicBoolean(false)
private var disposed = false
val isRunning get() = running.get()
fun scan(psi: LuaTypeGuessable) {
add(solverManager.getSolver(psi))
}
fun scan(file: LuaPsiFile) {
solverManager.cleanFile(file.fileId)
file.accept(object: LuaStubRecursiveVisitor() {
override fun visitExpr(o: LuaExpr) {
if (o is LuaIndexExpr && o.assignStat != null) {
add(solverManager.getSolver(o))
}
else if (o is LuaNameExpr && o.assignStat != null) {
add(solverManager.getSolver(o))
}
super.visitExpr(o)
}
override fun visitClassMethodDef(o: LuaClassMethodDef) {
add(ClassMethodIndexer(o, solverManager))
super.visitClassMethodDef(o)
}
})
}
fun run(indicator: ProgressIndicator) {
if (indexers.isEmpty() || isRunning)
return
running.set(true)
val report = IndexReport()
try {
var done = false
while (true) {
runReadAction {
done = run(indicator, report)
}
if (done) break
Thread.sleep(100)
}
}
catch (e: ProcessCanceledException) {
// canceled
}
catch (e: Exception) {
e.printStackTrace()
}
indexers.clear()
report.report()
running.set(false)
listener.onStatus(LuaIndexStatus.Finished)
}
@Synchronized
private fun run(indicator: ProgressIndicator, report: IndexReport): Boolean {
var total = indexers.size
val context = SearchContext.get(project)
val time = System.currentTimeMillis()
report.total = total
while (total > 0) {
indexers.sortByDescending { it.priority }
for (item in indexers) {
if (item.invalid)
continue
if (disposed)
throw ProcessCanceledException()
item.tryIndex(solverManager, context)
val costTime = System.currentTimeMillis() - time
if (costTime > 200) {
update(indicator, report)
return false
}
}
update(indicator, report)
if (indexers.count() == total)
break
total = indexers.count()
}
report.noSolution = indexers.size
return true
}
private fun update(indicator: ProgressIndicator, report: IndexReport) {
indexers.removeAll { it.done || it.invalid }
val unfinished = indexers.count()
report.finished = report.total - unfinished
indicator.text = "index: ${report.finished} / ${report.total}"
listener.onStatus(LuaIndexStatus.Analyse, report.finished, report.total)
synchronized(additional) {
indexers.addAll(additional)
report.total += additional.size
additional.clear()
}
}
private fun add(solver: TypeSolver) {
if (solver.sig is NullSolverSignature)
return
add(GuessableIndexer(solver.sig.psi, solverManager))
solver.dependence?.let { add(it) }
}
private fun add(indexer: Indexer) {
if (isRunning) {
synchronized(additional) {
additional.add(indexer)
}
} else {
indexers.add(indexer)
}
}
override fun onNewCreated(solver: TypeSolver) {
add(solver)
}
override fun dispose() {
disposed = true
solverManager.dispose()
}
}
| 137 | Kotlin | 278 | 1,628 | 27490df76b8c787b78c0d5e9e7e3c40aef4f637b | 10,178 | IntelliJ-EmmyLua | Apache License 2.0 |
6_technician_android_app/app/src/main/java/com/sap/mobile/mahlwerk/extension/Task+Status.kt | alinamatei-dev | 401,294,557 | false | null | package com.sap.mobile.mahlwerk.extension
import com.sap.cloud.android.odata.odataservice.Task
import com.sap.mobile.mahlwerk.model.FinalReportStatus
import com.sap.mobile.mahlwerk.model.TaskStatus
/** Convenience property for representing the status of a Task */
val Task.taskStatus: TaskStatus
get() {
return TaskStatus.values()[taskStatusID.toInt()]
}
/** Convenience property for representing the final report status of a Task */
val Task.finalReportStatus: FinalReportStatus
get() {
return FinalReportStatus.values()[finalReportStatusID.toInt()]
} | 1 | null | 1 | 1 | 509637c7be2fbf1b5b606df57b8cec64c6e44b4f | 587 | cloud-mobile-end2end-sample | Apache License 2.0 |
codegen-renderers/src/main/kotlin/io/vrap/codegen/languages/php/model/PhpCollectionRenderer.kt | davidweterings | 179,671,623 | true | {"Kotlin": 182085, "RAML": 37920, "PHP": 1522, "Dockerfile": 201, "Shell": 84} | package io.vrap.codegen.languages.php.model;
import com.google.inject.Inject
import com.google.inject.name.Named
import io.vrap.codegen.languages.php.PhpSubTemplates
import io.vrap.codegen.languages.php.extensions.*
import io.vrap.rmf.codegen.di.VrapConstants
import io.vrap.rmf.codegen.io.TemplateFile
import io.vrap.rmf.codegen.rendring.ObjectTypeRenderer
import io.vrap.rmf.codegen.types.VrapObjectType
import io.vrap.rmf.codegen.types.VrapTypeProvider
import io.vrap.rmf.raml.model.types.ArrayType
import io.vrap.rmf.raml.model.types.ObjectType
import io.vrap.rmf.raml.model.types.Property
import io.vrap.rmf.raml.model.types.util.TypesSwitch
import org.eclipse.emf.ecore.EObject
import java.util.*
class PhpCollectionRenderer @Inject constructor(override val vrapTypeProvider: VrapTypeProvider) : ObjectTypeExtensions, EObjectTypeExtensions, ObjectTypeRenderer {
@Inject
@Named(io.vrap.rmf.codegen.di.VrapConstants.BASE_PACKAGE_NAME)
lateinit var packagePrefix:String
override fun render(type: ObjectType): TemplateFile {
val vrapType = vrapTypeProvider.doSwitch(type) as VrapObjectType
val content = """
|<?php
|${PhpSubTemplates.generatorInfo}
|namespace ${vrapType.namespaceName()};
|
|use ${packagePrefix.toNamespaceName()}\Base\Collection;
|
|class ${vrapType.simpleClassName}Collection extends Collection {
| private static $!type = ${vrapType.simpleClassName}::class;
|}
""".trimMargin().forcedLiteralEscape()
return TemplateFile(
relativePath = "src/" + vrapType.fullClassName().replace(packagePrefix.toNamespaceName(), "").replace("\\", "/") + "Collection.php",
content = content
)
}
fun ObjectType.imports() = this.getImports().map { "use $it;" }.joinToString(separator = "\n")
fun Property.toPhpField(): String {
return """
|/**
| * @var ${this.type.toVrapType().simpleName()}
| */
|private $${if (this.isPatternProperty()) "values" else this.name};
""".trimMargin();
}
fun ObjectType.toBeanFields() = this.properties
.filter { it.name != this.discriminator }
.map { it.toPhpField() }.joinToString(separator = "\n\n")
fun ObjectType.setters() = this.properties
//Filter the discriminators because they don't make much sense the generated bean
.filter { it.name != this.discriminator }
.map { it.setter() }
.joinToString(separator = "\n\n")
fun ObjectType.getters() = this.properties
//Filter the discriminators because they don't make much sense the generated bean
.filter { it.name != this.discriminator }
.map { it.getter() }
.joinToString(separator = "\n\n")
fun Property.isPatternProperty() = this.name.startsWith("/") && this.name.endsWith("/")
fun Property.setter(): String {
return if (this.isPatternProperty()) {
"""
|@JsonAnySetter
|public void setValue(String key, ${this.type.toVrapType().simpleName()} value) {
| if (values == null) {
| values = new HashMap<>();
| }
| values.put(key, value);
|}
""".trimMargin()
} else {
"""
|public void set${this.name.capitalize()}(final ${this.type.toVrapType().simpleName()} ${this.name}){
| this.${this.name} = ${this.name};
|}
""".trimMargin()
}
}
fun Property.getter(): String {
return if (this.isPatternProperty()) {
"""
|${this.type.toPhpComment()}
|public function values() {
| return $!values;
|}
""".trimMargin()
} else {
"""
|/**
| ${this.type.toPhpComment()}
| * @return ${this.type.toVrapType().simpleName()}
| */
|public function get${this.name.capitalize()}(){
| return $!this->${this.name};
|}
""".trimMargin()
}
}
fun Property.validationAnnotations(): String {
val validationAnnotations = ArrayList<String>()
if (this.required != null && this.required!!) {
validationAnnotations.add("@NotNull")
}
if (CascadeValidationCheck.doSwitch(this.type)) {
validationAnnotations.add("@Valid")
}
return validationAnnotations.joinToString(separator = "\n")
}
private object CascadeValidationCheck : TypesSwitch<Boolean>() {
override fun defaultCase(`object`: EObject?): Boolean? {
return false
}
override fun caseObjectType(objectType: ObjectType?): Boolean? {
return true
}
override fun caseArrayType(arrayType: ArrayType): Boolean? {
return if (arrayType.items != null) {
doSwitch(arrayType.items)
} else {
false
}
}
}
}
| 0 | Kotlin | 0 | 0 | c38e63b40feffc21d8c2a1862dc40f148534d1d1 | 5,193 | rmf-codegen | Apache License 2.0 |
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/legacyBridge/ModifiableRootModelBridge.kt | ingokegel | 72,937,917 | true | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.legacyBridge
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.impl.SdkFinder
import com.intellij.openapi.util.ModificationTracker
interface ModifiableRootModelBridge : ModifiableRootModel, ModificationTracker {
fun prepareForCommit()
fun postCommit()
companion object {
@JvmStatic
fun findSdk(sdkName: String, sdkType: String): Sdk? {
for (finder in SdkFinder.EP_NAME.extensionsIfPointIsRegistered) {
val sdk = finder.findSdk(sdkName, sdkType)
if (sdk != null) return sdk
}
return ProjectJdkTable.getInstance().findJdk(sdkName, sdkType)
}
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 922 | intellij-community | Apache License 2.0 |
components/core/log/src/androidMain/kotlin/com/flipperdevices/core/log/TimberKtx.kt | flipperdevices | 288,258,832 | false | {"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21} | package com.flipperdevices.core.log
import timber.log.Timber
actual inline fun error(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.e(logMessage.invoke())
}
}
actual inline fun error(error: Throwable, logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.e(error, logMessage.invoke())
}
}
actual inline fun info(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.i(logMessage.invoke())
}
}
actual inline fun verbose(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.v(logMessage.invoke())
}
}
actual inline fun warn(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.w(logMessage.invoke())
}
}
actual inline fun debug(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.d(logMessage.invoke())
}
}
actual inline fun wtf(logMessage: () -> String) {
if (BuildConfig.INTERNAL) {
Timber.wtf(logMessage.invoke())
}
}
| 21 | Kotlin | 174 | 1,528 | 8f293e596741a6c97409acbc8de10c7ae6e8d8b0 | 1,004 | Flipper-Android-App | MIT License |
oneadapter/src/main/java/com/idanatz/oneadapter/external/states/States.kt | HAIWWH | 203,148,196 | true | {"Kotlin": 35462} | package com.idanatz.oneadapter.external.states
import org.jetbrains.annotations.NotNull
sealed class State<M>
abstract class SelectionState<M> : State<M>() {
companion object {
val TAG: String = SelectionState::class.java.simpleName
}
abstract fun selectionEnabled(@NotNull model: M): Boolean
abstract fun onSelected(@NotNull model: M, selected: Boolean)
} | 0 | Kotlin | 0 | 0 | bcc0fe2290d092731d3c4b23c4f38d7807a7302a | 383 | OneAdapter | MIT License |
okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RealConnection.kt | square | 5,152,285 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import java.lang.ref.Reference
import java.net.ConnectException
import java.net.HttpURLConnection.HTTP_OK
import java.net.HttpURLConnection.HTTP_PROXY_AUTH
import java.net.ProtocolException
import java.net.Proxy
import java.net.Socket
import java.net.SocketException
import java.net.UnknownServiceException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.SSLSocket
import okhttp3.Address
import okhttp3.Call
import okhttp3.CertificatePinner
import okhttp3.Connection
import okhttp3.ConnectionSpec
import okhttp3.EventListener
import okhttp3.Handshake
import okhttp3.Handshake.Companion.handshake
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import okhttp3.internal.EMPTY_RESPONSE
import okhttp3.internal.assertThreadDoesntHoldLock
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http1.Http1ExchangeCodec
import okhttp3.internal.http2.ConnectionShutdownException
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.Http2Connection
import okhttp3.internal.http2.Http2ExchangeCodec
import okhttp3.internal.http2.Http2Stream
import okhttp3.internal.http2.Settings
import okhttp3.internal.http2.StreamResetException
import okhttp3.internal.isHealthy
import okhttp3.internal.platform.Platform
import okhttp3.internal.tls.OkHostnameVerifier
import okhttp3.internal.toHostHeader
import okhttp3.internal.userAgent
import okhttp3.internal.ws.RealWebSocket
import okio.BufferedSink
import okio.BufferedSource
import okio.buffer
import okio.sink
import okio.source
/**
* A connection to a remote web server capable of carrying 1 or more concurrent streams.
*
* A connection's lifecycle has two phases.
*
* 1. While it's connecting, the connection is owned by a single call using single thread. In this
* phase the connection is not shared and no locking is necessary.
*
* 2. Once connected, a connection is shared to a connection pool. In this phase accesses to the
* connection's state must be guarded by holding a lock on the connection.
*/
class RealConnection(
val taskRunner: TaskRunner,
val connectionPool: RealConnectionPool,
private val route: Route
) : Http2Connection.Listener(), Connection {
// These properties are initialized by connect() and never reassigned.
/** The low-level TCP socket. */
private var rawSocket: Socket? = null
/**
* The application layer socket. Either an [SSLSocket] layered over [rawSocket], or [rawSocket]
* itself if this connection does not use SSL.
*/
private var socket: Socket? = null
private var handshake: Handshake? = null
private var protocol: Protocol? = null
private var http2Connection: Http2Connection? = null
private var source: BufferedSource? = null
private var sink: BufferedSink? = null
// These properties are guarded by this.
/**
* If true, no new exchanges can be created on this connection. It is necessary to set this to
* true when removing a connection from the pool; otherwise a racing caller might get it from the
* pool when it shouldn't. Symmetrically, this must always be checked before returning a
* connection from the pool.
*
* Once true this is always true. Guarded by this.
*/
var noNewExchanges = false
/**
* If true, this connection may not be used for coalesced requests. These are requests that could
* share the same connection without sharing the same hostname.
*/
private var noCoalescedConnections = false
/**
* The number of times there was a problem establishing a stream that could be due to route
* chosen. Guarded by this.
*/
internal var routeFailureCount = 0
private var successCount = 0
private var refusedStreamCount = 0
/**
* The maximum number of concurrent streams that can be carried by this connection. If
* `allocations.size() < allocationLimit` then new streams can be created on this connection.
*/
private var allocationLimit = 1
/** Current calls carried by this connection. */
val calls = mutableListOf<Reference<RealCall>>()
/** Timestamp when `allocations.size()` reached zero. Also assigned upon initial connection. */
var idleAtNs = Long.MAX_VALUE
/**
* Returns true if this is an HTTP/2 connection. Such connections can be used in multiple HTTP
* requests simultaneously.
*/
internal val isMultiplexed: Boolean
get() = http2Connection != null
/** True if we haven't yet called [connect] on this. */
internal val isNew: Boolean
get() = protocol == null
/** Prevent further exchanges from being created on this connection. */
@Synchronized internal fun noNewExchanges() {
noNewExchanges = true
}
/** Prevent this connection from being used for hosts other than the one in [route]. */
@Synchronized internal fun noCoalescedConnections() {
noCoalescedConnections = true
}
@Synchronized internal fun incrementSuccessCount() {
successCount++
}
fun connect(
connectTimeout: Int,
readTimeout: Int,
writeTimeout: Int,
pingIntervalMillis: Int,
connectionRetryEnabled: Boolean,
call: Call,
eventListener: EventListener
) {
check(isNew) { "already connected" }
var firstException: IOException? = null
val connectionSpecs = route.address.connectionSpecs
val connectionSpecSelector = ConnectionSpecSelector(connectionSpecs)
if (route.address.sslSocketFactory == null) {
if (ConnectionSpec.CLEARTEXT !in connectionSpecs) {
throw UnknownServiceException("CLEARTEXT communication not enabled for client")
}
val host = route.address.url.host
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw UnknownServiceException(
"CLEARTEXT communication to $host not permitted by network security policy"
)
}
} else {
if (Protocol.H2_PRIOR_KNOWLEDGE in route.address.protocols) {
throw UnknownServiceException("H2_PRIOR_KNOWLEDGE cannot be used with HTTPS")
}
}
while (true) {
try {
if (route.requiresTunnel()) {
connectTunnel(connectTimeout, readTimeout, writeTimeout, call, eventListener)
if (rawSocket == null) {
// We were unable to connect the tunnel but properly closed down our resources.
break
}
} else {
connectSocket(connectTimeout, readTimeout, call, eventListener)
}
establishProtocol(connectionSpecSelector, pingIntervalMillis, call, eventListener)
eventListener.connectEnd(call, route.socketAddress, route.proxy, protocol)
break
} catch (e: IOException) {
socket?.closeQuietly()
rawSocket?.closeQuietly()
socket = null
rawSocket = null
source = null
sink = null
handshake = null
protocol = null
http2Connection = null
allocationLimit = 1
eventListener.connectFailed(call, route.socketAddress, route.proxy, null, e)
if (firstException == null) {
firstException = e
} else {
firstException.addSuppressed(e)
}
if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
throw firstException
}
}
}
if (route.requiresTunnel() && rawSocket == null) {
throw ProtocolException(
"Too many tunnel connections attempted: $MAX_TUNNEL_ATTEMPTS"
)
}
idleAtNs = System.nanoTime()
}
/**
* Does all the work to build an HTTPS connection over a proxy tunnel. The catch here is that a
* proxy server can issue an auth challenge and then close the connection.
*/
@Throws(IOException::class)
private fun connectTunnel(
connectTimeout: Int,
readTimeout: Int,
writeTimeout: Int,
call: Call,
eventListener: EventListener
) {
var tunnelRequest: Request = createTunnelRequest()
val url = tunnelRequest.url
for (i in 0 until MAX_TUNNEL_ATTEMPTS) {
connectSocket(connectTimeout, readTimeout, call, eventListener)
tunnelRequest = createTunnel(readTimeout, writeTimeout, tunnelRequest, url)
?: break // Tunnel successfully created.
// The proxy decided to close the connection after an auth challenge. We need to create a new
// connection, but this time with the auth credentials.
rawSocket?.closeQuietly()
rawSocket = null
sink = null
source = null
eventListener.connectEnd(call, route.socketAddress, route.proxy, null)
}
}
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
@Throws(IOException::class)
private fun connectSocket(
connectTimeout: Int,
readTimeout: Int,
call: Call,
eventListener: EventListener
) {
val proxy = route.proxy
val address = route.address
val rawSocket = when (proxy.type()) {
Proxy.Type.DIRECT, Proxy.Type.HTTP -> address.socketFactory.createSocket()!!
else -> Socket(proxy)
}
this.rawSocket = rawSocket
eventListener.connectStart(call, route.socketAddress, proxy)
rawSocket.soTimeout = readTimeout
try {
Platform.get().connectSocket(rawSocket, route.socketAddress, connectTimeout)
} catch (e: ConnectException) {
throw ConnectException("Failed to connect to ${route.socketAddress}").apply {
initCause(e)
}
}
// The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0
// More details:
// https://github.com/square/okhttp/issues/3245
// https://android-review.googlesource.com/#/c/271775/
try {
source = rawSocket.source().buffer()
sink = rawSocket.sink().buffer()
} catch (npe: NullPointerException) {
if (npe.message == NPE_THROW_WITH_NULL) {
throw IOException(npe)
}
}
}
@Throws(IOException::class)
private fun establishProtocol(
connectionSpecSelector: ConnectionSpecSelector,
pingIntervalMillis: Int,
call: Call,
eventListener: EventListener
) {
if (route.address.sslSocketFactory == null) {
if (Protocol.H2_PRIOR_KNOWLEDGE in route.address.protocols) {
socket = rawSocket
protocol = Protocol.H2_PRIOR_KNOWLEDGE
startHttp2(pingIntervalMillis)
return
}
socket = rawSocket
protocol = Protocol.HTTP_1_1
return
}
eventListener.secureConnectStart(call)
connectTls(connectionSpecSelector)
eventListener.secureConnectEnd(call, handshake)
if (protocol === Protocol.HTTP_2) {
startHttp2(pingIntervalMillis)
}
}
@Throws(IOException::class)
private fun startHttp2(pingIntervalMillis: Int) {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
socket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream.
val http2Connection = Http2Connection.Builder(client = true, taskRunner)
.socket(socket, route.address.url.host, source, sink)
.listener(this)
.pingIntervalMillis(pingIntervalMillis)
.build()
this.http2Connection = http2Connection
this.allocationLimit = Http2Connection.DEFAULT_SETTINGS.getMaxConcurrentStreams()
http2Connection.start()
}
@Throws(IOException::class)
private fun connectTls(connectionSpecSelector: ConnectionSpecSelector) {
val address = route.address
val sslSocketFactory = address.sslSocketFactory
var success = false
var sslSocket: SSLSocket? = null
try {
// Create the wrapper over the connected socket.
sslSocket = sslSocketFactory!!.createSocket(
rawSocket, address.url.host, address.url.port, true /* autoClose */
) as SSLSocket
// Configure the socket's ciphers, TLS versions, and extensions.
val connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket)
if (connectionSpec.supportsTlsExtensions) {
Platform.get().configureTlsExtensions(sslSocket, address.url.host, address.protocols)
}
// Force handshake. This can throw!
sslSocket.startHandshake()
// block for session establishment
val sslSocketSession = sslSocket.session
val unverifiedHandshake = sslSocketSession.handshake()
// Verify that the socket's certificates are acceptable for the target host.
if (!address.hostnameVerifier!!.verify(address.url.host, sslSocketSession)) {
val peerCertificates = unverifiedHandshake.peerCertificates
if (peerCertificates.isNotEmpty()) {
val cert = peerCertificates[0] as X509Certificate
throw SSLPeerUnverifiedException(
"""
|Hostname ${address.url.host} not verified:
| certificate: ${CertificatePinner.pin(cert)}
| DN: ${cert.subjectDN.name}
| subjectAltNames: ${OkHostnameVerifier.allSubjectAltNames(cert)}
""".trimMargin()
)
} else {
throw SSLPeerUnverifiedException(
"Hostname ${address.url.host} not verified (no certificates)"
)
}
}
val certificatePinner = address.certificatePinner!!
handshake = Handshake(
unverifiedHandshake.tlsVersion,
unverifiedHandshake.cipherSuite,
unverifiedHandshake.localCertificates
) {
certificatePinner.certificateChainCleaner!!.clean(
unverifiedHandshake.peerCertificates,
address.url.host
)
}
// Check that the certificate pinner is satisfied by the certificates presented.
certificatePinner.check(address.url.host) {
handshake!!.peerCertificates.map { it as X509Certificate }
}
// Success! Save the handshake and the ALPN protocol.
val maybeProtocol = if (connectionSpec.supportsTlsExtensions) {
Platform.get().getSelectedProtocol(sslSocket)
} else {
null
}
socket = sslSocket
source = sslSocket.source().buffer()
sink = sslSocket.sink().buffer()
protocol = if (maybeProtocol != null) Protocol.get(maybeProtocol) else Protocol.HTTP_1_1
success = true
} finally {
if (sslSocket != null) {
Platform.get().afterHandshake(sslSocket)
}
if (!success) {
sslSocket?.closeQuietly()
}
}
}
/**
* To make an HTTPS connection over an HTTP proxy, send an unencrypted CONNECT request to create
* the proxy connection. This may need to be retried if the proxy requires authorization.
*/
@Throws(IOException::class)
private fun createTunnel(
readTimeout: Int,
writeTimeout: Int,
tunnelRequest: Request,
url: HttpUrl
): Request? {
var nextRequest = tunnelRequest
// Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
val requestLine = "CONNECT ${url.toHostHeader(includeDefaultPort = true)} HTTP/1.1"
while (true) {
val source = this.source!!
val sink = this.sink!!
val tunnelCodec = Http1ExchangeCodec(null, this, source, sink)
source.timeout().timeout(readTimeout.toLong(), MILLISECONDS)
sink.timeout().timeout(writeTimeout.toLong(), MILLISECONDS)
tunnelCodec.writeRequest(nextRequest.headers, requestLine)
tunnelCodec.finishRequest()
val response = tunnelCodec.readResponseHeaders(false)!!
.request(nextRequest)
.build()
tunnelCodec.skipConnectBody(response)
when (response.code) {
HTTP_OK -> {
// Assume the server won't send a TLS ServerHello until we send a TLS ClientHello. If
// that happens, then we will have buffered bytes that are needed by the SSLSocket!
// This check is imperfect: it doesn't tell us whether a handshake will succeed, just
// that it will almost certainly fail because the proxy has sent unexpected data.
if (!source.buffer.exhausted() || !sink.buffer.exhausted()) {
throw IOException("TLS tunnel buffered too many bytes!")
}
return null
}
HTTP_PROXY_AUTH -> {
nextRequest = route.address.proxyAuthenticator.authenticate(route, response)
?: throw IOException("Failed to authenticate with proxy")
if ("close".equals(response.header("Connection"), ignoreCase = true)) {
return nextRequest
}
}
else -> throw IOException("Unexpected response code for CONNECT: ${response.code}")
}
}
}
/**
* Returns a request that creates a TLS tunnel via an HTTP proxy. Everything in the tunnel request
* is sent unencrypted to the proxy server, so tunnels include only the minimum set of headers.
* This avoids sending potentially sensitive data like HTTP cookies to the proxy unencrypted.
*
* In order to support preemptive authentication we pass a fake "Auth Failed" response to the
* authenticator. This gives the authenticator the option to customize the CONNECT request. It can
* decline to do so by returning null, in which case OkHttp will use it as-is.
*/
@Throws(IOException::class)
private fun createTunnelRequest(): Request {
val proxyConnectRequest = Request.Builder()
.url(route.address.url)
.method("CONNECT", null)
.header("Host", route.address.url.toHostHeader(includeDefaultPort = true))
.header("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
.header("User-Agent", userAgent)
.build()
val fakeAuthChallengeResponse = Response.Builder()
.request(proxyConnectRequest)
.protocol(Protocol.HTTP_1_1)
.code(HTTP_PROXY_AUTH)
.message("Preemptive Authenticate")
.body(EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(-1L)
.header("Proxy-Authenticate", "OkHttp-Preemptive")
.build()
val authenticatedRequest = route.address.proxyAuthenticator
.authenticate(route, fakeAuthChallengeResponse)
return authenticatedRequest ?: proxyConnectRequest
}
/**
* Returns true if this connection can carry a stream allocation to `address`. If non-null
* `route` is the resolved route for a connection.
*/
internal fun isEligible(address: Address, routes: List<Route>?): Boolean {
assertThreadHoldsLock()
// If this connection is not accepting new exchanges, we're done.
if (calls.size >= allocationLimit || noNewExchanges) return false
// If the non-host fields of the address don't overlap, we're done.
if (!this.route.address.equalsNonHost(address)) return false
// If the host exactly matches, we're done: this connection can carry the address.
if (address.url.host == this.route().address.url.host) {
return true // This connection is a perfect match.
}
// At this point we don't have a hostname match. But we still be able to carry the request if
// our connection coalescing requirements are met. See also:
// https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding
// https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/
// 1. This connection must be HTTP/2.
if (http2Connection == null) return false
// 2. The routes must share an IP address.
if (routes == null || !routeMatchesAny(routes)) return false
// 3. This connection's server certificate's must cover the new host.
if (address.hostnameVerifier !== OkHostnameVerifier) return false
if (!supportsUrl(address.url)) return false
// 4. Certificate pinning must match the host.
try {
address.certificatePinner!!.check(address.url.host, handshake()!!.peerCertificates)
} catch (_: SSLPeerUnverifiedException) {
return false
}
return true // The caller's address can be carried by this connection.
}
/**
* Returns true if this connection's route has the same address as any of [candidates]. This
* requires us to have a DNS address for both hosts, which only happens after route planning. We
* can't coalesce connections that use a proxy, since proxies don't tell us the origin server's IP
* address.
*/
private fun routeMatchesAny(candidates: List<Route>): Boolean {
return candidates.any {
it.proxy.type() == Proxy.Type.DIRECT &&
route.proxy.type() == Proxy.Type.DIRECT &&
route.socketAddress == it.socketAddress
}
}
private fun supportsUrl(url: HttpUrl): Boolean {
assertThreadHoldsLock()
val routeUrl = route.address.url
if (url.port != routeUrl.port) {
return false // Port mismatch.
}
if (url.host == routeUrl.host) {
return true // Host match. The URL is supported.
}
// We have a host mismatch. But if the certificate matches, we're still good.
return !noCoalescedConnections && handshake != null && certificateSupportHost(url, handshake!!)
}
private fun certificateSupportHost(url: HttpUrl, handshake: Handshake): Boolean {
val peerCertificates = handshake.peerCertificates
return peerCertificates.isNotEmpty() &&
OkHostnameVerifier.verify(url.host, peerCertificates[0] as X509Certificate)
}
@Throws(SocketException::class)
internal fun newCodec(client: OkHttpClient, chain: RealInterceptorChain): ExchangeCodec {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
val http2Connection = this.http2Connection
return if (http2Connection != null) {
Http2ExchangeCodec(client, this, chain, http2Connection)
} else {
socket.soTimeout = chain.readTimeoutMillis()
source.timeout().timeout(chain.readTimeoutMillis.toLong(), MILLISECONDS)
sink.timeout().timeout(chain.writeTimeoutMillis.toLong(), MILLISECONDS)
Http1ExchangeCodec(client, this, source, sink)
}
}
@Throws(SocketException::class)
internal fun newWebSocketStreams(exchange: Exchange): RealWebSocket.Streams {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
socket.soTimeout = 0
noNewExchanges()
return object : RealWebSocket.Streams(true, source, sink) {
override fun close() {
exchange.bodyComplete<IOException?>(-1L, responseDone = true, requestDone = true, e = null)
}
}
}
override fun route(): Route = route
fun cancel() {
// Close the raw socket so we don't end up doing synchronous I/O.
rawSocket?.closeQuietly()
}
override fun socket(): Socket = socket!!
/** Returns true if this connection is ready to host new streams. */
fun isHealthy(doExtensiveChecks: Boolean): Boolean {
assertThreadDoesntHoldLock()
val nowNs = System.nanoTime()
val rawSocket = this.rawSocket!!
val socket = this.socket!!
val source = this.source!!
if (rawSocket.isClosed || socket.isClosed || socket.isInputShutdown ||
socket.isOutputShutdown) {
return false
}
val http2Connection = this.http2Connection
if (http2Connection != null) {
return http2Connection.isHealthy(nowNs)
}
val idleDurationNs = synchronized(this) { nowNs - idleAtNs }
if (idleDurationNs >= IDLE_CONNECTION_HEALTHY_NS && doExtensiveChecks) {
return socket.isHealthy(source)
}
return true
}
/** Refuse incoming streams. */
@Throws(IOException::class)
override fun onStream(stream: Http2Stream) {
stream.close(ErrorCode.REFUSED_STREAM, null)
}
/** When settings are received, adjust the allocation limit. */
@Synchronized override fun onSettings(connection: Http2Connection, settings: Settings) {
allocationLimit = settings.getMaxConcurrentStreams()
}
override fun handshake(): Handshake? = handshake
/** Track a bad route in the route database. Other routes will be attempted first. */
internal fun connectFailed(client: OkHttpClient, failedRoute: Route, failure: IOException) {
// Tell the proxy selector when we fail to connect on a fresh connection.
if (failedRoute.proxy.type() != Proxy.Type.DIRECT) {
val address = failedRoute.address
address.proxySelector.connectFailed(
address.url.toUri(), failedRoute.proxy.address(), failure
)
}
client.routeDatabase.failed(failedRoute)
}
/**
* Track a failure using this connection. This may prevent both the connection and its route from
* being used for future exchanges.
*/
@Synchronized internal fun trackFailure(call: RealCall, e: IOException?) {
if (e is StreamResetException) {
when {
e.errorCode == ErrorCode.REFUSED_STREAM -> {
// Stop using this connection on the 2nd REFUSED_STREAM error.
refusedStreamCount++
if (refusedStreamCount > 1) {
noNewExchanges = true
routeFailureCount++
}
}
e.errorCode == ErrorCode.CANCEL && call.isCanceled() -> {
// Permit any number of CANCEL errors on locally-canceled calls.
}
else -> {
// Everything else wants a fresh connection.
noNewExchanges = true
routeFailureCount++
}
}
} else if (!isMultiplexed || e is ConnectionShutdownException) {
noNewExchanges = true
// If this route hasn't completed a call, avoid it for new connections.
if (successCount == 0) {
if (e != null) {
connectFailed(call.client, route, e)
}
routeFailureCount++
}
}
}
override fun protocol(): Protocol = protocol!!
override fun toString(): String {
return "Connection{${route.address.url.host}:${route.address.url.port}," +
" proxy=${route.proxy}" +
" hostAddress=${route.socketAddress}" +
" cipherSuite=${handshake?.cipherSuite ?: "none"}" +
" protocol=$protocol}"
}
companion object {
private const val NPE_THROW_WITH_NULL = "throw with null exception"
private const val MAX_TUNNEL_ATTEMPTS = 21
const val IDLE_CONNECTION_HEALTHY_NS = 10_000_000_000 // 10 seconds.
fun newTestConnection(
taskRunner: TaskRunner,
connectionPool: RealConnectionPool,
route: Route,
socket: Socket,
idleAtNs: Long
): RealConnection {
val result = RealConnection(taskRunner, connectionPool, route)
result.socket = socket
result.idleAtNs = idleAtNs
return result
}
}
}
| 7 | null | 8732 | 41,455 | b97eeacaa31a2c72a9396f5a4eab82f69b39cda8 | 27,441 | okhttp | Apache License 2.0 |
app/src/main/java/com/example/retrofit/data/User.kt | edgarvaldez99 | 225,200,862 | false | null | package com.example.retrofit.data
import com.google.gson.annotations.SerializedName
data class User(
@SerializedName("id")
val id: String,
@SerializedName("name")
val name: String,
@SerializedName("email")
val email: String,
@SerializedName("username")
val username: String,
@SerializedName("authentication_token")
val authenticationToken: String,
@SerializedName("persona")
val person: Person
) {
data class Person(
@SerializedName("user_id")
val userId: Int,
@SerializedName("tipo_documento_id")
val documentTypeId: Int,
@SerializedName("documento")
val document: String,
@SerializedName("fecha_nacimiento")
val birthDate: String
)
override fun toString(): String {
return this.name
}
} | 0 | Kotlin | 0 | 0 | b9a9a631ec71bf82d9aa3ff226d64cf48bc5b443 | 827 | android-retrofit-example | MIT License |
app/src/main/java/com/kcteam/features/SearchLocation/SearchLocationFragment.kt | DebashisINT | 558,234,039 | false | null | package com.dryftdynamics.features.SearchLocation
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.dryftdynamics.R
import com.dryftdynamics.app.Pref
import com.dryftdynamics.app.utils.AppUtils
import com.dryftdynamics.base.presentation.BaseFragment
import com.dryftdynamics.features.dashboard.presentation.DashboardActivity
import com.dryftdynamics.mappackage.MapActivity.MY_PERMISSIONS_REQUEST_LOCATION
import com.dryftdynamics.widgets.AppCustomEditText
import com.dryftdynamics.widgets.AppCustomTextView
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.places.Places
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.*
import java.io.IOException
import java.util.*
/**
* Created by Pratishruti on 27-10-2017.
*/
class SearchLocationFragment : BaseFragment(), View.OnClickListener, LocationAdapter.OnLocationItemClickListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private lateinit var captureShopImage: ImageView
private lateinit var shopImage: RelativeLayout
private lateinit var mContext: Context
private lateinit var searchLocation_edt: AppCustomEditText
private lateinit var mapView: MapView
private var locationAdapter: LocationAdapter? = null
private var mGoogleApiClient: GoogleApiClient? = null
internal var geocoder: Geocoder? = null
private var selectedLatitude: Double = 0.0
private var selectedLongitude: Double = 0.0
private var isLocationClicked = false
private var mLocationRequest: LocationRequest? = null
private var googleMap: GoogleMap? = null
private lateinit var rv_address_list: RecyclerView
private lateinit var search_progress: ProgressBar
private var map: GoogleMap? = null
internal lateinit var location: Location
internal val handler = Handler()
private var locationManager: LocationManager? = null
private var provider: String? = null
private val minDistance = 1000
private var latitude: Double = 0.0
private var longitude: Double = 0.0
private lateinit var cross_iv: ImageView
private var placeId: String = ""
private lateinit var save_TV: AppCustomTextView
var fullAdd: String = ""
var pinCode: String = ""
private var markerOptions: MarkerOptions? = null
var isLocationPicked = false
private var currentLocationMarker: Marker? = null
private var state = ""
private var city = ""
private var country = ""
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.searchlocation, container, false)
mGoogleApiClient = GoogleApiClient.Builder(mContext)
.enableAutoManage(activity!!, 0, this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()
mGoogleApiClient?.connect()
initView(view, savedInstanceState)
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onStop() {
if (mGoogleApiClient != null && mGoogleApiClient?.isConnected!!) {
mGoogleApiClient?.stopAutoManage(activity!!);
mGoogleApiClient?.disconnect()
}
super.onStop()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
private fun initView(view: View, savedInstanceState: Bundle?) {
save_TV = view.findViewById(R.id.save_TV)
cross_iv = view.findViewById(R.id.cross_iv)
searchLocation_edt = view.findViewById(R.id.searchLocation_edt)
search_progress = view.findViewById(R.id.search_progress)
mapView = view.findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.onResume()
rv_address_list = view.findViewById(R.id.rv_address_list)
locationAdapter = LocationAdapter(mContext, ArrayList<EditTextAddressModel>(), this)
rv_address_list.layoutManager = LinearLayoutManager(mContext)
rv_address_list.itemAnimator = DefaultItemAnimator() as RecyclerView.ItemAnimator?
rv_address_list.setHasFixedSize(true)
rv_address_list.adapter = locationAdapter
searchLocation_edt.setOnClickListener(this)
cross_iv.setOnClickListener(this)
save_TV.setOnClickListener(this)
initTextChangeListener()
if (checkLocationPermission()) {
InitiateMap()
} else
return
searchLocation_edt.setOnKeyListener(View.OnKeyListener { p0, p1, p2 ->
if ((p2?.action == KeyEvent.ACTION_DOWN)) {
if (!isLocationClicked)
return@OnKeyListener false
else {
isLocationClicked = false
searchLocation_edt.setText(searchLocation_edt.text.toString())
rv_address_list.visibility = View.GONE
Places.GeoDataApi.getPlaceById(mGoogleApiClient!!, placeId).setResultCallback { places ->
if (places.status.isSuccess) {
try {
selectedLatitude = places.get(0).latLng.latitude
selectedLongitude = places.get(0).latLng.longitude
markerOptions?.position(places.get(0).latLng);
markerOptions?.title(searchLocation_edt.text.toString());
//googleMap?.clear();
googleMap?.animateCamera(CameraUpdateFactory.newLatLng(places.get(0).latLng));
if (currentLocationMarker != null)
currentLocationMarker?.remove()
currentLocationMarker = googleMap?.addMarker(markerOptions);
} catch (e: Exception) {
e.printStackTrace()
}
}
places.release()
}
}
return@OnKeyListener true;
}
false;
});
}
private fun fetchPinnedAddress(latLong: LatLng?): String {
try {
geocoder = Geocoder(mContext, Locale.getDefault())
val addresses: List<android.location.Address> = geocoder?.getFromLocation(latLong?.latitude!!, latLong.longitude, 1)!!;
if (addresses.isNotEmpty()) {
val address: Address = addresses[0];
fullAdd = address.getAddressLine(0);
if (addresses[0].postalCode != null)
pinCode = addresses[0].postalCode
if (addresses[0].adminArea != null)
state = addresses[0].adminArea
if (addresses[0].locality != null)
city = addresses[0].locality
if (addresses[0].countryName != null)
country = addresses[0].countryName
selectedLatitude = latLong?.latitude!!
selectedLongitude = latLong.longitude
//Reset MapView
if (markerOptions != null) {
markerOptions?.position(latLong);
markerOptions?.title(latLong.latitude.toString() + " : " + latLong.longitude.toString());
}
//googleMap?.clear();
googleMap?.animateCamera(CameraUpdateFactory.newLatLng(latLong));
if (currentLocationMarker != null)
currentLocationMarker?.remove()
currentLocationMarker = googleMap?.addMarker(markerOptions);
searchLocation_edt.setText(fullAdd)
}
} catch (ex: IOException) {
ex.printStackTrace();
}
return fullAdd;
}
private fun InitiateMap() {
try {
MapsInitializer.initialize(mContext.applicationContext)
} catch (e: Exception) {
e.printStackTrace()
}
mapView.getMapAsync(OnMapReadyCallback { mMap ->
googleMap = mMap
googleMap?.uiSettings!!.isMapToolbarEnabled = false;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return@OnMapReadyCallback
}
googleMap?.isMyLocationEnabled = true
/* mMap.addMarker(MarkerOptions().position(sydney).title(address));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
markerOptions = MarkerOptions()
googleMap?.setOnMapClickListener { p0 ->
if (AppUtils.isOnline(mContext))
search_progress.visibility = View.VISIBLE
// Setting the position for the marker
selectedLatitude = p0?.latitude!!
selectedLongitude = p0.longitude
markerOptions?.position(p0);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions?.title(p0.latitude.toString() + " : " + p0.longitude.toString());
// Clears the previously touched position
//googleMap?.clear();
// Animating to the touched position
val cameraPosition = CameraPosition.Builder().target(LatLng(selectedLatitude, selectedLongitude)).zoom(15f).build()
googleMap?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
//googleMap?.animateCamera(CameraUpdateFactory.newLatLng(p0));
// Placing a marker on the touched position
if (currentLocationMarker != null)
currentLocationMarker?.remove()
currentLocationMarker = googleMap?.addMarker(markerOptions)!!;
search_progress.visibility = View.GONE
isLocationPicked = true
if (p0 != null) {
fetchPinnedAddress(p0)
}
}
googleMap?.setOnMarkerDragListener(object : GoogleMap.OnMarkerDragListener {
override fun onMarkerDragStart(p0: Marker?) {
}
override fun onMarkerDrag(p0: Marker?) {
selectedLatitude = p0?.position!!.latitude
selectedLongitude = p0.position!!.longitude
isLocationPicked = true
p0.title = p0.position!!.latitude.toString() + " : " + p0.position!!.longitude.toString()
//googleMap?.clear();
val cameraPosition = CameraPosition.Builder().target(LatLng(selectedLatitude, selectedLongitude)).zoom(15f).build()
googleMap?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
override fun onMarkerDragEnd(p0: Marker?) {
}
});
})
}
private fun initTextChangeListener() {
searchLocation_edt.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (searchLocation_edt.isFocused && !isLocationClicked) {
if (searchLocation_edt.text.toString().trim().length > 2) {
if (AppUtils.isOnline(mContext)) {
if (!mGoogleApiClient?.isConnected!!)
mGoogleApiClient?.connect()
fetchAddress(searchLocation_edt.text.toString().trim(), mGoogleApiClient)
} else {
(mContext as DashboardActivity).showSnackMessage(getString(R.string.no_data_available))
}
} else {
search_progress.visibility = View.GONE
locationAdapter?.refreshList(ArrayList<EditTextAddressModel>())
}
}
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {
}
})
}
fun fetchAddress(locText: String, mGoogleApiClient: GoogleApiClient?) {
search_progress.visibility = View.VISIBLE
AsyncGetLocation(mContext, locText, mGoogleApiClient, object : AsyncGetLocation.GetLocationListener {
override fun getLocationAddress(mListPlace: ArrayList<EditTextAddressModel>?) {
search_progress.visibility = View.GONE
if (searchLocation_edt.text.toString().trim().isNotEmpty()) {
rv_address_list.visibility = View.VISIBLE
locationAdapter?.refreshList(mListPlace)
rv_address_list.scrollToPosition(mListPlace?.size!!)
} else {
rv_address_list.visibility = View.GONE
}
//locationAdapter?.refreshList(mListPlace)
}
}).execute()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onClick(p0: View?) {
when (p0!!.id) {
R.id.searchLocation_edt -> {
searchLocation_edt.requestFocus()
isLocationClicked = false
}
R.id.cross_iv -> {
searchLocation_edt.setText("")
searchLocation_edt.requestFocus()
isLocationPicked = true
}
R.id.save_TV -> {
AppUtils.hideSoftKeyboard(mContext as DashboardActivity)
if (validate() || isLocationPicked)
sendLocationInfoToAddShop()
}
}
}
private fun validate(): Boolean {
if (searchLocation_edt.text.toString().trim() == "") {
(mContext as DashboardActivity).showSnackMessage(getString(R.string.blank_location))
return false
}
return true
}
private fun sendLocationInfoToAddShop() {
val mlocationInfoModel = locationInfoModel()
mlocationInfoModel.address = fullAdd
if (selectedLatitude.toString() == "")
mlocationInfoModel.latitude = latitude.toString()
else
mlocationInfoModel.latitude = selectedLatitude.toString()
if (selectedLongitude.toString() == "")
mlocationInfoModel.longitude = longitude.toString()
else
mlocationInfoModel.longitude = selectedLongitude.toString()
if (!TextUtils.isEmpty(pinCode))
mlocationInfoModel.pinCode = pinCode
if (!TextUtils.isEmpty(state))
mlocationInfoModel.state = state
if (!TextUtils.isEmpty(city))
mlocationInfoModel.city = city
if (!TextUtils.isEmpty(country))
mlocationInfoModel.country = country
(mContext as DashboardActivity).getLocationInfoModel(mlocationInfoModel)
(mContext as DashboardActivity).onBackPressed()
/*(mContext as DashboardActivity).onBackPressed()
(mContext as DashboardActivity).loadFragment(FragType.AddShopFragment, true, mlocationInfoModel)*/
}
override fun onDestroy() {
AppUtils.hideSoftKeyboard((mContext as DashboardActivity))
super.onDestroy()
mapView.onDestroy()
}
override fun onDestroyView() {
super.onDestroyView()
if (mGoogleApiClient != null) {
mGoogleApiClient?.stopAutoManage(activity!!)
mGoogleApiClient?.disconnect()
}
}
override fun onLocationItemClick(description: String, place_id: String) {
isLocationClicked = true
isLocationPicked = true
searchLocation_edt.setText(description)
fullAdd = description
rv_address_list.visibility = View.GONE
placeId = place_id
Places.GeoDataApi.getPlaceById(mGoogleApiClient!!, place_id).setResultCallback { places ->
if (places.status.isSuccess) {
try {
selectedLatitude = places.get(0).latLng.latitude
selectedLongitude = places.get(0).latLng.longitude
markerOptions?.position(places.get(0).latLng);
markerOptions?.title(description);
//googleMap?.clear();
val cameraPosition = CameraPosition.Builder().target(LatLng(selectedLatitude, selectedLongitude)).zoom(15f).build()
googleMap?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
if (currentLocationMarker != null)
currentLocationMarker?.remove()
currentLocationMarker = googleMap?.addMarker(markerOptions)!!
fetchCurrentAddress(selectedLatitude, selectedLongitude)
} catch (e: Exception) {
e.printStackTrace()
}
}
places.release()
}
}
override fun onConnected(p0: Bundle?) {
mLocationRequest = LocationRequest()
mLocationRequest?.interval = 1000
mLocationRequest?.fastestInterval = 1000
mLocationRequest?.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient?.isConnected!!) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this)
if (!TextUtils.isEmpty(Pref.latitude) && !TextUtils.isEmpty(Pref.longitude)) {
if (Pref.latitude != "0.0" && Pref.longitude != "0.0") {
val location = Location("")
location.latitude = Pref.latitude!!.toDouble()
location.longitude = Pref.longitude!!.toDouble()
LoadSaync(location, true)
} else
getLastKnownLocation()
} else {
getLastKnownLocation()
}
}
}
}
@SuppressLint("MissingPermission")
private fun getLastKnownLocation() {
val lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
if (lastLocation != null && lastLocation.latitude != null && lastLocation.latitude != 0.0) {
LoadSaync(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient), true)
}
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
}
override fun onLocationChanged(location: Location?) {
LoadSaync(location!!, false)
}
fun LoadSaync(mLocation: Location, isCameraAnimate: Boolean) {
try {
if (isLocationPicked)
return
location = mLocation
latitude = location.latitude
longitude = location.longitude
fetchCurrentAddress(latitude, longitude)
if (selectedLatitude != 0.0 && selectedLongitude != 0.0) {
if (selectedLatitude != latitude && selectedLongitude != longitude) {
} else {
val markerOptions: MarkerOptions = MarkerOptions();
markerOptions.position(LatLng(selectedLatitude, selectedLongitude));
markerOptions.title(fullAdd);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap?.addMarker(markerOptions);
if (isCameraAnimate) {
val cameraPosition = CameraPosition.Builder().target(LatLng(location.latitude, location.longitude)).zoom(15f).build()
googleMap?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}
} else {
if (isCameraAnimate) {
val cameraPosition = CameraPosition.Builder().target(LatLng(location.latitude, location.longitude)).zoom(15f).build()
googleMap?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun checkLocationPermission(): Boolean {
if (ContextCompat.checkSelfPermission(mContext,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(mContext as Activity,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(mContext as Activity,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION)
} else {
ActivityCompat.requestPermissions(mContext as Activity,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION)
}
return false
} else {
return true
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
MY_PERMISSIONS_REQUEST_LOCATION -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
InitiateMap()
} else {
checkLocationPermission()
}
return
}
}
}
private fun fetchCurrentAddress(latitude: Double, longitude: Double): String {
try {
geocoder = Geocoder(mContext, Locale.getDefault())
val addresses: List<android.location.Address> = geocoder?.getFromLocation(latitude, longitude, 1)!!;
if (addresses.isNotEmpty()) {
val address: Address = addresses[0];
fullAdd = address.getAddressLine(0);
if (addresses[0].adminArea != null)
state = addresses[0].adminArea
if (addresses[0].locality != null)
city = addresses[0].locality
if (addresses[0].countryName != null)
country = addresses[0].countryName
if (address.postalCode != null)
pinCode = address.postalCode
selectedLatitude = latitude
selectedLongitude = longitude
searchLocation_edt.setText(fullAdd)
}
} catch (ex: IOException) {
ex.printStackTrace();
}
return fullAdd;
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 24,966 | NationalPlastic | Apache License 2.0 |
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Peugeot.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36756847} | package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.Peugeot: ImageVector
get() {
if (_peugeot != null) {
return _peugeot!!
}
_peugeot = Builder(name = "Peugeot", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0001f, 0.0f)
curveToRelative(3.499f, 0.0f, 7.1308f, 0.2987f, 10.8171f, 0.9349f)
curveToRelative(0.055f, 1.4778f, 0.1175f, 3.762f, 0.0126f, 5.7004f)
curveToRelative(-0.2349f, 4.3217f, -1.1861f, 7.676f, -2.9943f, 10.5564f)
curveToRelative(-1.8026f, 2.872f, -4.5938f, 5.3416f, -7.8354f, 6.8083f)
curveToRelative(-3.2416f, -1.4667f, -6.0331f, -3.9362f, -7.8356f, -6.8083f)
curveToRelative(-1.808f, -2.8804f, -2.7594f, -6.2348f, -2.9941f, -10.5564f)
curveToRelative(-0.1053f, -1.9383f, -0.0427f, -4.2226f, 0.0124f, -5.7004f)
curveTo(4.8691f, 0.2987f, 8.5011f, 0.0f, 12.0001f, 0.0f)
close()
moveTo(12.0001f, 0.4163f)
curveToRelative(-3.4494f, 0.0f, -6.9514f, 0.2933f, -10.4139f, 0.8722f)
curveToRelative(-0.076f, 2.1923f, -0.076f, 3.9367f, -5.0E-4f, 5.3243f)
curveToRelative(0.2305f, 4.248f, 1.1619f, 7.5394f, 2.9309f, 10.3575f)
curveToRelative(1.7688f, 2.8179f, 4.421f, 5.1457f, 7.4835f, 6.5718f)
curveToRelative(3.0622f, -1.4261f, 5.7147f, -3.7539f, 7.4835f, -6.5718f)
curveToRelative(1.769f, -2.8182f, 2.7001f, -6.1095f, 2.9309f, -10.3575f)
curveToRelative(0.0755f, -1.3876f, 0.0755f, -3.132f, -5.0E-4f, -5.3243f)
curveTo(18.9515f, 0.7096f, 15.4493f, 0.4163f, 12.0001f, 0.4163f)
close()
moveTo(11.97f, 13.0361f)
reflectiveCurveToRelative(0.0681f, 0.4045f, 0.0888f, 0.5218f)
curveToRelative(0.0116f, 0.0665f, 0.0141f, 0.0843f, -0.0027f, 0.1495f)
curveToRelative(-0.0477f, 0.1695f, -0.3633f, 1.59f, -0.5385f, 2.6258f)
curveToRelative(-0.0822f, 0.4767f, -0.1533f, 0.9498f, -0.1947f, 1.3546f)
curveToRelative(-0.0234f, 0.23f, -0.0158f, 0.2851f, 0.0449f, 0.4892f)
curveToRelative(0.172f, 0.5767f, 0.8082f, 2.0834f, 0.9304f, 2.3581f)
arcToRelative(0.3288f, 0.3288f, 0.0f, false, true, 0.0257f, 0.0951f)
lineToRelative(0.0459f, 0.3553f)
curveToRelative(-0.2038f, -0.3081f, -1.3115f, -2.3458f, -1.7465f, -3.4742f)
curveToRelative(-0.0513f, -0.1329f, -0.0612f, -0.1984f, -0.0044f, -0.4428f)
curveToRelative(0.3025f, -1.2962f, 1.1211f, -3.4992f, 1.3511f, -4.0324f)
close()
moveTo(10.3547f, 9.9044f)
curveToRelative(0.0312f, 0.0913f, 0.2909f, 0.9805f, 0.3107f, 1.1919f)
curveToRelative(0.016f, 0.1174f, 0.0133f, 0.149f, -0.0284f, 0.2614f)
curveToRelative(-0.2276f, 0.606f, -0.9159f, 2.1129f, -1.1814f, 2.6161f)
curveToRelative(-0.059f, 0.1107f, -0.1145f, 0.1828f, -0.2256f, 0.2958f)
curveToRelative(-0.2535f, 0.2582f, -0.7386f, 0.7462f, -1.039f, 1.0192f)
curveToRelative(-0.1091f, 0.0993f, -0.1385f, 0.1841f, -0.1607f, 0.3126f)
curveToRelative(-0.0358f, 0.2063f, -0.0713f, 0.5584f, -0.0812f, 0.7402f)
curveToRelative(-0.0086f, 0.1599f, 0.0173f, 0.2347f, 0.1064f, 0.3931f)
curveToRelative(0.5294f, 0.9451f, 2.2966f, 3.1194f, 2.8001f, 3.576f)
curveToRelative(0.0365f, 0.0331f, 0.0632f, 0.0553f, 0.1402f, 0.1065f)
curveToRelative(0.074f, 0.0494f, 0.3154f, 0.2061f, 0.3154f, 0.2061f)
arcToRelative(0.085f, 0.085f, 0.0f, false, true, 0.0239f, 0.0257f)
lineToRelative(0.0874f, 0.1539f)
curveToRelative(-0.2256f, -0.1123f, -0.5874f, -0.2928f, -0.7742f, -0.3929f)
arcToRelative(0.7527f, 0.7527f, 0.0f, false, true, -0.1249f, -0.0845f)
curveToRelative(-0.5896f, -0.4902f, -2.3963f, -2.6064f, -2.9277f, -3.49f)
curveToRelative(-0.1325f, -0.2206f, -0.1461f, -0.292f, -0.1283f, -0.5008f)
curveToRelative(0.0333f, -0.3887f, 0.0849f, -0.8774f, 0.1301f, -1.0916f)
curveToRelative(0.0274f, -0.1292f, 0.0558f, -0.2051f, 0.1547f, -0.3192f)
curveToRelative(0.7533f, -0.8648f, 2.2059f, -2.7743f, 2.6293f, -3.5908f)
curveToRelative(0.0471f, -0.0924f, 0.0511f, -0.1245f, 0.0521f, -0.2117f)
curveToRelative(0.0027f, -0.253f, -0.078f, -0.7457f, -0.0992f, -0.8702f)
arcToRelative(0.2385f, 0.2385f, 0.0f, false, true, -0.0025f, -0.0591f)
lineToRelative(0.0228f, -0.2877f)
close()
moveTo(15.2857f, 9.4296f)
curveToRelative(0.0812f, 0.0377f, 0.2137f, 0.0801f, 0.2732f, 0.1502f)
curveToRelative(0.9366f, 0.9784f, 1.6856f, 1.9929f, 1.8356f, 2.2603f)
curveToRelative(0.0289f, 0.0514f, 0.0486f, 0.1028f, 0.0558f, 0.1616f)
curveToRelative(0.1683f, 1.4269f, 0.0237f, 2.9385f, -0.3201f, 4.2535f)
curveToRelative(-0.0311f, 0.1186f, -0.0659f, 0.1794f, -0.1799f, 0.2651f)
curveToRelative(-0.7607f, 0.5713f, -2.5689f, 2.0716f, -3.176f, 2.6297f)
arcToRelative(0.996f, 0.996f, 0.0f, false, false, -0.1718f, 0.2088f)
curveToRelative(-0.153f, 0.2511f, -0.3419f, 0.6012f, -0.462f, 0.825f)
curveToRelative(-0.1234f, -0.2696f, -0.3924f, -0.9273f, -0.4847f, -1.1931f)
curveToRelative(-0.0301f, -0.0867f, -0.0355f, -0.1322f, -0.0037f, -0.2483f)
curveToRelative(0.1505f, -0.5512f, 0.862f, -2.1538f, 1.0005f, -2.4436f)
curveToRelative(-0.0018f, 0.0372f, 0.0063f, 0.1347f, -0.0079f, 0.1693f)
curveToRelative(-0.0624f, 0.1895f, -0.445f, 1.4526f, -0.5227f, 2.0003f)
curveToRelative(-0.0173f, 0.1218f, -0.0158f, 0.1547f, 0.0f, 0.2743f)
curveToRelative(0.0341f, 0.2557f, 0.1868f, 0.7247f, 0.1868f, 0.7247f)
curveToRelative(0.0174f, -0.0414f, 0.1887f, -0.3836f, 0.309f, -0.4774f)
curveToRelative(0.7089f, -0.6984f, 2.1971f, -1.9725f, 3.0499f, -2.6638f)
curveToRelative(0.0958f, -0.0776f, 0.1315f, -0.1295f, 0.1528f, -0.2767f)
curveToRelative(0.1056f, -0.7254f, 0.1362f, -2.0275f, 0.0726f, -2.9751f)
arcToRelative(1.012f, 1.012f, 0.0f, false, false, -0.1708f, -0.5003f)
curveToRelative(-0.231f, -0.3417f, -0.5072f, -0.6651f, -0.926f, -1.0805f)
arcToRelative(0.4152f, 0.4152f, 0.0f, false, true, -0.1157f, -0.2187f)
curveToRelative(-0.1222f, -0.6524f, -0.3949f, -1.8453f, -0.3949f, -1.8453f)
close()
moveTo(7.3656f, 10.9387f)
arcToRelative(0.3306f, 0.3306f, 0.0f, false, true, 0.1794f, -0.0067f)
curveToRelative(0.267f, 0.0642f, 0.8322f, 0.2029f, 1.2594f, 0.3123f)
curveToRelative(0.06f, 0.0153f, 0.1347f, 0.0714f, 0.1666f, 0.1245f)
lineToRelative(0.093f, 0.1549f)
arcToRelative(0.1822f, 0.1822f, 0.0f, false, true, 0.0059f, 0.1774f)
arcToRelative(21.7947f, 21.7947f, 0.0f, false, true, -0.3055f, 0.5651f)
lineToRelative(-0.0886f, 0.1583f)
curveToRelative(-0.1631f, 0.2896f, -0.3254f, 0.5691f, -0.4176f, 0.7161f)
curveToRelative(-0.0607f, 0.0971f, -0.0945f, 0.1401f, -0.2026f, 0.1784f)
curveToRelative(-0.4203f, 0.148f, -0.9423f, 0.3249f, -1.2525f, 0.4255f)
curveToRelative(-0.0634f, 0.0205f, -0.0849f, 0.0591f, -0.0726f, 0.1295f)
curveToRelative(0.0222f, 0.1282f, 0.0938f, 0.5636f, 0.1212f, 0.6906f)
curveToRelative(0.0101f, 0.0469f, 0.0476f, 0.0843f, 0.1172f, 0.0709f)
curveToRelative(0.1834f, -0.0348f, 0.6715f, -0.1544f, 0.6715f, -0.1544f)
reflectiveCurveToRelative(-0.1439f, 0.1332f, -0.23f, 0.2117f)
arcToRelative(0.1456f, 0.1456f, 0.0f, false, true, -0.0545f, 0.0324f)
curveToRelative(-0.133f, 0.0445f, -0.4578f, 0.1356f, -0.559f, 0.1579f)
curveToRelative(-0.079f, 0.017f, -0.1293f, -0.0141f, -0.1496f, -0.1035f)
curveToRelative(0.0f, 0.0f, -0.1385f, -0.59f, -0.1885f, -0.7907f)
arcToRelative(1.552f, 1.552f, 0.0f, false, false, -0.0254f, -0.0872f)
curveToRelative(-0.0375f, -0.1161f, -0.1276f, -0.3444f, -0.1784f, -0.464f)
arcToRelative(0.108f, 0.108f, 0.0f, false, true, -0.0087f, -0.044f)
curveToRelative(0.0015f, -0.1366f, 0.0267f, -0.4415f, 0.0267f, -0.4415f)
reflectiveCurveToRelative(0.2989f, 0.2804f, 0.4435f, 0.3817f)
curveToRelative(0.0326f, 0.023f, 0.0521f, 0.0277f, 0.0921f, 0.0175f)
curveToRelative(0.1987f, -0.0511f, 0.6555f, -0.2024f, 0.9062f, -0.2962f)
arcToRelative(0.3475f, 0.3475f, 0.0f, false, false, 0.1463f, -0.1048f)
curveToRelative(0.2594f, -0.3135f, 0.5846f, -0.8013f, 0.7725f, -1.1692f)
arcToRelative(0.2194f, 0.2194f, 0.0f, false, false, 0.0146f, -0.1631f)
lineToRelative(-0.0405f, -0.1334f)
curveToRelative(-0.0118f, -0.039f, -0.0531f, -0.083f, -0.0911f, -0.0976f)
arcToRelative(34.0249f, 34.0249f, 0.0f, false, false, -1.1999f, -0.4329f)
lineToRelative(0.0489f, -0.0155f)
close()
moveTo(16.1072f, 7.1412f)
arcToRelative(0.407f, 0.407f, 0.0f, false, true, 0.2994f, 0.0069f)
curveToRelative(0.7409f, 0.3113f, 1.9867f, 1.0437f, 2.6792f, 1.5596f)
curveToRelative(0.0669f, 0.0499f, 0.0935f, 0.0843f, 0.1111f, 0.1648f)
curveToRelative(0.1626f, 0.7402f, 0.2243f, 1.8845f, 0.1219f, 2.8478f)
curveToRelative(-0.0074f, 0.0692f, -0.0212f, 0.1107f, -0.0573f, 0.1846f)
curveToRelative(-0.4388f, 0.8981f, -0.9326f, 1.7434f, -1.4524f, 2.3954f)
curveToRelative(0.0078f, -0.0807f, 0.0446f, -0.4617f, 0.0471f, -0.6834f)
arcToRelative(0.0765f, 0.0765f, 0.0f, false, true, 0.0304f, -0.0605f)
arcToRelative(9.0576f, 9.0576f, 0.0f, false, false, 0.304f, -0.2468f)
curveToRelative(0.0365f, -0.0316f, 0.0568f, -0.0553f, 0.0758f, -0.086f)
curveToRelative(0.2117f, -0.3425f, 0.5903f, -1.0595f, 0.7428f, -1.4909f)
arcToRelative(0.787f, 0.787f, 0.0f, false, false, 0.0429f, -0.3281f)
curveToRelative(-0.0489f, -0.6011f, -0.1431f, -1.434f, -0.2836f, -1.9776f)
arcToRelative(0.3337f, 0.3337f, 0.0f, false, false, -0.1703f, -0.2147f)
curveToRelative(-0.1212f, -0.0623f, -0.3588f, -0.1707f, -0.9f, -0.3879f)
arcToRelative(0.7631f, 0.7631f, 0.0f, false, true, -0.2068f, -0.1238f)
curveToRelative(-0.3549f, -0.2985f, -0.9097f, -0.7459f, -1.2549f, -1.0034f)
arcToRelative(0.4301f, 0.4301f, 0.0f, false, false, -0.3527f, -0.0749f)
arcToRelative(21.4993f, 21.4993f, 0.0f, false, false, -0.7517f, 0.1856f)
curveToRelative(-0.0612f, 0.0166f, -0.0854f, 0.018f, -0.1486f, 0.0106f)
curveToRelative(-0.1009f, -0.0117f, -0.3007f, -0.0275f, -0.382f, -0.0336f)
curveToRelative(0.5871f, -0.2761f, 1.152f, -0.5142f, 1.5057f, -0.6437f)
close()
moveTo(8.274f, 12.0001f)
curveToRelative(-0.1836f, 0.3024f, -0.403f, 0.6236f, -0.5689f, 0.8243f)
arcToRelative(0.1988f, 0.1988f, 0.0f, false, true, -0.0834f, 0.0588f)
arcToRelative(14.1489f, 14.1489f, 0.0f, false, true, -0.7063f, 0.2382f)
lineToRelative(1.3586f, -1.1213f)
close()
moveTo(5.8473f, 11.6031f)
lineToRelative(-0.1083f, 0.7484f)
lineToRelative(-0.3685f, -0.4329f)
curveToRelative(0.0671f, -0.1455f, 0.2633f, -0.2829f, 0.4768f, -0.3155f)
close()
moveTo(5.1607f, 9.9045f)
lineToRelative(-0.133f, 0.0838f)
curveToRelative(-0.0333f, 0.0212f, -0.0424f, 0.0304f, -0.0563f, 0.0595f)
arcToRelative(2.6968f, 2.6968f, 0.0f, false, true, -0.0856f, 0.1616f)
curveToRelative(-0.0091f, 0.0158f, -0.0336f, 0.0403f, -0.0466f, 0.0504f)
arcToRelative(16.6112f, 16.6112f, 0.0f, false, true, -0.4773f, 0.3533f)
curveToRelative(-0.0089f, 0.0062f, -0.0202f, 0.0035f, -0.0279f, -0.004f)
curveToRelative(-0.0165f, -0.0166f, -0.0859f, -0.0954f, -0.0982f, -0.1139f)
arcToRelative(0.0823f, 0.0823f, 0.0f, false, true, -0.0151f, -0.0489f)
arcToRelative(2.0329f, 2.0329f, 0.0f, false, true, 0.0062f, -0.1337f)
curveToRelative(0.0039f, -0.0509f, 0.0185f, -0.0751f, 0.0805f, -0.1394f)
curveToRelative(0.0693f, -0.0719f, 0.1449f, -0.1475f, 0.2243f, -0.2251f)
curveToRelative(0.1947f, -0.1641f, 0.6863f, -0.5633f, 1.5642f, -1.1904f)
arcToRelative(0.1927f, 0.1927f, 0.0f, false, false, 0.0437f, -0.0423f)
curveToRelative(0.0921f, -0.1244f, 0.354f, -0.4644f, 0.4186f, -0.5452f)
arcToRelative(0.1928f, 0.1928f, 0.0f, false, true, 0.0308f, -0.0311f)
arcToRelative(2.4849f, 2.4849f, 0.0f, false, true, 0.2595f, -0.1833f)
curveToRelative(0.2445f, -0.1542f, 0.7181f, -0.4354f, 0.9834f, -0.5898f)
lineToRelative(-0.1007f, 0.124f)
curveToRelative(-0.0056f, 0.0055f, -0.0111f, 0.0106f, -0.0167f, 0.0163f)
arcToRelative(42.2875f, 42.2875f, 0.0f, false, false, -0.5625f, 0.4314f)
curveToRelative(-0.0286f, 0.0227f, -0.04f, 0.0425f, -0.0466f, 0.0783f)
curveToRelative(-0.0227f, 0.1266f, -0.0605f, 0.367f, -0.0716f, 0.5001f)
curveToRelative(-0.0032f, 0.039f, -0.02f, 0.0583f, -0.0597f, 0.0744f)
curveToRelative(-0.173f, 0.0704f, -0.3781f, 0.1445f, -0.5439f, 0.211f)
curveToRelative(-0.0356f, 0.0141f, -0.0454f, 0.0195f, -0.0664f, 0.0356f)
curveToRelative(-0.0166f, 0.0128f, -0.2369f, 0.2098f, -0.2369f, 0.2098f)
reflectiveCurveToRelative(0.479f, -0.1181f, 0.6547f, -0.1579f)
curveToRelative(0.042f, -0.0094f, 0.06f, -0.0069f, 0.0987f, 0.0114f)
curveToRelative(0.0363f, 0.0168f, 0.0967f, 0.0408f, 0.1286f, 0.0524f)
curveToRelative(0.0489f, 0.018f, 0.0748f, 0.0172f, 0.1288f, 0.0054f)
curveToRelative(0.1979f, -0.0442f, 0.5308f, -0.1233f, 0.708f, -0.1695f)
curveToRelative(0.0921f, -0.024f, 0.1424f, -0.0489f, 0.2204f, -0.1035f)
curveToRelative(0.0849f, -0.0591f, 0.2999f, -0.2205f, 0.2999f, -0.2205f)
reflectiveCurveToRelative(-0.004f, 0.0285f, -0.0069f, 0.0443f)
arcToRelative(0.0591f, 0.0591f, 0.0f, false, true, -0.0161f, 0.0318f)
arcToRelative(3.986f, 3.986f, 0.0f, false, true, -0.1581f, 0.1777f)
curveToRelative(-0.0871f, 0.0902f, -0.1392f, 0.1223f, -0.2485f, 0.168f)
curveToRelative(-0.5035f, 0.21f, -1.3638f, 0.5362f, -2.0091f, 0.7598f)
curveToRelative(-0.0423f, 0.0148f, -0.0606f, 0.0269f, -0.0919f, 0.059f)
curveToRelative(-0.0341f, 0.0346f, -0.0795f, 0.085f, -0.0795f, 0.085f)
reflectiveCurveToRelative(0.5262f, 0.0383f, 0.6868f, 0.0568f)
curveToRelative(0.0521f, 0.0059f, 0.0893f, 0.023f, 0.1291f, 0.0573f)
curveToRelative(0.132f, 0.1137f, 0.5691f, 0.5641f, 0.6999f, 0.7205f)
curveToRelative(0.0f, 0.0f, -1.2426f, 0.2068f, -1.8184f, 0.3499f)
curveToRelative(-0.0711f, 0.0175f, -0.1066f, 0.0628f, -0.1227f, 0.1198f)
curveToRelative(-0.0476f, 0.1675f, -0.1599f, 0.7062f, -0.1599f, 0.7062f)
reflectiveCurveToRelative(-0.04f, -0.0128f, -0.0958f, -0.045f)
curveToRelative(-0.0383f, -0.022f, -0.0577f, -0.0403f, -0.0997f, -0.0847f)
curveToRelative(-0.1362f, -0.144f, -0.3601f, -0.4198f, -0.4677f, -0.5796f)
curveToRelative(-0.0316f, -0.0472f, -0.0449f, -0.1072f, -0.0054f, -0.1554f)
curveToRelative(0.1167f, -0.1438f, 0.3512f, -0.4062f, 0.4805f, -0.5411f)
curveToRelative(0.0138f, -0.0146f, 0.0313f, -0.04f, 0.0499f, -0.0766f)
curveToRelative(0.0498f, -0.1032f, 0.1038f, -0.3175f, 0.1282f, -0.4139f)
close()
moveTo(13.1824f, 7.0879f)
arcToRelative(0.1805f, 0.1805f, 0.0f, false, true, 0.1083f, 0.0148f)
lineToRelative(0.2564f, 0.1228f)
arcToRelative(0.0935f, 0.0935f, 0.0f, false, true, 0.0503f, 0.0628f)
curveToRelative(0.0348f, 0.1468f, 0.0775f, 0.3412f, 0.1061f, 0.5065f)
arcToRelative(0.2993f, 0.2993f, 0.0f, false, true, -0.036f, 0.1994f)
curveToRelative(-0.1061f, 0.1846f, -0.324f, 0.5166f, -0.446f, 0.695f)
curveToRelative(-0.0271f, 0.04f, -0.0304f, 0.0885f, -0.022f, 0.1361f)
curveToRelative(0.0553f, 0.3059f, 0.2858f, 1.374f, 0.2858f, 1.374f)
lineToRelative(-0.1451f, -0.1322f)
arcToRelative(0.2102f, 0.2102f, 0.0f, false, true, -0.0602f, -0.0917f)
curveToRelative(-0.1032f, -0.3022f, -0.2962f, -0.9335f, -0.385f, -1.2406f)
arcToRelative(0.1588f, 0.1588f, 0.0f, false, true, 0.0299f, -0.145f)
curveToRelative(0.1513f, -0.1838f, 0.3717f, -0.4778f, 0.5005f, -0.6641f)
curveToRelative(0.036f, -0.0524f, 0.0479f, -0.1102f, 0.0267f, -0.1534f)
arcToRelative(4.6142f, 4.6142f, 0.0f, false, false, -0.1273f, -0.2369f)
arcToRelative(0.1058f, 0.1058f, 0.0f, false, false, -0.0597f, -0.0489f)
lineToRelative(-0.174f, -0.0558f)
arcToRelative(0.1452f, 0.1452f, 0.0f, false, false, -0.093f, 0.0017f)
curveToRelative(-0.3791f, 0.1376f, -0.8889f, 0.336f, -1.2009f, 0.4655f)
curveToRelative(-0.0457f, 0.019f, -0.0644f, 0.0205f, -0.1197f, 0.0121f)
curveToRelative(-0.0903f, -0.0133f, -0.3534f, -0.0605f, -0.4825f, -0.0847f)
arcToRelative(0.0344f, 0.0344f, 0.0f, false, true, -0.023f, -0.0511f)
lineToRelative(0.153f, -0.2654f)
arcToRelative(0.1474f, 0.1474f, 0.0f, false, true, 0.0955f, -0.0704f)
curveToRelative(0.4922f, -0.1123f, 1.143f, -0.2413f, 1.7619f, -0.3505f)
close()
moveTo(7.7369f, 8.3065f)
arcToRelative(0.0544f, 0.0544f, 0.0f, false, true, 0.0548f, 0.0326f)
curveToRelative(0.0309f, 0.072f, 0.0225f, 0.1523f, -0.0074f, 0.2209f)
curveToRelative(-0.0116f, 0.028f, -0.0474f, 0.0551f, -0.0767f, 0.0616f)
lineToRelative(-0.2456f, 0.0546f)
arcToRelative(0.0227f, 0.0227f, 0.0f, false, true, -0.0274f, -0.0237f)
lineToRelative(0.023f, -0.2886f)
arcToRelative(0.04f, 0.04f, 0.0f, false, true, 0.0365f, -0.0366f)
lineToRelative(0.2428f, -0.0208f)
close()
moveTo(10.531f, 6.4522f)
arcToRelative(0.0366f, 0.0366f, 0.0f, false, true, 0.0321f, 0.0549f)
lineToRelative(-0.5987f, 1.032f)
arcToRelative(0.2643f, 0.2643f, 0.0f, false, true, -0.1552f, 0.126f)
lineToRelative(-1.1227f, 0.3516f)
arcToRelative(1.6503f, 1.6503f, 0.0f, false, true, -0.3761f, 0.0712f)
curveToRelative(-0.249f, 0.0188f, -0.9886f, 0.042f, -0.9886f, 0.042f)
lineToRelative(0.0162f, -0.0351f)
arcToRelative(0.0741f, 0.0741f, 0.0f, false, true, 0.038f, -0.0368f)
lineToRelative(0.35f, -0.1487f)
arcToRelative(0.169f, 0.169f, 0.0f, false, false, 0.0666f, -0.0502f)
lineToRelative(0.5405f, -0.6661f)
curveToRelative(0.0289f, -0.0356f, 0.0666f, -0.0697f, 0.1069f, -0.0909f)
curveToRelative(0.357f, -0.1881f, 0.992f, -0.4705f, 1.4368f, -0.6192f)
arcToRelative(0.5085f, 0.5085f, 0.0f, false, true, 0.1426f, -0.0235f)
lineToRelative(0.5116f, -0.0072f)
close()
moveTo(9.9308f, 5.2538f)
curveToRelative(1.2389f, -0.109f, 2.9153f, -0.1386f, 4.5168f, -0.0173f)
arcToRelative(0.837f, 0.837f, 0.0f, false, true, 0.2638f, 0.064f)
curveToRelative(0.5247f, 0.2209f, 1.4556f, 0.7042f, 2.4906f, 1.2969f)
arcToRelative(0.7764f, 0.7764f, 0.0f, false, true, 0.1281f, 0.0917f)
curveToRelative(0.2742f, 0.2419f, 0.9689f, 0.9535f, 0.9689f, 0.9535f)
lineToRelative(-0.2167f, -0.043f)
arcToRelative(0.2282f, 0.2282f, 0.0f, false, true, -0.0844f, -0.0351f)
curveToRelative(-0.4383f, -0.2948f, -1.0782f, -0.6785f, -1.6145f, -0.949f)
arcToRelative(0.5915f, 0.5915f, 0.0f, false, false, -0.2034f, -0.0598f)
arcToRelative(14.6895f, 14.6895f, 0.0f, false, false, -0.8443f, -0.0618f)
curveToRelative(-0.1138f, -0.0047f, -0.1913f, -0.0237f, -0.3026f, -0.0803f)
curveToRelative(-0.2127f, -0.108f, -0.728f, -0.342f, -0.9847f, -0.44f)
curveToRelative(-0.1098f, -0.042f, -0.1658f, -0.0519f, -0.2734f, -0.0502f)
curveToRelative(-0.441f, 0.0064f, -1.4457f, 0.0385f, -1.9588f, 0.0704f)
arcToRelative(0.2445f, 0.2445f, 0.0f, false, true, -0.0521f, -0.0025f)
lineToRelative(-0.2445f, -0.0383f)
curveToRelative(0.6935f, -0.1196f, 2.4077f, -0.2725f, 3.1172f, -0.3098f)
lineToRelative(-0.2887f, -0.0966f)
arcToRelative(0.596f, 0.596f, 0.0f, false, false, -0.1728f, -0.0299f)
curveToRelative(-0.9698f, -0.0218f, -2.3036f, -0.0178f, -3.4321f, 0.067f)
arcToRelative(0.6098f, 0.6098f, 0.0f, false, false, -0.2021f, 0.0504f)
curveToRelative(-0.3228f, 0.1419f, -1.11f, 0.5692f, -1.8994f, 1.0081f)
curveToRelative(-0.2546f, 0.1416f, -0.529f, 0.2952f, -0.7731f, 0.4326f)
curveToRelative(0.0f, 0.0f, 0.0985f, -0.1268f, 0.1175f, -0.1515f)
curveToRelative(0.0168f, -0.0215f, 0.0219f, -0.0255f, 0.0447f, -0.0403f)
curveToRelative(0.1018f, -0.0684f, 0.4109f, -0.2678f, 0.5343f, -0.3585f)
curveToRelative(0.2377f, -0.1794f, 0.6128f, -0.4956f, 0.8364f, -0.6916f)
arcToRelative(0.6677f, 0.6677f, 0.0f, false, false, 0.1288f, -0.1529f)
curveToRelative(0.0723f, -0.1171f, 0.1513f, -0.2441f, 0.1999f, -0.3145f)
curveToRelative(0.0414f, -0.0611f, 0.1123f, -0.1038f, 0.2006f, -0.1117f)
close()
moveTo(4.655f, 2.404f)
curveToRelative(0.306f, -0.0316f, 0.477f, 0.0875f, 0.477f, 0.3975f)
verticalLineToRelative(0.1715f)
curveToRelative(0.0f, 0.3172f, -0.171f, 0.4455f, -0.477f, 0.4774f)
arcToRelative(71.2552f, 71.2552f, 0.0f, false, false, -1.269f, 0.144f)
verticalLineToRelative(0.4687f)
curveToRelative(-0.0886f, 0.0109f, -0.1774f, 0.0218f, -0.266f, 0.0331f)
lineTo(3.12f, 2.5814f)
arcToRelative(70.6625f, 70.6625f, 0.0f, false, true, 1.535f, -0.1774f)
close()
moveTo(18.8582f, 2.3549f)
arcToRelative(71.245f, 71.245f, 0.0f, false, true, 2.022f, 0.2263f)
verticalLineToRelative(0.2444f)
arcToRelative(68.7666f, 68.7666f, 0.0f, false, false, -0.8741f, -0.105f)
verticalLineToRelative(1.2707f)
arcToRelative(94.0383f, 94.0383f, 0.0f, false, false, -0.2663f, -0.0299f)
lineTo(19.7398f, 2.6906f)
arcToRelative(68.3322f, 68.3322f, 0.0f, false, false, -0.8815f, -0.0914f)
verticalLineToRelative(-0.2443f)
close()
moveTo(7.6494f, 2.1558f)
verticalLineToRelative(0.2441f)
arcToRelative(71.8527f, 71.8527f, 0.0f, false, false, -1.6641f, 0.1223f)
verticalLineToRelative(0.3731f)
arcToRelative(68.5725f, 68.5725f, 0.0f, false, true, 1.48f, -0.1107f)
verticalLineToRelative(0.2444f)
arcToRelative(70.5409f, 70.5409f, 0.0f, false, false, -1.48f, 0.1104f)
verticalLineToRelative(0.4094f)
arcToRelative(69.7002f, 69.7002f, 0.0f, false, true, 1.6641f, -0.1223f)
verticalLineToRelative(0.2441f)
arcToRelative(70.9377f, 70.9377f, 0.0f, false, false, -1.9245f, 0.145f)
verticalLineToRelative(-1.515f)
arcToRelative(70.5346f, 70.5346f, 0.0f, false, true, 1.9245f, -0.1448f)
close()
moveTo(16.282f, 2.5707f)
curveToRelative(0.0f, -0.3397f, 0.1683f, -0.4097f, 0.5476f, -0.384f)
curveToRelative(0.3332f, 0.023f, 0.6658f, 0.0479f, 0.9988f, 0.0756f)
curveToRelative(0.3295f, 0.0272f, 0.5469f, 0.1198f, 0.5469f, 0.4665f)
verticalLineToRelative(0.6765f)
curveToRelative(0.0f, 0.3402f, -0.1878f, 0.4015f, -0.5469f, 0.3719f)
arcToRelative(72.5525f, 72.5525f, 0.0f, false, false, -0.9988f, -0.0754f)
curveToRelative(-0.3628f, -0.0245f, -0.5476f, -0.0946f, -0.5476f, -0.4546f)
verticalLineToRelative(-0.6765f)
close()
moveTo(13.7008f, 2.0423f)
curveToRelative(0.6426f, 0.0153f, 1.285f, 0.0395f, 1.9274f, 0.0726f)
verticalLineToRelative(0.2441f)
arcToRelative(70.7366f, 70.7366f, 0.0f, false, false, -1.6666f, -0.0657f)
verticalLineToRelative(0.3728f)
curveToRelative(0.4943f, 0.0139f, 0.9884f, 0.0327f, 1.4823f, 0.0567f)
verticalLineToRelative(0.2444f)
arcToRelative(70.4407f, 70.4407f, 0.0f, false, false, -1.4822f, -0.0566f)
verticalLineToRelative(0.4092f)
arcToRelative(69.1564f, 69.1564f, 0.0f, false, true, 1.6666f, 0.066f)
verticalLineToRelative(0.2441f)
arcToRelative(71.29f, 71.29f, 0.0f, false, false, -1.9274f, -0.0726f)
verticalLineToRelative(-1.515f)
close()
moveTo(10.3568f, 2.041f)
verticalLineToRelative(1.0958f)
curveToRelative(0.0f, 0.3467f, -0.1819f, 0.4228f, -0.5484f, 0.4341f)
arcToRelative(68.0289f, 68.0289f, 0.0f, false, false, -0.9573f, 0.0361f)
curveToRelative(-0.3401f, 0.0153f, -0.5479f, -0.0494f, -0.5479f, -0.3926f)
lineTo(8.3032f, 2.1186f)
lineToRelative(0.2606f, -0.0133f)
verticalLineToRelative(1.142f)
curveToRelative(0.0f, 0.0694f, 0.0595f, 0.126f, 0.1385f, 0.1223f)
arcToRelative(70.1195f, 70.1195f, 0.0f, false, true, 1.2547f, -0.0475f)
curveToRelative(0.0795f, -0.0022f, 0.1323f, -0.063f, 0.1323f, -0.1324f)
verticalLineToRelative(-1.142f)
curveToRelative(0.089f, -0.0025f, 0.1781f, -0.0047f, 0.2675f, -0.0067f)
close()
moveTo(16.6813f, 2.4212f)
curveToRelative(-0.0792f, -0.0054f, -0.1387f, 0.0502f, -0.1387f, 0.1295f)
verticalLineToRelative(0.7491f)
curveToRelative(0.0f, 0.0694f, 0.0595f, 0.1423f, 0.1387f, 0.1478f)
curveToRelative(0.4321f, 0.0287f, 0.8638f, 0.0613f, 1.2954f, 0.0978f)
curveToRelative(0.0691f, 0.0059f, 0.1382f, -0.0576f, 0.1382f, -0.1268f)
verticalLineToRelative(-0.7493f)
curveToRelative(0.0f, -0.0791f, -0.0691f, -0.1445f, -0.1382f, -0.1505f)
arcToRelative(70.1864f, 70.1864f, 0.0f, false, false, -1.2954f, -0.0976f)
close()
moveTo(11.5092f, 2.0236f)
curveToRelative(0.479f, -0.0035f, 0.958f, -0.0017f, 1.4368f, 0.0047f)
verticalLineToRelative(0.2441f)
arcToRelative(72.1473f, 72.1473f, 0.0f, false, false, -1.536f, -0.004f)
curveToRelative(-0.0693f, 7.0E-4f, -0.1387f, 0.0608f, -0.1387f, 0.1302f)
verticalLineToRelative(0.759f)
curveToRelative(0.0f, 0.0694f, 0.0693f, 0.1381f, 0.1387f, 0.1374f)
curveToRelative(0.4593f, -0.004f, 0.9183f, -0.0032f, 1.3776f, 0.002f)
verticalLineToRelative(-0.4094f)
arcToRelative(66.592f, 66.592f, 0.0f, false, false, -0.7994f, -0.0042f)
verticalLineToRelative(-0.2443f)
curveToRelative(0.3534f, 0.0f, 0.7068f, 0.0027f, 1.0602f, 0.0079f)
verticalLineToRelative(0.8976f)
arcToRelative(71.1228f, 71.1228f, 0.0f, false, false, -1.4896f, -0.0064f)
curveToRelative(-0.3635f, 0.0025f, -0.5484f, -0.0603f, -0.5484f, -0.4136f)
verticalLineToRelative(-0.6602f)
curveToRelative(0.0f, -0.3299f, 0.1651f, -0.4383f, 0.4988f, -0.4408f)
close()
moveTo(4.7546f, 2.6398f)
lineToRelative(-0.0206f, 4.0E-4f)
arcToRelative(70.2289f, 70.2289f, 0.0f, false, false, -1.348f, 0.1522f)
lineTo(3.386f, 3.35f)
arcToRelative(71.0344f, 71.0344f, 0.0f, false, true, 1.348f, -0.152f)
curveToRelative(0.0689f, -0.0074f, 0.138f, -0.0704f, 0.138f, -0.1364f)
verticalLineToRelative(-0.3068f)
curveToRelative(0.0f, -0.0694f, -0.0691f, -0.1218f, -0.138f, -0.1146f)
lineToRelative(0.0206f, -4.0E-4f)
close()
}
}
.build()
return _peugeot!!
}
private var _peugeot: ImageVector? = null
| 15 | Kotlin | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 31,404 | compose-icons | MIT License |
client-android/app/src/main/java/stasis/client_android/StasisClientDependencies.kt | sndnv | 153,169,374 | false | {"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516} | package stasis.client_android
import stasis.client_android.lib.ops.backup.Providers as BackupProviders
import stasis.client_android.lib.ops.recovery.Providers as RecoveryProviders
import android.app.Application
import android.content.SharedPreferences
import android.os.HandlerThread
import android.os.Process
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import stasis.client_android.lib.analysis.Checksum
import stasis.client_android.lib.api.clients.CachedServerApiEndpointClient
import stasis.client_android.lib.api.clients.Clients
import stasis.client_android.lib.api.clients.DefaultServerApiEndpointClient
import stasis.client_android.lib.api.clients.DefaultServerBootstrapEndpointClient
import stasis.client_android.lib.api.clients.DefaultServerCoreEndpointClient
import stasis.client_android.lib.api.clients.ServerBootstrapEndpointClient
import stasis.client_android.lib.compression.Compression
import stasis.client_android.lib.compression.Gzip
import stasis.client_android.lib.encryption.Aes
import stasis.client_android.lib.model.DatasetMetadata
import stasis.client_android.lib.model.server.datasets.DatasetDefinition
import stasis.client_android.lib.model.server.datasets.DatasetDefinitionId
import stasis.client_android.lib.model.server.datasets.DatasetEntry
import stasis.client_android.lib.model.server.datasets.DatasetEntryId
import stasis.client_android.lib.model.server.devices.Device
import stasis.client_android.lib.model.server.devices.DeviceId
import stasis.client_android.lib.model.server.schedules.Schedule
import stasis.client_android.lib.model.server.users.User
import stasis.client_android.lib.model.server.users.UserId
import stasis.client_android.lib.ops.backup.Backup
import stasis.client_android.lib.ops.monitoring.DefaultServerMonitor
import stasis.client_android.lib.ops.scheduling.DefaultOperationExecutor
import stasis.client_android.lib.ops.search.DefaultSearch
import stasis.client_android.lib.security.CredentialsProvider
import stasis.client_android.lib.security.DefaultOAuthClient
import stasis.client_android.lib.security.HttpCredentials
import stasis.client_android.lib.staging.DefaultFileStaging
import stasis.client_android.lib.utils.Cache
import stasis.client_android.lib.utils.Reference
import stasis.client_android.persistence.cache.DatasetEntryCacheFileSerdes
import stasis.client_android.persistence.cache.DatasetMetadataCacheFileSerdes
import stasis.client_android.persistence.config.ConfigRepository.Companion.getAuthenticationConfig
import stasis.client_android.persistence.config.ConfigRepository.Companion.getServerApiConfig
import stasis.client_android.persistence.config.ConfigRepository.Companion.getServerCoreConfig
import stasis.client_android.providers.ProviderContext
import stasis.client_android.security.Secrets
import stasis.client_android.settings.Settings.getPingInterval
import stasis.client_android.tracking.DefaultBackupTracker
import stasis.client_android.tracking.DefaultRecoveryTracker
import stasis.client_android.tracking.DefaultServerTracker
import stasis.client_android.tracking.DefaultTrackers
import stasis.client_android.tracking.TrackerViews
import java.time.Duration
import java.util.UUID
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object StasisClientDependencies {
private val providerContextReference: AtomicReference<Reference<ProviderContext>> =
AtomicReference(Reference.empty())
@Singleton
@Provides
fun provideDispatcherIO(): CoroutineDispatcher = Dispatchers.IO
@Singleton
@Provides
fun provideServerBootstrapEndpointClientFactory(): ServerBootstrapEndpointClient.Factory =
object : ServerBootstrapEndpointClient.Factory {
override fun create(server: String): ServerBootstrapEndpointClient =
DefaultServerBootstrapEndpointClient(
serverBootstrapUrl = server
)
}
@Singleton
@Provides
fun provideDefaultTrackers(application: Application): DefaultTrackers {
val trackerHandler = HandlerThread(
"DefaultTracker",
Process.THREAD_PRIORITY_BACKGROUND
).apply { start() }
return DefaultTrackers(
backup = DefaultBackupTracker(application.applicationContext, trackerHandler.looper),
recovery = DefaultRecoveryTracker(application.applicationContext, trackerHandler.looper),
server = DefaultServerTracker(trackerHandler.looper)
)
}
@Singleton
@Provides
fun provideTrackerView(trackers: DefaultTrackers): TrackerViews =
TrackerViews(
backup = trackers.backup,
recovery = trackers.recovery,
server = trackers.server
)
@Singleton
@Provides
fun provideProviderContextFactory(
dispatcher: CoroutineDispatcher,
trackers: DefaultTrackers,
trackerViews: TrackerViews,
datasetDefinitionsCache: Cache<DatasetDefinitionId, DatasetDefinition>,
datasetEntriesCache: Cache<DatasetEntryId, DatasetEntry>,
datasetMetadataCache: Cache<DatasetEntryId, DatasetMetadata>
): ProviderContext.Factory =
object : ProviderContext.Factory {
override fun getOrCreate(preferences: SharedPreferences): Reference<ProviderContext> =
providerContextReference.updateAndGet {
it.singleton(
retrieveConfig = {
preferences.getAuthenticationConfig()?.let { authenticationConfig ->
preferences.getServerCoreConfig()?.let { coreConfig ->
preferences.getServerApiConfig()?.let { apiConfig ->
Triple(authenticationConfig, coreConfig, apiConfig)
}
}
}
},
create = { (authenticationConfig, coreConfig, apiConfig) ->
val coroutineScope = CoroutineScope(dispatcher)
val user: UserId = UUID.fromString(apiConfig.user)
val userSalt: String = apiConfig.userSalt
val device: DeviceId = UUID.fromString(apiConfig.device)
val credentials = CredentialsProvider(
config = CredentialsProvider.Config(
coreScope = authenticationConfig.scopeCore,
apiScope = authenticationConfig.scopeApi,
expirationTolerance = Defaults.CredentialsExpirationTolerance
),
oAuthClient = DefaultOAuthClient(
tokenEndpoint = authenticationConfig.tokenEndpoint,
client = authenticationConfig.clientId,
clientSecret = authenticationConfig.clientSecret
),
initDeviceSecret = { secret ->
Secrets.initDeviceSecret(
user = user,
device = device,
secret = secret,
preferences = preferences
)
},
loadDeviceSecret = { userPassword ->
Secrets.loadDeviceSecret(
user = user,
userSalt = userSalt,
userPassword = <PASSWORD>,
device = device,
preferences = preferences
)
},
storeDeviceSecret = { secret, userPassword ->
Secrets.storeDeviceSecret(
user = user,
userSalt = userSalt,
userPassword = <PASSWORD>,
device = device,
secret = secret,
preferences = preferences
)
},
getAuthenticationPassword = { userPassword ->
Secrets.loadUserAuthenticationPassword(
user = user,
userSalt = userSalt,
userPassword = <PASSWORD>,
preferences = preferences
)
},
coroutineScope = coroutineScope
)
val coreClient = DefaultServerCoreEndpointClient(
serverCoreUrl = coreConfig.address,
credentials = { HttpCredentials.OAuth2BearerToken(token = credentials.core.get().access_token) },
self = UUID.fromString(coreConfig.nodeId)
)
val apiClient = CachedServerApiEndpointClient(
underlying = DefaultServerApiEndpointClient(
serverApiUrl = apiConfig.url,
credentials = { HttpCredentials.OAuth2BearerToken(token = credentials.api.get().access_token) },
decryption = DefaultServerApiEndpointClient.DecryptionContext(
core = coreClient,
deviceSecret = { credentials.deviceSecret.get() },
decoder = Aes
),
self = device
),
datasetDefinitionsCache = datasetDefinitionsCache,
datasetEntriesCache = datasetEntriesCache,
datasetMetadataCache = datasetMetadataCache
)
val search = DefaultSearch(
api = apiClient
)
val encryption = Aes
val compression = Compression(
withDefaultCompression = Gzip,
withDisabledExtensions = setOf(
"3gp", "mp4", "m4a", "aac", "ts", "amr",
"flac", "mid", "xmf", "mxmf", "mp3", "mkv",
"ogg", "wav", "webm", "bmp", "gif", "jpg",
"jpeg", "png", "webp", "heic", "heif"
)
)
val checksum = Checksum.Companion.SHA256
val staging = DefaultFileStaging(
storeDirectory = null, // no explicit directory
prefix = "", // no prefix
suffix = "" // no suffix
)
val clients = Clients(api = apiClient, core = coreClient)
val executor = DefaultOperationExecutor(
config = DefaultOperationExecutor.Config(
backup = DefaultOperationExecutor.Config.Backup(
limits = Backup.Descriptor.Limits(maxPartSize = Defaults.MaxBackupPartSize)
)
),
deviceSecret = { credentials.deviceSecret.get() },
backupProviders = BackupProviders(
checksum = checksum,
staging = staging,
compression = compression,
encryptor = encryption,
decryptor = encryption,
clients = clients,
track = trackers.backup,
),
recoveryProviders = RecoveryProviders(
checksum = checksum,
staging = staging,
compression = compression,
decryptor = encryption,
clients = clients,
track = trackers.recovery
),
operationDispatcher = dispatcher
)
val monitor = DefaultServerMonitor(
initialDelay = Duration.ofSeconds(5),
interval = preferences.getPingInterval(),
api = apiClient,
tracker = trackers.server,
scope = coroutineScope
)
ProviderContext(
core = coreClient,
api = apiClient,
search = search,
executor = executor,
trackers = trackerViews,
credentials = credentials,
monitor = monitor
)
},
destroy = { context -> context?.credentials?.logout() }
)
}
}
@Singleton
@Provides
fun provideDatasetDefinitionsCache(): Cache<DatasetDefinitionId, DatasetDefinition> =
inMemoryCache()
@Singleton
@Provides
fun provideDatasetEntriesCache(
application: Application
): Cache<DatasetEntryId, DatasetEntry> =
persistedCache(name = "dataset_entries", application = application, serdes = DatasetEntryCacheFileSerdes)
@Singleton
@Provides
fun provideDatasetMetadataCache(
application: Application
): Cache<DatasetEntryId, DatasetMetadata> =
persistedCache(name = "dataset_metadata", application = application, serdes = DatasetMetadataCacheFileSerdes)
@Singleton
@Provides
fun provideUserRefreshingCache(
dispatcher: CoroutineDispatcher
): Cache.Refreshing<Int, User> =
refreshingCache(dispatcher, interval = Defaults.UserRefreshInterval)
@Singleton
@Provides
fun provideDeviceRefreshingCache(
dispatcher: CoroutineDispatcher
): Cache.Refreshing<Int, Device> =
refreshingCache(dispatcher, interval = Defaults.DeviceRefreshInterval)
@Singleton
@Provides
fun provideSchedulesRefreshingCache(
dispatcher: CoroutineDispatcher
): Cache.Refreshing<Int, List<Schedule>> =
refreshingCache(dispatcher, interval = Defaults.SchedulesRefreshInterval)
private fun <K : Any, V> inMemoryCache(): Cache<K, V> =
Cache.Map()
private fun <K : Any, V> refreshingCache(
dispatcher: CoroutineDispatcher,
interval: Duration
): Cache.Refreshing<K, V> =
Cache.Refreshing(
underlying = Cache.Map(),
interval = interval,
scope = CoroutineScope(dispatcher)
)
private fun <K : Any, V> persistedCache(
name: String,
application: Application,
serdes: Cache.File.Serdes<K, V>
): Cache<K, V> =
Cache.File(
target = application.applicationContext.cacheDir.toPath().resolve(name),
serdes = serdes
)
object Defaults {
const val MaxBackupPartSize: Long = 32L * 1024L * 1024L // 128MB
val UserRefreshInterval: Duration = Duration.ofMinutes(5)
val DeviceRefreshInterval: Duration = Duration.ofMinutes(5)
val SchedulesRefreshInterval: Duration = Duration.ofMinutes(5)
val CredentialsExpirationTolerance: Duration = Duration.ofSeconds(15)
}
}
| 1 | Scala | 4 | 53 | d7b3002880814039b332b3d5373a16b57637eb1e | 17,043 | stasis | Apache License 2.0 |
app/src/main/java/com/seif/booksislandapp/presentation/home/categories/book_categories/BookCategoriesFragment.kt | SeifEldinMohamed | 570,587,114 | false | null | package com.seif.booksislandapp.presentation.home.categories.book_categories
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.seif.booksislandapp.R
import com.seif.booksislandapp.databinding.FragmentBookCategoriesBinding
import com.seif.booksislandapp.domain.model.book.BookCategory
import com.seif.booksislandapp.presentation.home.categories.ItemCategoryViewModel
import com.seif.booksislandapp.presentation.home.categories.book_categories.adapter.BookCategoriesAdapter
import com.seif.booksislandapp.presentation.home.categories.book_categories.adapter.OnCategoryItemClick
class BookCategoriesFragment : Fragment(), OnCategoryItemClick<BookCategory> {
lateinit var binding: FragmentBookCategoriesBinding
private val bookCategoriesAdapter: BookCategoriesAdapter by lazy { BookCategoriesAdapter() }
private val itemCategoryViewModel: ItemCategoryViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentBookCategoriesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.ivBack.setOnClickListener {
findNavController().navigateUp()
}
bookCategoriesAdapter.onCategoryItemClick = this
binding.rvBookCategories.adapter = bookCategoriesAdapter
bookCategoriesAdapter.submitList(createBookCategoriesList())
}
private fun createBookCategoriesList(): ArrayList<BookCategory> {
return arrayListOf(
BookCategory(name = "Literature", R.color.literature_color),
BookCategory(name = "Historical", R.color.historical_color),
BookCategory(name = "Religious", R.color.religious_color),
BookCategory(name = "Scientific", R.color.scientific_color),
BookCategory(name = "Political", R.color.political_color),
BookCategory(name = "Money and Business", R.color.money_business_color),
BookCategory(name = "Self Development", R.color.self_development_color),
BookCategory(name = "Comics", R.color.comics_color),
BookCategory(name = "Psychology", R.color.psychology_color),
BookCategory(name = "Biography", R.color.biography_color),
BookCategory(name = "Philosophy", R.color.philosophy_color),
BookCategory(name = "Language", R.color.language_color),
BookCategory(name = "Law", R.color.law_color),
BookCategory(name = "Press and Media", R.color.press_and_media_color),
BookCategory(name = "Medicine and Health", R.color.medicine_and_health_color),
BookCategory(name = "Technology", R.color.technology_color),
BookCategory(name = "Arts", R.color.arts_color),
BookCategory(name = "Sports", R.color.sports_color),
BookCategory(name = "Travel", R.color.travel_color),
BookCategory(name = "References and Research", R.color.reference_and_research_color),
BookCategory(name = "Family and Child", R.color.family_and_child_color),
BookCategory(name = "Cooks", R.color.cook_color)
)
}
override fun onCategoryItemClick(bookCategory: BookCategory) {
// val bundle = Bundle()
// bundle.putString("category_name", bookCategory.name)
// findNavController().navigate(R)
itemCategoryViewModel.selectItem(bookCategory.name)
findNavController().navigateUp()
}
} | 1 | Kotlin | 0 | 0 | 91cf4e2aeb3032305c61382a36eae95b44e058c0 | 3,902 | Books-Island-App | Apache License 2.0 |
app/src/main/java/br/com/github/ui/common/liveData/LiveDataSingleEvent.kt | petersongfarias | 642,393,181 | false | null | package br.com.github.ui.common.liveData
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
class LiveDataSingleEvent<T> : MutableLiveData<T>() {
private val mPending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
if (hasActiveObservers()) {
Timber.d(TAG, "Multiple observers registered but only one will be notified of changes.")
}
// Observe the internal MutableLiveData
super.observe(owner) {
if (mPending.compareAndSet(true, false)) {
observer.onChanged(it)
}
}
}
@MainThread
override fun setValue(t: T?) {
mPending.set(true)
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
value = null
}
companion object {
private const val TAG = "SingleLiveEvent"
}
}
| 0 | Kotlin | 0 | 0 | 845820dd6030199458efbf9ed4116a7a7ca315a1 | 1,150 | GitApp | Apache License 2.0 |
src/commonMain/kotlin/mahjongutils/hora/Hora.kt | ssttkkl | 547,654,890 | false | null | @file:OptIn(ExperimentalSerializationApi::class)
package mahjongutils.hora
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import mahjongutils.hanhu.ChildPoint
import mahjongutils.hanhu.ParentPoint
import mahjongutils.hanhu.getChildPointByHanHu
import mahjongutils.hanhu.getParentPointByHanHu
import mahjongutils.models.Furo
import mahjongutils.models.Tile
import mahjongutils.models.Wind
import mahjongutils.models.hand.HoraHandPattern
import mahjongutils.shanten.ShantenResult
import mahjongutils.shanten.ShantenWithGot
import mahjongutils.shanten.shanten
import mahjongutils.yaku.Yaku
import mahjongutils.yaku.Yakus
/**
* 和牌分析结果
*/
@Serializable
data class Hora internal constructor(
/**
* 和牌形
*/
val pattern: HoraHandPattern,
/**
* 宝牌数目
*/
val dora: Int,
/**
* 额外役种
*/
val extraYaku: Set<Yaku>,
) : HoraInfo by pattern {
/**
* 役种
*/
@EncodeDefault
val yaku: Set<Yaku> = buildSet {
if (pattern.menzen) {
addAll(Yakus.allYakuman.filter { it.check(pattern) })
} else {
addAll(Yakus.allYakuman.filter { !it.menzenOnly && it.check(pattern) })
}
addAll(extraYaku.filter { it.isYakuman })
if (isEmpty()) {
// 非役满情况才判断其他役种
if (pattern.menzen) {
addAll(Yakus.allCommonYaku.filter { it.check(pattern) })
} else {
addAll(Yakus.allCommonYaku.filter { !it.menzenOnly && it.check(pattern) })
}
addAll(extraYaku.filter { !it.isYakuman })
}
}
/**
* 是否含役满役种
*/
@EncodeDefault
val hasYakuman: Boolean = yaku.any { it.isYakuman }
/**
* 番
*/
@EncodeDefault
val han: Int = run {
var ans = if (pattern.menzen) {
yaku.sumOf { it.han }
} else {
yaku.sumOf { it.han - it.furoLoss }
}
if (ans > 0 && !hasYakuman) {
ans += dora
}
ans
}
/**
* 亲家(庄家)和牌点数
*/
val parentPoint: ParentPoint
get() = if (han == 0) {
ParentPoint(0, 0)
} else if (hasYakuman) {
val times = yaku.filter { it.isYakuman }.sumOf { it.han / 13 }
val ans = getParentPointByHanHu(13, 20)
ParentPoint(ans.ron * times, ans.tsumo * times)
} else {
getParentPointByHanHu(han, hu)
}
/**
* 子家(闲家)和牌点数
*/
val childPoint: ChildPoint
get() = if (han == 0) {
ChildPoint(0, 0, 0)
} else if (hasYakuman) {
val times = yaku.filter { it.isYakuman }.sumOf { it.han / 13 }
val ans = getChildPointByHanHu(13, 20)
ChildPoint(ans.ron * times, ans.tsumoParent * times, ans.tsumoChild * times)
} else {
getChildPointByHanHu(han, hu)
}
}
/**
* 和牌分析
*
* @param tiles 门前的牌
* @param furo 副露
* @param agari 和牌张
* @param tsumo 是否自摸
* @param dora 宝牌数目
* @param selfWind 自风
* @param roundWind 场风
* @param extraYaku 额外役种
* @return 和牌分析结果
*/
fun hora(
tiles: List<Tile>, furo: List<Furo> = emptyList(), agari: Tile, tsumo: Boolean,
dora: Int = 0, selfWind: Wind? = null, roundWind: Wind? = null, extraYaku: Set<Yaku> = emptySet()
): Hora {
val k = tiles.size / 3 + furo.size
if (k != 4) {
throw IllegalArgumentException("invalid length of tiles")
}
val shantenResult = shanten(tiles, furo, false)
return hora(shantenResult, agari, tsumo, dora, selfWind, roundWind, extraYaku)
}
/**
* 和牌分析
*
* @param shantenResult 向听分析结果
* @param agari 和牌张
* @param tsumo 是否自摸
* @param dora 宝牌数目
* @param selfWind 自风
* @param roundWind 场风
* @param extraYaku 额外役种
* @return 和牌分析结果
*/
fun hora(
shantenResult: ShantenResult, agari: Tile, tsumo: Boolean,
dora: Int = 0, selfWind: Wind? = null, roundWind: Wind? = null, extraYaku: Set<Yaku> = emptySet()
): Hora {
if (shantenResult.shantenInfo !is ShantenWithGot) {
throw IllegalArgumentException("shantenInfo is not with got")
}
if (shantenResult.shantenInfo.shantenNum != -1) {
throw IllegalArgumentException("shantenNum != -1")
}
val patterns = buildList {
if (shantenResult.regular?.shantenInfo?.shantenNum == -1) {
addAll(shantenResult.regular.hand.patterns)
}
if (shantenResult.chitoi?.shantenInfo?.shantenNum == -1) {
addAll(shantenResult.chitoi.hand.patterns)
}
if (shantenResult.kokushi?.shantenInfo?.shantenNum == -1) {
addAll(shantenResult.kokushi.hand.patterns)
}
}
val possibleHora = patterns.map { pat ->
HoraHandPattern.build(pat, agari, tsumo, selfWind, roundWind).map { horaHandPat ->
Hora(horaHandPat, dora, extraYaku)
}
}.flatten()
val hora = possibleHora.maxBy {
it.han * 1000 + it.pattern.hu // first key: han, second key: hu
}
return hora
} | 0 | Kotlin | 0 | 4 | 256395761c45294cf1f385f4f95df82cc886993c | 5,061 | mahjong-utils | MIT License |
support/hibernate-reactive/src/main/kotlin/com/linecorp/kotlinjdsl/support/hibernate/reactive/extension/StageStatelessSessionExtensions.kt | line | 442,633,985 | false | null | package com.linecorp.kotlinjdsl.support.hibernate.reactive.extension
import com.linecorp.kotlinjdsl.SinceJdsl
import com.linecorp.kotlinjdsl.querymodel.jpql.delete.DeleteQuery
import com.linecorp.kotlinjdsl.querymodel.jpql.select.SelectQuery
import com.linecorp.kotlinjdsl.querymodel.jpql.update.UpdateQuery
import com.linecorp.kotlinjdsl.render.RenderContext
import com.linecorp.kotlinjdsl.support.hibernate.reactive.JpqlStageSessionUtils
import org.hibernate.reactive.stage.Stage
/**
* Creates a [Stage.Query] from the [SelectQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: SelectQuery<T>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, query.returnType, context)
/**
* Creates a [Stage.Query] from the [SelectQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: SelectQuery<T>,
queryParams: Map<String, Any?>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, queryParams, query.returnType, context)
/**
* Creates a [Stage.Query] from the [UpdateQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: UpdateQuery<T>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, context)
/**
* Creates a [Stage.Query] from the [UpdateQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: UpdateQuery<T>,
queryParams: Map<String, Any?>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, queryParams, context)
/**
* Creates a [Stage.Query] from the [DeleteQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: DeleteQuery<T>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, context)
/**
* Creates a [Stage.Query] from the [DeleteQuery] and [RenderContext].
*/
@SinceJdsl("3.0.0")
fun <T : Any> Stage.Session.createQuery(
query: DeleteQuery<T>,
queryParams: Map<String, Any?>,
context: RenderContext,
): Stage.Query<T> = JpqlStageSessionUtils.createQuery(this, query, queryParams, context)
| 7 | null | 86 | 705 | 3a58ff84b1c91bbefd428634f74a94a18c9b76fd | 2,298 | kotlin-jdsl | Apache License 2.0 |
example/composeApp/src/commonMain/kotlin/presentation/ui/home/HomeScreen.kt | KryptonReborn | 803,884,694 | false | {"Kotlin": 207738, "Swift": 594, "HTML": 323} | package presentation.ui.home
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import presentation.ui.home.viewmodel.HomeEvent
import presentation.ui.home.viewmodel.HomeState
import presentation.ui.result.viewmodel.ResultEvent
@Composable
fun HomeScreen(
state: HomeState,
events: (HomeEvent) -> Unit,
navigateToResult: (id: String) -> Unit,
) {
Scaffold {
LazyColumn(modifier = Modifier.fillMaxSize()) {
item {
Text(
text = "Health Api",
style = TextStyle(fontSize = 26.sp, fontWeight = FontWeight.Bold),
)
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetApiRoot.id) }) {
Text("Get Api Root")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetHealth.id) }) {
Text("Get Health")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetCurrentBackendTime.id) }) {
Text("Get Current Backend Time")
}
}
item {
Text(
text = "Metrics Api",
style = TextStyle(fontSize = 26.sp, fontWeight = FontWeight.Bold),
)
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetMetrics.id) }) {
Text("Get Metrics")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetMetricEndpoints.id) }) {
Text("Get Metric Endpoints")
}
}
item {
Text(
text = "Cardano Account Api",
style = TextStyle(fontSize = 26.sp, fontWeight = FontWeight.Bold),
)
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccount.id) }) {
Text("Get Account")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountAddressesAsset.id) }) {
Text("Get Account Addresses Asset")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountAddresses.id) }) {
Text("Get Account Addresses")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountAddressesTotal.id) }) {
Text("Get Account Addresses Total")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountDelegations.id) }) {
Text("Get Account Delegations")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountHistory.id) }) {
Text("Get Account History")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountMirs.id) }) {
Text("Get Account Mirs")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountRegistrations.id) }) {
Text("Get Account Registrations")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountRewards.id) }) {
Text("Get Account Rewards")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAccountWithdrawals.id) }) {
Text("Get Account Withdrawals")
}
}
item {
Text(
text = "Cardano Address Api",
style = TextStyle(fontSize = 26.sp, fontWeight = FontWeight.Bold),
)
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetSpecificAddress.id) }) {
Text("Get Specific Address")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetSpecificAddressExtended.id) }) {
Text("Get Specific Address Extended")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAddressDetail.id) }) {
Text("Get Address Detail")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAddressUtxos.id) }) {
Text("Get Address Utxos")
}
}
item {
Text(
text = "Assets Api",
style = TextStyle(fontSize = 26.sp, fontWeight = FontWeight.Bold),
)
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssets.id) }) {
Text("Get Assets")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetSpecificAsset.id) }) {
Text("Get Specific Asset")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssetHistory.id) }) {
Text("Get Asset History")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssetTxs.id) }) {
Text("Get Asset Txs")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssetTransactions.id) }) {
Text("Get Asset Transactions")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssetAddresses.id) }) {
Text("Get Asset Addresses")
}
}
item {
TextButton(onClick = { navigateToResult(ResultEvent.GetAssetPolicy.id) }) {
Text("Get Asset Policy")
}
}
}
}
}
| 1 | Kotlin | 1 | 1 | 11d6d7f09b2e0d157bb91398b4b53a38f564677e | 6,886 | blockfrost-kotlin-sdk | Apache License 2.0 |
src/test/kotlin/care/better/platform/web/template/converter/raw/context/setter/LinkContextSetterTest.kt | better-care | 343,549,109 | false | null | /* Copyright 2021 Better Ltd (www.better.care)
*
* 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 care.better.platform.web.template.converter.raw.context.setter
import care.better.platform.web.template.converter.raw.context.ConversionContext
import care.better.platform.web.template.converter.value.SimpleValueConverter
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.openehr.rm.datatypes.DvCodedText
/**
* @author <NAME>
* @since 3.1.0
*/
class LinkContextSetterTest {
@Test
fun testSingle() {
val conversionContextBuilder = ConversionContext.create()
LinkCtxSetter.set(conversionContextBuilder, SimpleValueConverter, mapOf(Pair("|type", "type"), Pair("|meaning", "meaning"), Pair("|target", "target")))
assertThat(conversionContextBuilder.getLinks()).hasSize(1)
assertThat(conversionContextBuilder.getLinks()[0].type?.value).isEqualTo("type")
assertThat(conversionContextBuilder.getLinks()[0].meaning?.value).isEqualTo("meaning")
assertThat(conversionContextBuilder.getLinks()[0].target?.value).isEqualTo("target")
}
@Test
fun testSingleCoded() {
val conversionContextBuilder = ConversionContext.create()
LinkCtxSetter.set(
conversionContextBuilder,
SimpleValueConverter,
mapOf(Pair("|type", "tterm::tcode::type"), Pair("|meaning", "mterm::mcode::meaning"), Pair("|target", "target")))
assertThat(conversionContextBuilder.getLinks()).hasSize(1)
assertThat(conversionContextBuilder.getLinks()[0].type?.value).isEqualTo("type")
assertThat((conversionContextBuilder.getLinks()[0].type as DvCodedText).definingCode?.codeString).isEqualTo("tcode")
assertThat((conversionContextBuilder.getLinks()[0].type as DvCodedText).definingCode?.terminologyId?.value).isEqualTo("tterm")
assertThat(conversionContextBuilder.getLinks()[0].meaning?.value).isEqualTo("meaning")
assertThat((conversionContextBuilder.getLinks()[0].meaning as DvCodedText).definingCode?.codeString).isEqualTo("mcode")
assertThat((conversionContextBuilder.getLinks()[0].meaning as DvCodedText).definingCode?.terminologyId?.value).isEqualTo("mterm")
assertThat(conversionContextBuilder.getLinks()[0].target?.value).isEqualTo("target")
}
@Test
fun testMultipleCoded() {
val conversionContextBuilder = ConversionContext.create()
LinkCtxSetter.set(
conversionContextBuilder,
SimpleValueConverter,
listOf(
mapOf(Pair("|type", "11tterm::11tcode::type"), Pair("|meaning", "11mterm::11mcode::meaning"), Pair("|target", "target11")),
mapOf(Pair("|type", "type0"), Pair("|meaning", "meaning0"), Pair("|target", "target0"))))
assertThat(conversionContextBuilder.getLinks()).hasSize(2)
assertThat(conversionContextBuilder.getLinks()[0].type?.value).isEqualTo("type")
assertThat((conversionContextBuilder.getLinks()[0].type as DvCodedText).definingCode?.codeString).isEqualTo("11tcode")
assertThat((conversionContextBuilder.getLinks()[0].type as DvCodedText).definingCode?.terminologyId?.value).isEqualTo("11tterm")
assertThat(conversionContextBuilder.getLinks()[0].meaning?.value).isEqualTo("meaning")
assertThat((conversionContextBuilder.getLinks()[0].meaning as DvCodedText).definingCode?.codeString).isEqualTo("11mcode")
assertThat((conversionContextBuilder.getLinks()[0].meaning as DvCodedText).definingCode?.terminologyId?.value).isEqualTo("11mterm")
assertThat(conversionContextBuilder.getLinks()[0].target?.value).isEqualTo("target11")
assertThat(conversionContextBuilder.getLinks()[1].type?.value).isEqualTo("type0")
assertThat(conversionContextBuilder.getLinks()[1].meaning?.value).isEqualTo("meaning0")
assertThat(conversionContextBuilder.getLinks()[1].target?.value).isEqualTo("target0")
}
}
| 0 | Kotlin | 1 | 1 | 4aa47c5c598be6687dc2c095b1f7fcee49702a28 | 4,506 | web-template | Apache License 2.0 |
app/src/main/java/id/krafterstudio/androidarch/infrastructure/data/note/NoteApi.kt | sjarifHD | 161,516,916 | false | null | package id.krafterstudio.androidarch.infrastructure.data.note
import io.reactivex.Completable
import io.reactivex.Flowable
import retrofit2.http.GET
import retrofit2.http.POST
/**
* Created by sjarifhd on 11/12/18.
* Innovation, eFishery
*/
interface NoteApi {
@GET("notes")
fun getNotes(): Flowable<MutableList<NoteRemote>>
@POST("notes")
fun addNote(note: NoteRemote): Completable
companion object {
private const val URL = "https://expressnote.herokuapp.com/"
}
} | 0 | Kotlin | 0 | 1 | cb3942140b978cdcd28fd15edbcbc5c70e2872ba | 505 | AndroidArch | The Unlicense |
lab_assignments/MortgageCalculator/app/src/main/java/com/android/cecs453/mortgagecalculator/Prefs.kt | neoNite77 | 593,476,822 | false | null | package com.android.cecs453.mortgagecalculator
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.util.Log
class Prefs (context1: Context) {
private var context: Context? = context1
private var amount:Float=200000.0f
private var years: Int =15
private var rate: Float =0.035f
fun setPreferences(mort: Mortgage) {
var s: SharedPreferences? =
context!!.getSharedPreferences("Mortgage", Context.MODE_PRIVATE)
var editor = s?.edit()
if (editor != null) {
editor.putFloat(Mortgage.PREFERENCE_AMOUNT, mort.getAmount())
}
if (editor != null) {
editor.putInt(Mortgage.PREFERENCE_YEARS, mort.getYears())
}
// if (editor != null) {
// editor.putFloat(Mortgage.PREFERENCE_RATE, mort.getRate())
// }
editor?.putFloat(Mortgage.PREFERENCE_RATE, mort.getRate())
editor?.commit()
}
fun getPreferences(mort: Mortgage)
{
var s: SharedPreferences? = PreferenceManager.getDefaultSharedPreferences(context)
//var s: SharedPreferences? =
if (s != null) {
mort.setYears(s.getInt(Mortgage.PREFERENCE_YEARS, 30))
mort.setAmount(s.getFloat(Mortgage.PREFERENCE_AMOUNT, 100000.0f))
mort.setRate(s.getFloat(Mortgage.PREFERENCE_RATE, 0.035f))
}
}
}
| 0 | Kotlin | 0 | 0 | a706a171051da6d7a0a53d41f26a713c21ac0ff4 | 1,430 | android_kotlin | Apache License 2.0 |
økonomi/infrastructure/src/test/kotlin/økonomi/infrastructure/kvittering/consumer/lokal/LokalKvitteringJobTest.kt | navikt | 227,366,088 | false | {"Kotlin": 9236522, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800} | package økonomi.infrastructure.kvittering.consumer.lokal
import arrow.core.nonEmptyListOf
import arrow.core.right
import io.kotest.matchers.shouldBe
import no.nav.su.se.bakover.common.Rekkefølge
import no.nav.su.se.bakover.common.UUID30
import no.nav.su.se.bakover.common.domain.Saksnummer
import no.nav.su.se.bakover.common.domain.sak.Sakstype
import no.nav.su.se.bakover.common.extensions.januar
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.person.Fnr
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.common.tid.periode.januar
import no.nav.su.se.bakover.domain.grunnlag.Uføregrad
import no.nav.su.se.bakover.domain.oppdrag.Utbetaling
import no.nav.su.se.bakover.domain.oppdrag.Utbetalingslinje
import no.nav.su.se.bakover.domain.oppdrag.Utbetalingsrequest
import no.nav.su.se.bakover.domain.oppdrag.avstemming.Avstemmingsnøkkel
import no.nav.su.se.bakover.domain.oppdrag.utbetaling.UtbetalingRepo
import no.nav.su.se.bakover.domain.søknadsbehandling.IverksattSøknadsbehandling
import no.nav.su.se.bakover.service.utbetaling.UtbetalingService
import no.nav.su.se.bakover.service.vedtak.FerdigstillVedtakService
import no.nav.su.se.bakover.test.argThat
import no.nav.su.se.bakover.test.fixedClock
import no.nav.su.se.bakover.test.fixedTidspunkt
import no.nav.su.se.bakover.test.generer
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import økonomi.domain.kvittering.Kvittering
import økonomi.domain.simulering.Simulering
import økonomi.domain.simulering.SimulertMåned
import økonomi.infrastructure.kvittering.consumer.UtbetalingKvitteringConsumer
import java.time.LocalDate
import java.util.UUID
internal class LokalKvitteringJobTest {
private val tidspunkt = fixedTidspunkt
private val fnr = Fnr.generer()
private val utbetaling = Utbetaling.UtbetalingForSimulering(
id = UUID30.randomUUID(),
opprettet = tidspunkt,
sakId = UUID.randomUUID(),
saksnummer = Saksnummer(2021),
fnr = fnr,
utbetalingslinjer = nonEmptyListOf(
Utbetalingslinje.Ny(
id = UUID30.randomUUID(),
opprettet = Tidspunkt.EPOCH,
fraOgMed = 1.januar(2021),
tilOgMed = 31.januar(2021),
forrigeUtbetalingslinjeId = null,
beløp = 0,
uføregrad = Uføregrad.parse(50),
rekkefølge = Rekkefølge.start(),
),
),
behandler = NavIdentBruker.Attestant("attestant"),
avstemmingsnøkkel = Avstemmingsnøkkel(Tidspunkt.EPOCH),
sakstype = Sakstype.UFØRE,
).toSimulertUtbetaling(
simulering = Simulering(
gjelderId = fnr,
gjelderNavn = "ubrukt",
datoBeregnet = LocalDate.now(fixedClock),
nettoBeløp = 0,
måneder = listOf(SimulertMåned(måned = januar(2021))),
rawResponse = "LokalKvitterinJobTest baserer ikke denne på rå XML.",
),
).toOversendtUtbetaling(
oppdragsmelding = Utbetalingsrequest(value = ""),
)
private val kvittering = Kvittering(
utbetalingsstatus = Kvittering.Utbetalingsstatus.OK,
originalKvittering = "unused",
mottattTidspunkt = tidspunkt,
)
@Test
fun `lokalt kvittering jobb persisterer og ferdigstiller innvilgelse`() {
val utbetalingRepoMock = mock<UtbetalingRepo> {
on { hentUkvitterteUtbetalinger() } doReturn listOf(utbetaling)
}
val utbetalingMedKvittering = utbetaling.toKvittertUtbetaling(
kvittering = kvittering,
)
val utbetalingServiceMock = mock<UtbetalingService> {
on { oppdaterMedKvittering(any(), any(), anyOrNull()) } doReturn utbetalingMedKvittering.right()
}
val innvilgetSøknadsbehandling = mock<IverksattSøknadsbehandling.Innvilget> {}
val ferdigstillVedtakServiceMock = mock<FerdigstillVedtakService> {
on { ferdigstillVedtakEtterUtbetaling(any()) } doReturn Unit.right()
}
val utbetalingKvitteringConsumer = UtbetalingKvitteringConsumer(
utbetalingService = utbetalingServiceMock,
ferdigstillVedtakService = ferdigstillVedtakServiceMock,
clock = fixedClock,
)
LokalKvitteringService(utbetalingRepoMock, utbetalingKvitteringConsumer).run()
verify(utbetalingRepoMock).hentUkvitterteUtbetalinger()
verify(utbetalingServiceMock).oppdaterMedKvittering(
utbetalingId = argThat { it shouldBe utbetaling.id },
kvittering = argThat { it shouldBe kvittering.copy(originalKvittering = it.originalKvittering) },
sessionContext = anyOrNull(),
)
verify(ferdigstillVedtakServiceMock).ferdigstillVedtakEtterUtbetaling(
argThat { it shouldBe utbetalingMedKvittering },
)
verifyNoMoreInteractions(
utbetalingRepoMock,
utbetalingServiceMock,
ferdigstillVedtakServiceMock,
innvilgetSøknadsbehandling,
)
}
}
| 4 | Kotlin | 1 | 1 | ed28832346c1f839ea3a489eae8cc623079a0a2f | 5,292 | su-se-bakover | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Messageremove.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Messageremove: ImageVector
get() {
if (_messageremove != null) {
return _messageremove!!
}
_messageremove = Builder(name = "Messageremove", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.97f, 14.83f)
curveTo(7.25f, 14.01f, 6.18f, 13.5f, 5.0f, 13.5f)
curveTo(2.79f, 13.5f, 1.0f, 15.29f, 1.0f, 17.5f)
curveTo(1.0f, 18.25f, 1.21f, 18.96f, 1.58f, 19.56f)
curveTo(1.78f, 19.9f, 2.04f, 20.21f, 2.34f, 20.47f)
curveTo(3.04f, 21.11f, 3.97f, 21.5f, 5.0f, 21.5f)
curveTo(6.46f, 21.5f, 7.73f, 20.72f, 8.42f, 19.56f)
curveTo(8.79f, 18.96f, 9.0f, 18.25f, 9.0f, 17.5f)
curveTo(9.0f, 16.48f, 8.61f, 15.54f, 7.97f, 14.83f)
close()
moveTo(6.6f, 19.08f)
curveTo(6.45f, 19.23f, 6.26f, 19.3f, 6.07f, 19.3f)
curveTo(5.88f, 19.3f, 5.69f, 19.23f, 5.54f, 19.08f)
lineTo(5.01f, 18.55f)
lineTo(4.46f, 19.1f)
curveTo(4.31f, 19.25f, 4.12f, 19.32f, 3.93f, 19.32f)
curveTo(3.74f, 19.32f, 3.55f, 19.25f, 3.4f, 19.1f)
curveTo(3.11f, 18.81f, 3.11f, 18.33f, 3.4f, 18.04f)
lineTo(3.95f, 17.49f)
lineTo(3.42f, 16.96f)
curveTo(3.13f, 16.67f, 3.13f, 16.19f, 3.42f, 15.9f)
curveTo(3.71f, 15.61f, 4.19f, 15.61f, 4.48f, 15.9f)
lineTo(5.01f, 16.43f)
lineTo(5.51f, 15.93f)
curveTo(5.8f, 15.64f, 6.28f, 15.64f, 6.57f, 15.93f)
curveTo(6.86f, 16.22f, 6.86f, 16.7f, 6.57f, 16.99f)
lineTo(6.07f, 17.49f)
lineTo(6.6f, 18.02f)
curveTo(6.89f, 18.31f, 6.89f, 18.78f, 6.6f, 19.08f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.25f, 2.4297f)
horizontalLineTo(7.75f)
curveTo(4.9f, 2.4297f, 3.0f, 4.3297f, 3.0f, 7.1797f)
verticalLineTo(11.6397f)
curveTo(3.0f, 11.9897f, 3.36f, 12.2397f, 3.7f, 12.1497f)
curveTo(4.12f, 12.0497f, 4.55f, 11.9997f, 5.0f, 11.9997f)
curveTo(7.86f, 11.9997f, 10.22f, 14.3197f, 10.48f, 17.1297f)
curveTo(10.5f, 17.4097f, 10.73f, 17.6297f, 11.0f, 17.6297f)
horizontalLineTo(11.55f)
lineTo(15.78f, 20.4497f)
curveTo(16.4f, 20.8697f, 17.25f, 20.4097f, 17.25f, 19.6497f)
verticalLineTo(17.6297f)
curveTo(18.67f, 17.6297f, 19.86f, 17.1497f, 20.69f, 16.3297f)
curveTo(21.52f, 15.4897f, 22.0f, 14.2997f, 22.0f, 12.8797f)
verticalLineTo(7.1797f)
curveTo(22.0f, 4.3297f, 20.1f, 2.4297f, 17.25f, 2.4297f)
close()
moveTo(15.83f, 10.8097f)
horizontalLineTo(9.17f)
curveTo(8.78f, 10.8097f, 8.46f, 10.4897f, 8.46f, 10.0997f)
curveTo(8.46f, 9.6997f, 8.78f, 9.3797f, 9.17f, 9.3797f)
horizontalLineTo(15.83f)
curveTo(16.22f, 9.3797f, 16.54f, 9.6997f, 16.54f, 10.0997f)
curveTo(16.54f, 10.4897f, 16.22f, 10.8097f, 15.83f, 10.8097f)
close()
}
}
.build()
return _messageremove!!
}
private var _messageremove: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 4,719 | VuesaxIcons | MIT License |
playground/app/src/main/kotlin/io/github/composegears/valkyrie/playground/icons/lazy/outlined/Add.kt | ComposeGears | 778,162,113 | false | {"Kotlin": 777429} | package io.github.composegears.valkyrie.playground.icons.lazy.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.composegears.valkyrie.playground.icons.lazy.LazyIcons
val LazyIcons.Outlined.Add: ImageVector by lazy(LazyThreadSafetyMode.NONE) {
ImageVector.Builder(
name = "Outlined.Add",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f,
).apply {
path(fill = SolidColor(Color(0xFF232F34))) {
moveTo(19f, 13f)
lineTo(13f, 13f)
lineTo(13f, 19f)
lineTo(11f, 19f)
lineTo(11f, 13f)
lineTo(5f, 13f)
lineTo(5f, 11f)
lineTo(11f, 11f)
lineTo(11f, 5f)
lineTo(13f, 5f)
lineTo(13f, 11f)
lineTo(19f, 11f)
lineTo(19f, 13f)
close()
}
}.build()
}
| 27 | Kotlin | 6 | 321 | f0647081b15b907ad92b38c33eb62179ffd0f969 | 1,110 | Valkyrie | Apache License 2.0 |
lib/src/main/java/net/opatry/ticktick/entity/TaskUpdateRequest.kt | opatry | 739,177,691 | false | null | /*
* Copyright (c) 2024 Olivier Patry
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.opatry.ticktick.entity
import com.google.gson.annotations.SerializedName
/**
* @property projectId Project id.
* @property id Task id.
* @property title Task title
* @property content Task content
* @property desc Description of checklist
* @property isAllDay All day
* @property startDate Start date and time in `"yyyy-MM-dd'T'HH:mm:ssZ"` format **Example:** `"2019-11-13T03:00:00+0000"`
* @property dueDate Due date and time in `"yyyy-MM-dd'T'HH:mm:ssZ"` format **Example:** `"2019-11-13T03:00:00+0000"`
* @property timeZone The time zone in which the time is specified
* @property reminders Lists of reminders specific to the task
* @property repeatFlag Recurring rules of task
* @property priority The priority of task, default is "0"
* @property sortOrder The order of task
* @property items The list of subtasks
*/
data class TaskUpdateRequest(
@SerializedName("projectId")
val projectId: String,
@SerializedName("id")
val id: String,
@SerializedName("title")
val title: String? = null,
@SerializedName("content")
val content: String? = null,
@SerializedName("desc")
val desc: String? = null,
@SerializedName("isAllDay")
val isAllDay: Boolean? = null,
@SerializedName("startDate")
val startDate: String? = null,
@SerializedName("dueDate")
val dueDate: String? = null,
@SerializedName("timeZone")
val timeZone: String? = null,
@SerializedName("reminders")
val reminders: List<String>? = null,
@SerializedName("repeatFlag")
val repeatFlag: String? = null,
@SerializedName("priority")
val priority: Task.Priority? = null,
@SerializedName("sortOrder")
val sortOrder: Long? = null,
@SerializedName("items")
val items: List<ChecklistItemEdit>? = null,
)
| 0 | null | 0 | 2 | be4a41bb293395fb6ae0db7709462b8551c41171 | 2,929 | ticktick-kt | MIT License |
fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/WrapWithSafeLetCallFixFactories.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix.fixes
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.*
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.receiverType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicator
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KotlinApplicatorBasedQuickFix
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory
import org.jetbrains.kotlin.idea.core.FirKotlinNameSuggester
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.types.expressions.OperatorConventions
object WrapWithSafeLetCallFixFactories {
class Input(
val nullableExpressionPointer: SmartPsiElementPointer<KtExpression>,
val suggestedVariableName: String,
val isImplicitInvokeCallToMemberProperty: Boolean,
) : KotlinApplicatorInput
private val LOG = Logger.getInstance(this::class.java)
/**
* Applicator that wraps a given target expression inside a `let` call on the input `nullableExpression`.
*
* Consider the following code snippet:
*
* ```
* fun test(s: String?) {
* println(s.length)
* }
* ```
*
* In this case, one use the applicator with the following arguments
* - target expression: `s.length`
* - nullable expression: `s`
* - suggestedVariableName: `myName`
* - isImplicitInvokeCallToMemberProperty: false
*
* Then the applicator changes the code to
*
* ```
* fun test(s: String?) {
* println(s?.let { myName -> myName.length })
* }
* ```
* `isImplicitInvokeCallToMemberProperty` controls the behavior when hoisting up the nullable expression. It should be set to true
* if the call is to a invocable member property.
*/
private val applicator: KotlinApplicator<KtExpression, Input> = applicator {
familyAndActionName(KotlinBundle.lazyMessage("wrap.with.let.call"))
applyTo { targetExpression, input ->
val nullableExpression = input.nullableExpressionPointer.element ?: return@applyTo
if (!nullableExpression.parents.contains(targetExpression)) {
LOG.warn(
"Unexpected input for WrapWithSafeLetCall. Nullable expression '${nullableExpression.text}' should be a descendant" +
" of '${targetExpression.text}'."
)
return@applyTo
}
val suggestedVariableName = input.suggestedVariableName
val psiFactory = KtPsiFactory(targetExpression.project)
fun getNewExpression(nullableExpressionText: String, expressionUnderLetText: String): KtExpression {
return when (suggestedVariableName) {
"it" -> psiFactory.createExpressionByPattern("$0?.let { $1 }", nullableExpressionText, expressionUnderLetText)
else -> psiFactory.createExpressionByPattern(
"$0?.let { $1 -> $2 }",
nullableExpressionText,
suggestedVariableName,
expressionUnderLetText
)
}
}
val callExpression = nullableExpression.parentOfType<KtCallExpression>(withSelf = true)
val qualifiedExpression = callExpression?.getQualifiedExpressionForSelector()
val receiverExpression = qualifiedExpression?.receiverExpression
if (receiverExpression != null && input.isImplicitInvokeCallToMemberProperty) {
// In this case, the nullable expression is an invocable member. For example consider the following
//
// interface Foo {
// val bar: (() -> Unit)?
// }
// fun test(foo: Foo) {
// foo.bar()
// }
//
// In this case, `foo.bar` is nullable and this fix should change the code to `foo.bar?.let { it() }`. But note that
// the PSI structure of the above code is
//
// - qualifiedExpression: foo.bar()
// - receiver: foo
// - operationTokenNode: .
// - selectorExpression: bar()
// - calleeExpression: bar
// - valueArgumentList: ()
//
// So we need to explicitly construct the nullable expression text `foo.bar`.
val nullableExpressionText =
"${receiverExpression.text}${qualifiedExpression.operationSign.value}${nullableExpression.text}"
val newInvokeCallText =
"${suggestedVariableName}${callExpression.valueArgumentList?.text ?: ""}${
callExpression.lambdaArguments.joinToString(
" ",
prefix = " "
) { it.text }
}"
if (qualifiedExpression == targetExpression) {
targetExpression.replace(getNewExpression(nullableExpressionText, newInvokeCallText))
} else {
qualifiedExpression.replace(psiFactory.createExpression(newInvokeCallText))
targetExpression.replace(getNewExpression(nullableExpressionText, targetExpression.text))
}
} else {
val nullableExpressionText = when (nullableExpression) {
is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS -> "(${nullableExpression.text})"
else -> nullableExpression.text
}
nullableExpression.replace(psiFactory.createExpression(suggestedVariableName))
targetExpression.replace(getNewExpression(nullableExpressionText, targetExpression.text))
}
}
}
val forUnsafeCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeCall::class) { diagnostic ->
val nullableExpression = diagnostic.receiverExpression
createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(nullableExpression)
}
val forUnsafeImplicitInvokeCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeImplicitInvokeCall::class) { diagnostic ->
val callExpression = diagnostic.psi.parentOfType<KtCallExpression>(withSelf = true) ?: return@diagnosticFixFactory emptyList()
val callingFunctionalVariableInLocalScope =
isCallingFunctionalTypeVariableInLocalScope(callExpression) ?: return@diagnosticFixFactory emptyList()
createWrapWithSafeLetCallInputForNullableExpression(
callExpression.calleeExpression,
isImplicitInvokeCallToMemberProperty = !callingFunctionalVariableInLocalScope
)
}
private fun KtAnalysisSession.isCallingFunctionalTypeVariableInLocalScope(callExpression: KtCallExpression): Boolean? {
val calleeExpression = callExpression.calleeExpression
val calleeName = calleeExpression?.text ?: return null
val callSite = callExpression.parent as? KtQualifiedExpression ?: callExpression
val functionalVariableSymbol = (calleeExpression.resolveCall()?.singleCallOrNull<KtSimpleVariableAccessCall>())?.symbol ?: return false
val localScope = callExpression.containingKtFile.getScopeContextForPosition(callSite).getCompositeScope()
// If no symbol in the local scope contains the called symbol, then the symbol must be a member symbol.
return localScope.getCallableSymbols { it.identifierOrNullIfSpecial == calleeName }.any { it == functionalVariableSymbol }
}
val forUnsafeInfixCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeInfixCall::class) { diagnostic ->
createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(diagnostic.receiverExpression)
}
val forUnsafeOperatorCall = diagnosticFixFactory(KtFirDiagnostic.UnsafeOperatorCall::class) { diagnostic ->
createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(diagnostic.receiverExpression)
}
val forArgumentTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ArgumentTypeMismatch::class) { diagnostic ->
if (diagnostic.isMismatchDueToNullability) createWrapWithSafeLetCallInputForNullableExpression(diagnostic.psi.wrappingExpressionOrSelf)
else emptyList()
}
private fun KtAnalysisSession.createWrapWithSafeLetCallInputForNullableExpressionIfMoreThanImmediateParentIsWrapped(
nullableExpression: KtExpression?,
isImplicitInvokeCallToMemberProperty: Boolean = false,
): List<KotlinApplicatorBasedQuickFix<KtExpression, Input>> {
val surroundingExpression = nullableExpression?.surroundingExpression
if (
surroundingExpression == null ||
// If the surrounding expression is at a place that accepts null value, then we don't provide wrap with let call because the
// plain safe call operator (?.) is a better fix.
isExpressionAtNullablePosition(surroundingExpression)
) {
return emptyList()
}
// In addition, if there is no parent that is at a nullable position, then we don't offer wrapping with let either because
// it still doesn't fix the code. Hence, the plain safe call operator is a better fix.
val surroundingNullableExpression = findParentExpressionAtNullablePosition(nullableExpression) ?: return emptyList()
return createWrapWithSafeLetCallInputForNullableExpression(
nullableExpression,
isImplicitInvokeCallToMemberProperty,
surroundingNullableExpression
)
}
private fun KtAnalysisSession.createWrapWithSafeLetCallInputForNullableExpression(
nullableExpression: KtExpression?,
isImplicitInvokeCallToMemberProperty: Boolean = false,
surroundingExpression: KtExpression? = findParentExpressionAtNullablePosition(nullableExpression)
?: nullableExpression?.surroundingExpression
): List<KotlinApplicatorBasedQuickFix<KtExpression, Input>> {
if (nullableExpression == null || surroundingExpression == null) return emptyList()
val scope = nullableExpression.containingKtFile.getScopeContextForPosition(nullableExpression).getCompositeScope()
val existingNames = scope.getPossibleCallableNames().mapNotNull { it.identifierOrNullIfSpecial }
// Note, the order of the candidate matters. We would prefer the default `it` so the generated code won't need to declare the
// variable explicitly.
val candidateNames = listOfNotNull("it", getDeclaredParameterNameForArgument(nullableExpression))
val suggestedName = FirKotlinNameSuggester.suggestNameByMultipleNames(candidateNames) { it !in existingNames }
return listOf(
KotlinApplicatorBasedQuickFix(
surroundingExpression,
Input(nullableExpression.createSmartPointer(), suggestedName, isImplicitInvokeCallToMemberProperty),
applicator
)
)
}
private fun KtAnalysisSession.getDeclaredParameterNameForArgument(argumentExpression: KtExpression): String? {
val valueArgument = argumentExpression.parent as? KtValueArgument ?: return null
val callExpression = argumentExpression.parentOfType<KtCallExpression>()
val successCallTarget = callExpression?.resolveCall()?.singleFunctionCallOrNull()?.symbol ?: return null
return successCallTarget.valueParameters.getOrNull(valueArgument.argumentIndex)?.name?.identifierOrNullIfSpecial
}
private fun KtAnalysisSession.findParentExpressionAtNullablePosition(expression: KtExpression?): KtExpression? {
if (expression == null) return null
var current = expression.surroundingExpression
while (current != null && !isExpressionAtNullablePosition(current)) {
current = current.surroundingExpression
}
return current
}
private fun KtAnalysisSession.isExpressionAtNullablePosition(expression: KtExpression): Boolean {
val parent = expression.parent
return when {
parent is KtProperty && expression == parent.initializer -> {
if (parent.typeReference == null) return true
val symbol = parent.getSymbol()
(symbol as? KtCallableSymbol)?.returnType?.isMarkedNullable ?: true
}
parent is KtValueArgument && expression == parent.getArgumentExpression() -> {
// In the following logic, if call is missing, unresolved, or contains error, we just stop here so the wrapped call would be
// inserted here.
val functionCall = parent.getParentOfType<KtCallExpression>(strict = true) ?: return true
val resolvedCall = functionCall.resolveCall().singleFunctionCallOrNull() ?: return true
return doesFunctionAcceptNull(resolvedCall, parent.argumentIndex) ?: true
}
parent is KtBinaryExpression -> {
if (parent.operationToken in KtTokens.ALL_ASSIGNMENTS && parent.left == expression) {
// If current expression is an l-value in an assignment, just keep going up because one cannot assign to a let call.
return false
}
val resolvedCall = parent.resolveCall()?.singleFunctionCallOrNull()
when {
resolvedCall != null -> {
// The binary expression is a call to some function
val isInExpression = parent.operationToken in OperatorConventions.IN_OPERATIONS
val expressionIsArg = when {
parent.left == expression -> isInExpression
parent.right == expression -> !isInExpression
else -> return true
}
doesFunctionAcceptNull(resolvedCall, if (expressionIsArg) 0 else -1) ?: true
}
parent.operationToken == KtTokens.EQ -> {
// The binary expression is a variable assignment
parent.left?.getKtType()?.isMarkedNullable ?: true
}
// The binary expression is some unrecognized constructs so we stop here.
else -> true
}
}
// Qualified expression can always be updated with a safe call operator to make it accept nullable receiver. Hence, we
// don't want to offer the wrap with let call quickfix.
parent is KtQualifiedExpression && parent.receiverExpression == expression -> true
// Ideally we should do more analysis on the control structure to determine if the type can actually allow null here. But that
// may be too fancy and can be counter-intuitive to user.
parent is KtContainerNodeForControlStructureBody -> true
// Again, for simplicity's sake, we treat block as a place that can accept expression of any type. This is not strictly true
// for lambda expressions, but it results in a more deterministic behavior.
parent is KtBlockExpression -> true
else -> false
}
}
/**
* Checks if the called function can accept null for the argument at the given index. If the index is -1, then we check the receiver
* type. The function returns null if any necessary assumptions are not met. For example, if the call is not resolved to a unique
* function or the function doesn't have a parameter at the given index. Then caller can do whatever needed to cover such cases.
*/
private fun KtAnalysisSession.doesFunctionAcceptNull(call: KtCall, index: Int): Boolean? {
val symbol = (call as? KtFunctionCall<*>)?.symbol ?: return null
if (index == -1) {
// Null extension receiver means the function does not accept extension receiver and hence cannot be invoked on a nullable
// value.
return (symbol as? KtCallableSymbol)?.receiverType?.isMarkedNullable == true
}
return symbol.valueParameters.getOrNull(index)?.returnType?.isMarkedNullable
}
private val KtExpression.surroundingExpression: KtExpression?
get() {
var current: PsiElement? = parent
while (true) {
// Never go above declarations or control structure so that the wrap-with-let quickfix only applies to a "small" scope
// around the nullable expression.
if (current == null ||
current is KtContainerNodeForControlStructureBody ||
current is KtWhenEntry ||
current is KtParameter ||
current is KtProperty ||
current is KtReturnExpression ||
current is KtDeclaration ||
current is KtBlockExpression
) {
return null
}
val parent = current.parent
if (current is KtExpression &&
// We skip parenthesized expression and labeled expressions.
current !is KtParenthesizedExpression && current !is KtLabeledExpression &&
// We skip KtCallExpression if it's the `selectorExpression` of a qualified expression because the selector expression is
// not an actual expression that can be swapped for any arbitrary expressions.
(parent !is KtQualifiedExpression || parent.selectorExpression != current)
) {
return current
}
current = parent
}
}
private val PsiElement.wrappingExpressionOrSelf: KtExpression? get() = parentOfType(withSelf = true)
} | 284 | null | 5162 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 18,911 | intellij-kotlin | Apache License 2.0 |
iminling-core/src/main/kotlin/com/iminling/core/config/rest/ClientHttpResponseWrapper.kt | konghanghang | 340,850,176 | false | null | package com.iminling.core.config.rest
import com.iminling.common.json.JsonUtil
import com.iminling.core.config.value.ResultModel
import org.springframework.http.HttpHeaders
import org.springframework.http.client.AbstractClientHttpResponse
import org.springframework.http.client.ClientHttpResponse
import org.springframework.util.StreamUtils
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
/**
* @author <EMAIL>
* @since 2021/11/9
*/
class ClientHttpResponseWrapper(private val response: ClientHttpResponse): AbstractClientHttpResponse() {
var inputStream: InputStream? = null
var inner: Boolean = false
override fun getHeaders(): HttpHeaders {
return response.headers
}
override fun getBody(): InputStream {
if (inputStream == null) {
// 是否是内部调用
if (!inner) {
inputStream = response.body
return inputStream as InputStream
}
var body = response.body
var byteArrayOutputStream = ByteArrayOutputStream()
StreamUtils.copy(body, byteArrayOutputStream)
var objectMapper = JsonUtil.getInstant()
var readValue = objectMapper.readValue(byteArrayOutputStream.toByteArray(), ResultModel::class.java)
inputStream = ByteArrayInputStream(objectMapper.writeValueAsBytes(readValue.data))
}
return inputStream as InputStream
}
override fun close() {
inputStream?.let {
StreamUtils.drain(it)
it.close()
}
response.close()
}
override fun getRawStatusCode(): Int {
return response.rawStatusCode
}
override fun getStatusText(): String {
return response.statusText
}
} | 0 | Kotlin | 0 | 1 | 9f2cb7d85ad7364ff3aa92bfd5eb15db9b23809a | 1,793 | base-iminling-core | MIT License |
instrumented/integration/src/androidTest/kotlin/com/datadog/android/sdk/integration/trace/ConsentPendingNotGrantedTracesTest.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.sdk.integration.trace
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import com.datadog.android.Datadog
import com.datadog.android.privacy.TrackingConsent
import com.datadog.android.sdk.rules.MockServerActivityTestRule
import com.datadog.android.sdk.utils.isTracesUrl
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
internal class ConsentPendingNotGrantedTracesTest : TracesTest() {
@get:Rule
val mockServerRule = MockServerActivityTestRule(
ActivityLifecycleTrace::class.java,
keepRequests = true,
trackingConsent = TrackingConsent.PENDING
)
@Test
fun verifyAllTracesAreDropped() {
runInstrumentationScenario(mockServerRule)
// update the tracking consent
Datadog.setTrackingConsent(TrackingConsent.NOT_GRANTED)
// Wait to make sure all batches are consumed
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
Thread.sleep(INITIAL_WAIT_MS)
val tracePayloads = mockServerRule
.getRequests()
.filter { it.url?.isTracesUrl() ?: false }
assertThat(tracePayloads).isEmpty()
}
}
| 44 | Kotlin | 60 | 86 | bcf0d12fd978df4e28848b007d5fcce9cb97df1c | 1,631 | dd-sdk-android | Apache License 2.0 |
library/src/commonMain/kotlin/org/jraf/klibnotion/model/property/spec/RelationPropertySpec.kt | BoD | 330,462,851 | false | {"Kotlin": 634624} | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2021-present Benoit 'BoD<NAME> (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jraf.klibnotion.model.property.spec
import org.jraf.klibnotion.model.base.UuidString
/**
* See [Reference](https://developers.notion.com/reference/database).
*/
interface RelationPropertySpec : PropertySpec {
/**
* The database this relation refers to.
* New linked pages must belong to this database in order to be valid.
*/
val databaseId: UuidString
/**
* By default, relations are formed as two synced properties across databases: if you make a change to one property,
* it updates the synced property at the same time.
* [syncedPropertyName] refers to the name of the property in the related database.
*/
val syncedPropertyName: String
/**
* By default, relations are formed as two synced properties across databases: if you make a change to one property,
* it updates the synced property at the same time.
* [syncedPropertyId] refers to the id of the property in the related database.
* Like [PropertySpec.id], this is usually a short string of random letters and symbols.
*/
val syncedPropertyId: String
} | 26 | Kotlin | 4 | 45 | 5c5c8c1916ae9204913f6fad39d34fa82480ce64 | 1,969 | klibnotion | Apache License 2.0 |
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/codegen/ApiTypeProviderTest.kt | JohanWranker | 121,043,472 | false | null | /*
* Copyright 2018 the original author or 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 org.gradle.kotlin.dsl.codegen
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectFactory
import org.gradle.api.Plugin
import org.gradle.api.file.ContentFilterable
import org.gradle.api.internal.file.copy.CopySpecSource
import org.gradle.api.model.ObjectFactory
import org.gradle.api.plugins.PluginCollection
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.AbstractCopyTask
import org.gradle.kotlin.dsl.fixtures.AbstractIntegrationTest
import org.gradle.kotlin.dsl.fixtures.codegen.GenericsVariance
import org.gradle.kotlin.dsl.support.canonicalNameOf
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.nullValue
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Test
class ApiTypeProviderTest : AbstractIntegrationTest() {
@Test
fun `provides a source code generation oriented model over a classpath`() {
val jars = listOf(withClassJar("some.jar",
Plugin::class.java,
PluginCollection::class.java,
ObjectFactory::class.java))
apiTypeProviderFor(jars).use { api ->
assertThat(api.typeOrNull<Test>(), nullValue())
api.type<PluginCollection<*>>().apply {
assertThat(sourceName, equalTo("org.gradle.api.plugins.PluginCollection"))
assertTrue(isPublic)
assertThat(typeParameters.size, equalTo(1))
typeParameters.single().apply {
assertThat(sourceName, equalTo("T"))
assertThat(bounds.size, equalTo(1))
assertThat(bounds.single().sourceName, equalTo("org.gradle.api.Plugin"))
}
functions.single { it.name == "withType" }.apply {
assertThat(typeParameters.size, equalTo(1))
typeParameters.single().apply {
assertThat(sourceName, equalTo("S"))
assertThat(bounds.size, equalTo(1))
assertThat(bounds.single().sourceName, equalTo("T"))
}
assertThat(parameters.size, equalTo(1))
parameters.single().type.apply {
assertThat(sourceName, equalTo("java.lang.Class"))
assertThat(typeArguments.size, equalTo(1))
typeArguments.single().apply {
assertThat(sourceName, equalTo("S"))
}
}
returnType.apply {
assertThat(sourceName, equalTo("org.gradle.api.plugins.PluginCollection"))
assertThat(typeArguments.size, equalTo(1))
typeArguments.single().apply {
assertThat(sourceName, equalTo("S"))
}
}
}
}
api.type<ObjectFactory>().apply {
functions.single { it.name == "newInstance" }.apply {
parameters.drop(1).single().type.apply {
assertThat(sourceName, equalTo("kotlin.Array"))
assertThat(typeArguments.single().sourceName, equalTo("Any"))
}
}
}
}
}
@Test
fun `maps generic question mark to *`() {
val jars = listOf(withClassJar("some.jar", ContentFilterable::class.java))
apiTypeProviderFor(jars).use { api ->
api.type<ContentFilterable>().functions.single { it.name == "expand" }.apply {
assertTrue(typeParameters.isEmpty())
assertThat(parameters.size, equalTo(1))
parameters.single().type.apply {
assertThat(sourceName, equalTo("kotlin.collections.Map"))
assertThat(typeArguments.size, equalTo(2))
assertThat(typeArguments[0].sourceName, equalTo("String"))
assertThat(typeArguments[1].sourceName, equalTo("*"))
}
}
}
}
@Test
fun `includes function overrides that change signature, excludes overrides that don't`() {
val jars = listOf(withClassJar("some.jar", AbstractCopyTask::class.java, CopySpecSource::class.java))
apiTypeProviderFor(jars).use { api ->
val type = api.type<AbstractCopyTask>()
assertThat(type.functions.filter { it.name == "filter" }.size, equalTo(4))
assertThat(type.functions.filter { it.name == "getRootSpec" }.size, equalTo(0))
}
}
@Test
fun `provides generic bounds`() {
fun ApiFunctionParameter.assertSingleTypeArgumentWithVariance(variance: Variance) =
assertThat(type.typeArguments.single().variance, equalTo(variance))
val jars = listOf(withClassJar("some.jar", GenericsVariance::class.java))
apiTypeProviderFor(jars).use { api ->
api.type<GenericsVariance>().functions.forEach { function ->
when (function.name) {
"invariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.INVARIANT)
"covariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.COVARIANT)
"contravariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.CONTRAVARIANT)
}
}
}
}
@Test
fun `provides if a type is a SAM`() {
val jars = listOf(withClassJar("some.jar",
Action::class.java,
NamedDomainObjectFactory::class.java,
ObjectFactory::class.java,
PluginCollection::class.java,
Spec::class.java))
apiTypeProviderFor(jars).use { api ->
assertTrue(api.type<Action<*>>().isSAM)
assertTrue(api.type<NamedDomainObjectFactory<*>>().isSAM)
assertFalse(api.type<ObjectFactory>().isSAM)
assertFalse(api.type<PluginCollection<*>>().isSAM)
assertTrue(
api.type<PluginCollection<*>>().functions
.filter { it.name == "matching" }
.single { it.parameters.single().type.sourceName == Spec::class.qualifiedName }
.parameters.single().type.type!!.isSAM)
assertTrue(api.type<Spec<*>>().isSAM)
}
}
private
inline fun <reified T> ApiTypeProvider.type() =
typeOrNull<T>()!!
private
inline fun <reified T> ApiTypeProvider.typeOrNull() =
type(canonicalNameOf<T>())
}
| 2,663 | null | 4552 | 2 | e089307757e7ee7e1a898e84841bd2100ff7ef27 | 7,324 | gradle | Apache License 2.0 |
educational-core/src/com/jetbrains/edu/learning/VirtualFileExt.kt | JetBrains | 43,696,115 | false | null | @file:JvmName("VirtualFileExt")
package com.jetbrains.edu.learning
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.io.FileTooBigException
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.ui.UIUtil
import com.jetbrains.edu.learning.EduDocumentListener.Companion.runWithListener
import com.jetbrains.edu.learning.courseFormat.*
import com.jetbrains.edu.learning.courseFormat.ext.configurator
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import com.jetbrains.edu.learning.courseGeneration.macro.EduMacroUtils
import com.jetbrains.edu.learning.exceptions.BrokenPlaceholderException
import com.jetbrains.edu.learning.exceptions.HugeBinaryFileException
import com.jetbrains.edu.learning.messages.EduCoreBundle
import org.apache.commons.codec.binary.Base64
import java.io.IOException
fun VirtualFile.getEditor(project: Project): Editor? {
val selectedEditor = invokeAndWaitIfNeeded { FileEditorManager.getInstance(project).getSelectedEditor(this) }
return if (selectedEditor is TextEditor) selectedEditor.editor else null
}
val VirtualFile.document
get() : Document = FileDocumentManager.getInstance().getDocument(this) ?: error("Cannot find document for a file: ${name}")
fun VirtualFile.startLoading(project: Project) {
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(this) ?: return
fileEditor.setViewer(true)
fileEditor.loadingPanel?.apply {
setLoadingText(EduCoreBundle.message("editor.loading.solution"))
startLoading()
}
}
fun VirtualFile.stopLoading(project: Project) {
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(this) ?: return
fileEditor.setViewer(false)
fileEditor.loadingPanel?.stopLoading()
}
private fun FileEditor.setViewer(isViewer: Boolean) {
val textEditor = this as? TextEditor ?: return
(textEditor.editor as EditorEx).isViewer = isViewer
}
private val FileEditor.loadingPanel: JBLoadingPanel?
get() = UIUtil.findComponentOfType(component, JBLoadingPanel::class.java)
fun VirtualFile.getSection(project: Project): Section? {
val course = project.course ?: return null
if (!isDirectory) return null
return if (project.courseDir == parent) course.getSection(name) else null
}
fun VirtualFile.isSectionDirectory(project: Project): Boolean {
return getSection(project) != null
}
fun VirtualFile.getLesson(project: Project): Lesson? {
val course = project.course ?: return null
if (!isDirectory) return null
if (parent == null) return null
val section = parent.getSection(project)
if (section != null) {
return section.getLesson(name)
}
return if (project.courseDir == parent) course.getLesson(name) else null
}
fun VirtualFile.isLessonDirectory(project: Project): Boolean {
return getLesson(project) != null
}
fun VirtualFile.getContainingTask(project: Project): Task? {
val course = project.course ?: return null
val taskDir = getTaskDir(project) ?: return null
val lessonDir = taskDir.parent ?: return null
val lesson = lessonDir.getLesson(project) ?: return null
return if (lesson is FrameworkLesson && course.isStudy) {
lesson.currentTask()
}
else {
lesson.getTask(taskDir.name)
}
}
fun VirtualFile.getTask(project: Project): Task? {
if (!isDirectory) return null
val lesson: Lesson = parent?.getLesson(project) ?: return null
return lesson.getTask(name)
}
fun VirtualFile.isTaskDirectory(project: Project): Boolean {
return getTask(project) != null
}
fun VirtualFile.getStudyItem(project: Project): StudyItem? {
val course = project.course ?: return null
val courseDir = project.courseDir
if (courseDir == this) return course
val section = getSection(project)
if (section != null) return section
val lesson = getLesson(project)
return lesson ?: getTask(project)
}
/**
* @return true, if file doesn't belong to task (in term of course structure)
* but can be added to it as task, test or additional file.
* Otherwise, returns false
*/
fun VirtualFile.canBeAddedToTask(project: Project): Boolean {
if (isDirectory) return false
val configurator = getContainingTask(project)?.course?.configurator ?: return false
return if (configurator.excludeFromArchive(project, this)) false else !belongsToTask(project)
}
/**
* @return true, if some task contains given `file` as task, test or additional file.
* Otherwise, returns false
*/
fun VirtualFile.belongsToTask(project: Project): Boolean {
val task = getContainingTask(project) ?: return false
val relativePath = pathRelativeToTask(project)
return task.getTaskFile(relativePath) != null
}
fun VirtualFile.canBelongToCourse(project: Project): Boolean {
if (isSectionDirectory(project) || isLessonDirectory(project) || isTaskDirectory(project)) return true
return if (isDirectory) {
getContainingTask(project) != null
}
else {
belongsToTask(project)
}
}
fun VirtualFile.pathRelativeToTask(project: Project): String {
val taskDir = getTaskDir(project) ?: return name
return FileUtil.getRelativePath(taskDir.path, path, VfsUtilCore.VFS_SEPARATOR_CHAR) ?: return name
}
fun VirtualFile.getTaskDir(project: Project): VirtualFile? {
var taskDir = this
while (true) {
val lessonDirCandidate = taskDir.parent ?: return null
val lesson = lessonDirCandidate.getLesson(project)
if (lesson != null) {
if (lesson is FrameworkLesson && EduNames.TASK == taskDir.name || lesson.getTask(taskDir.name) != null) {
return taskDir
}
}
taskDir = lessonDirCandidate
}
}
fun VirtualFile.isTestsFile(project: Project): Boolean {
if (isDirectory) return false
val task = getContainingTask(project) ?: return false
val path: String = pathRelativeToTask(project)
val course = StudyTaskManager.getInstance(project).course ?: return false
val configurator = course.configurator ?: return false
return configurator.isTestFile(task, path)
}
fun VirtualFile.isTaskRunConfigurationFile(project: Project): Boolean {
if (isDirectory) return false
val parent = parent ?: return false
if (parent.name != EduNames.RUN_CONFIGURATION_DIR) return false
val grandParent = parent.parent
return grandParent != null && grandParent.getTaskDir(project) == grandParent
}
fun VirtualFile.getTaskFile(project: Project): TaskFile? {
val task = getContainingTask(project)
return task?.getTaskFile(pathRelativeToTask(project))
}
val VirtualFile.isToEncodeContent: Boolean
get(): Boolean = toEncodeFileContent(path)
fun VirtualFile.mimeType(): String? = mimeFileType(path)
@Throws(IOException::class)
fun VirtualFile.loadEncodedContent(isToEncodeContent: Boolean = this.isToEncodeContent): String {
return if (isToEncodeContent) {
Base64.encodeBase64String(contentsToByteArray())
}
else {
VfsUtilCore.loadText(this)
}
}
@Throws(HugeBinaryFileException::class)
fun VirtualFile.toStudentFile(project: Project, task: Task): TaskFile? {
try {
val taskCopy = task.copy()
val taskFile = taskCopy.getTaskFile(pathRelativeToTask(project)) ?: return null
if (isToEncodeContent) {
if (task.lesson is FrameworkLesson && length >= EduUtils.getBinaryFileLimit()) {
throw HugeBinaryFileException("${task.getPathInCourse()}/${taskFile.name}", length, EduUtils.getBinaryFileLimit().toLong(), true)
}
taskFile.setText(loadEncodedContent(isToEncodeContent = true))
return taskFile
}
FileDocumentManager.getInstance().saveDocument(document)
val studentFile = LightVirtualFile("student_task", PlainTextFileType.INSTANCE, document.text)
runWithListener(project, taskFile, studentFile) { studentDocument: Document ->
for (placeholder in taskFile.answerPlaceholders) {
try {
placeholder.possibleAnswer = studentDocument.getText(TextRange.create(placeholder.offset, placeholder.endOffset))
EduUtils.replaceAnswerPlaceholder(studentDocument, placeholder)
}
catch (e: IndexOutOfBoundsException) {
// We are here because placeholder is broken. We need to put broken placeholder into exception.
// We need to take it from original task, because taskCopy has issues with links (taskCopy.lesson is always null)
val file = task.getTaskFile(taskFile.name)
val answerPlaceholder = file?.answerPlaceholders?.get(placeholder.index)
throw BrokenPlaceholderException(EduCoreBundle.message("exception.broken.placeholder.title"), answerPlaceholder ?: placeholder)
}
}
val text = studentDocument.immutableCharSequence.toString()
taskFile.setText(EduMacroUtils.collapseMacrosForFile(project, this, text))
}
return taskFile
}
catch (e: FileTooBigException) {
throw HugeBinaryFileException("${task.getPathInCourse()}/${name}", length, FileUtilRt.LARGE_FOR_CONTENT_LOADING.toLong(), false)
}
catch (e: IOException) {
LOG.error("Failed to convert `${path}` to student file")
}
return null
}
private val LOG = Logger.getInstance("com.jetbrains.edu.learning.VirtualFileExt")
| 7 | null | 49 | 99 | cfc24fe13318de446b8adf6e05d1a7c15d9511b5 | 9,829 | educational-plugin | Apache License 2.0 |
HW_1/app/src/main/java/com/example/tipcalculator/MainActivity.kt | salcortes96 | 381,897,263 | false | null | package com.example.tipcalculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.AbsSeekBar
import android.widget.SeekBar
import kotlinx.android.synthetic.main.activity_main.*
private const val TAG = "MainActivity"
private const val INITIAL_TIP_PERCENT = 15
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
seekBarTip.progress = INITIAL_TIP_PERCENT
tvTipPercent.text = "$INITIAL_TIP_PERCENT%"
updateTipDescription(INITIAL_TIP_PERCENT)
/*seek bar class*/
seekBarTip.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged( seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
Log.i(TAG, "onProgressChanged $progress")
tvTipPercent.text = "$progress%"
updateTipDescription(progress)
computeTipAndTotal()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
} )
etBase.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
Log.i(TAG, "afterTextChanged $s")
computeTipAndTotal()
}
})
}
private fun updateTipDescription(tipPercent: Int) {
val tipDescription : String
when (tipPercent) {
in 0..9 -> tipDescription = "Poor"
in 10..14 -> tipDescription = "Acceptable"
in 15..19 -> tipDescription = "Good"
in 20..24 -> tipDescription = "Great"
else -> tipDescription = "Amazing"
}
tvTipDescription.text = tipDescription
}
private fun computeTipAndTotal(){
//Get the value of the base and tip percentage
if (etBase.text.isEmpty()){
tvTipAmout.text =""
tvTotalAmount.text = ""
return
}
val baseAmount = etBase.text.toString().toDouble()
val tipPercent = seekBarTip.progress
val tipAmount = baseAmount * tipPercent / 100
val totalAmount = baseAmount + tipAmount
tvTipAmout.text = "%.2f".format(tipAmount)
tvTotalAmount.text = "%.2f".format(totalAmount)
}
}
| 0 | Kotlin | 0 | 0 | 4f50bc22c0854d82dd2f384aceaef09523c2a088 | 2,725 | 523-Assignments | MIT License |
src/main/kotlin/no/nav/fo/veilarbregistrering/arbeidsforhold/adapter/ArbeidsforholdDto.kt | navikt | 131,013,336 | false | {"Kotlin": 892366, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87} | package no.nav.fo.veilarbregistrering.arbeidsforhold.adapter
data class ArbeidsforholdDto (
val arbeidsgiver: ArbeidsgiverDto? = null,
val ansettelsesperiode: AnsettelsesperiodeDto? = null,
val arbeidsavtaler: List<ArbeidsavtaleDto> = emptyList(),
val navArbeidsforholdId: Int? = null,
) | 17 | Kotlin | 5 | 6 | 68dabd12cfa5af1eb0a3af33fd422a3e755ad433 | 304 | veilarbregistrering | MIT License |
app/src/androidTest/java/com/duckduckgo/app/email/ui/EmailProtectionSignInViewModelTest.kt | cmonfortep | 252,403,423 | true | {"Gemfile.lock": 1, "Git Config": 1, "Gradle": 44, "Shell": 6, "JSON": 159, "Markdown": 20, "Java Properties": 4, "Text": 28, "Ignore List": 40, "Batchfile": 1, "EditorConfig": 3, "XML": 779, "Ruby": 2, "Kotlin": 1519, "YAML": 15, "CMake": 1, "Proguard": 1, "HTML": 276, "JavaScript": 239, "C++": 1, "INI": 1, "Java": 8, "Gradle Kotlin DSL": 1, "Makefile": 2, "Perl": 5, "CSS": 11, "JSON with Comments": 2, "Git Attributes": 2, "Swift": 2, "SVG": 9} | /*
* Copyright (c) 2021 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.email.ui
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
import androidx.work.Configuration
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.impl.utils.SynchronousExecutor
import androidx.work.testing.WorkManagerTestInitHelper
import app.cash.turbine.test
import com.duckduckgo.app.CoroutineTestRule
import com.duckduckgo.app.email.AppEmailManager.WaitlistState.*
import com.duckduckgo.app.email.EmailManager
import com.duckduckgo.app.email.api.EmailAlias
import com.duckduckgo.app.email.api.EmailInviteCodeResponse
import com.duckduckgo.app.email.api.EmailService
import com.duckduckgo.app.email.api.WaitlistResponse
import com.duckduckgo.app.email.api.WaitlistStatusResponse
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Companion.LOGIN_URL
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Command.*
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Companion.ADDRESS_BLOG_POST
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Companion.GET_STARTED_URL
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Companion.PRIVACY_GUARANTEE
import com.duckduckgo.app.email.ui.EmailProtectionSignInViewModel.Companion.SIGN_UP_URL
import com.duckduckgo.app.email.waitlist.WaitlistWorkRequestBuilder
import com.duckduckgo.app.runBlocking
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import java.lang.Exception
import kotlin.time.ExperimentalTime
@ExperimentalTime
@FlowPreview
@ExperimentalCoroutinesApi
class EmailProtectionSignInViewModelTest {
@get:Rule
var coroutineRule = CoroutineTestRule()
private val mockEmailManager: EmailManager = mock()
private var mockEmailService: EmailService = mock()
private val waitlistBuilder: WaitlistWorkRequestBuilder = WaitlistWorkRequestBuilder()
private val context = InstrumentationRegistry.getInstrumentation().targetContext
private lateinit var workManager: WorkManager
private lateinit var testee: EmailProtectionSignInViewModel
@Before
fun before() {
whenever(mockEmailManager.waitlistState()).thenReturn(NotJoinedQueue)
initializeWorkManager()
testee = EmailProtectionSignInViewModel(mockEmailManager, mockEmailService, workManager, waitlistBuilder)
}
@Test
fun whenViewModelCreatedThenEmitWaitlistState() = coroutineRule.runBlocking {
testee.viewState.test {
assert(expectItem().waitlistState is NotJoinedQueue)
}
}
@Test
fun whenHaveADuckAddressThenEmitCommandOpenUrlWithCorrectUrl() = coroutineRule.runBlocking {
testee.commands.test {
testee.haveADuckAddress()
assertEquals(OpenUrl(url = LOGIN_URL), expectItem())
}
}
@Test
fun whenHaveAnInviteCodeThenEmitCommandOpenUrlWithCorrectUrl() = coroutineRule.runBlocking {
val inviteCode = "abcde"
whenever(mockEmailManager.getInviteCode()).thenReturn(inviteCode)
val expectedURL = "$SIGN_UP_URL$inviteCode"
testee.commands.test {
testee.haveAnInviteCode()
assertEquals(OpenUrl(url = expectedURL), expectItem())
}
}
@Test
fun whenGetStartedThenEmitCommandOpenUrlWithCorrectUrl() = coroutineRule.runBlocking {
val inviteCode = "abcde"
whenever(mockEmailManager.getInviteCode()).thenReturn(inviteCode)
val expectedURL = "$GET_STARTED_URL$inviteCode"
testee.commands.test {
testee.getStarted()
assertEquals(OpenUrl(url = expectedURL), expectItem())
}
}
@Test
fun whenReadBlogPostThenEmitCommandOpenUrlWithCorrectUrl() = coroutineRule.runBlocking {
testee.commands.test {
testee.readBlogPost()
assertEquals(OpenUrl(url = ADDRESS_BLOG_POST), expectItem())
}
}
@Test
fun whenReadPrivacyGuaranteeThenEmitCommandOpenUrlWithCorrectUrl() = coroutineRule.runBlocking {
testee.commands.test {
testee.readPrivacyGuarantees()
assertEquals(OpenUrl(url = PRIVACY_GUARANTEE), expectItem())
}
}
@Test
fun whenJoinTheWaitlistAndCallTimestampIsNullThenEmitShowErrorMessageCommand() = coroutineRule.runBlocking {
whenever(mockEmailService.joinWaitlist()).thenReturn(WaitlistResponse("token", null))
whenever(mockEmailManager.waitlistState()).thenReturn(JoinedQueue())
testee.commands.test {
testee.joinTheWaitlist()
assertEquals(ShowErrorMessage, expectItem())
}
}
@Test
fun whenJoinTheWaitlistAndCallTokenIsNullThenEmitShowErrorMessageCommand() = coroutineRule.runBlocking {
whenever(mockEmailService.joinWaitlist()).thenReturn(WaitlistResponse(null, 12345))
whenever(mockEmailManager.waitlistState()).thenReturn(JoinedQueue())
testee.commands.test {
testee.joinTheWaitlist()
assertEquals(ShowErrorMessage, expectItem())
}
}
@Test
fun whenJoinTheWaitlistAndCallTokenIsEmptyThenEmitShowErrorMessageCommand() = coroutineRule.runBlocking {
whenever(mockEmailService.joinWaitlist()).thenReturn(WaitlistResponse("", 12345))
whenever(mockEmailManager.waitlistState()).thenReturn(JoinedQueue())
testee.commands.test {
testee.joinTheWaitlist()
assertEquals(ShowErrorMessage, expectItem())
}
}
@Test
fun whenJoinTheWaitlistAndCallIsSuccessfulThenJoinWaitlistCalled() = coroutineRule.runBlocking {
givenJoinWaitlistSuccessful()
testee.joinTheWaitlist()
verify(mockEmailManager).joinWaitlist(12345, "token")
}
@Test
fun whenJoinTheWaitlistAndCallIsSuccessfulThenEmitShowNotificationDialogCommand() = coroutineRule.runBlocking {
givenJoinWaitlistSuccessful()
testee.commands.test {
testee.joinTheWaitlist()
assertEquals(ShowNotificationDialog, expectItem())
}
}
@Test
fun whenJoinTheWaitlistAndCallIsSuccessfulThenEnqueueEmailWaitlistWork() = coroutineRule.runBlocking {
givenJoinWaitlistSuccessful()
testee.joinTheWaitlist()
assertWaitlistWorkerIsEnqueued()
}
@Test
fun whenJoinTheWaitlistAndCallFailsThenEmitShowErrorMessageCommand() = coroutineRule.runBlocking {
testee = EmailProtectionSignInViewModel(mockEmailManager, TestEmailService(), workManager, waitlistBuilder)
testee.commands.test {
testee.joinTheWaitlist()
assertEquals(ShowErrorMessage, expectItem())
}
}
@Test
fun whenOnNotifyMeClickedThenNotifyOnJoinedWaitlistCalled() = coroutineRule.runBlocking {
testee.onNotifyMeClicked()
verify(mockEmailManager).notifyOnJoinedWaitlist()
}
@Test
fun whenOnDialogDismissedThenEmitWaitlistState() = coroutineRule.runBlocking {
givenJoinWaitlistSuccessful()
testee.viewState.test {
assert(expectItem().waitlistState is NotJoinedQueue)
testee.onDialogDismissed()
assert(expectItem().waitlistState is JoinedQueue)
}
}
private fun assertWaitlistWorkerIsEnqueued() {
val scheduledWorkers = getScheduledWorkers()
assertFalse(scheduledWorkers.isEmpty())
}
private fun givenJoinWaitlistSuccessful() = coroutineRule.runBlocking {
whenever(mockEmailService.joinWaitlist()).thenReturn(WaitlistResponse("token", 12345))
whenever(mockEmailManager.waitlistState()).thenReturn(JoinedQueue())
}
private fun getScheduledWorkers(): List<WorkInfo> {
return workManager
.getWorkInfosByTag(WaitlistWorkRequestBuilder.EMAIL_WAITLIST_SYNC_WORK_TAG)
.get()
.filter { it.state == WorkInfo.State.ENQUEUED }
}
private fun initializeWorkManager() {
val config = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(SynchronousExecutor())
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
workManager = WorkManager.getInstance(context)
}
class TestEmailService : EmailService {
override suspend fun newAlias(authorization: String): EmailAlias = EmailAlias("test")
override suspend fun joinWaitlist(): WaitlistResponse { throw Exception() }
override suspend fun waitlistStatus(): WaitlistStatusResponse = WaitlistStatusResponse(1234)
override suspend fun getCode(token: String): EmailInviteCodeResponse = EmailInviteCodeResponse("token")
}
}
| 5 | Kotlin | 671 | 3 | c03633f7faee192948e68c3897c526c323ee0f2e | 9,528 | Android | Apache License 2.0 |
src/main/kotlin/view/utils/elementCss/properties/Grid.kt | mzaart | 160,255,325 | false | null | package view.utils.elementCss.properties
import org.w3c.dom.HTMLElement
import view.utils.extensions.nonNull
/**
* Sets CSS properties related to a CSS grid.
*/
class Grid: CssProperty {
var rowGap: CssDimen = Dimension("grid-row-gap")
var columnGap: CssDimen = Dimension("grid-column-gap")
var rowCount: Int? = null
var columnCount: Int? = null
override fun applyToStyle(element: HTMLElement) {
rowGap.applyToStyle(element)
columnGap.applyToStyle(element)
val style = element.style
rowCount.nonNull { style.setProperty("grid-template-rows", "repeat($it, 1fr") }
columnCount.nonNull { style.setProperty("grid-template-columns", "repeat($it, 1fr") }
style.setProperty("justify-items", "center")
style.setProperty("align-items", "center")
}
} | 0 | Kotlin | 0 | 0 | 00a0988c448e4668dc95fa8b74d65ab7c4e2456f | 828 | MaterialDesignJsViewRenderer | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/courthearingeventreceiver/model/HearingType.kt | ministryofjustice | 377,493,306 | false | null | package uk.gov.justice.digital.hmpps.courthearingeventreceiver.model
import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.validation.constraints.NotBlank
data class HearingType(
@NotBlank
@JsonProperty("id")
val id: String,
@NotBlank
@JsonProperty("description")
val description: String,
@JsonProperty("welshDescription")
val welshDescription: String? = null,
)
| 3 | null | 1 | 1 | 629ae872de45051facfeb2a950ef684b90835e4d | 397 | court-hearing-event-receiver | MIT License |
mobile-ui/src/main/java/com/lekaha/simpletube/ui/model/BrowseDetailViewModel.kt | lekaha | 122,983,306 | false | null | package com.lekaha.simpletube.ui.model
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.lekaha.simpletube.presentation.ViewResponse
import com.lekaha.simpletube.presentation.browse.BrowseDetailSimpletubesContract
import com.lekaha.simpletube.presentation.model.SimpletubeSectionsView
class BrowseDetailViewModel(var detailPresenter: BrowseDetailSimpletubesContract.Presenter)
: ViewModel(), LifecycleObserver, BrowseDetailSimpletubesContract.View {
private var isProgressing: MutableLiveData<Boolean> = MutableLiveData()
private var occurredError: MutableLiveData<Throwable> = MutableLiveData()
private var simpletubeSections: MutableLiveData<SimpletubeSectionsView> = MutableLiveData()
private lateinit var browseDetailTitle: String
init {
detailPresenter.setView(this)
}
override fun getSimpletubeName(): String = browseDetailTitle
override fun setPresenter(presenter: BrowseDetailSimpletubesContract.Presenter) {
this.detailPresenter = presenter
this.detailPresenter.setView(this)
}
override fun onResponse(response: ViewResponse<SimpletubeSectionsView>) {
when(response.status) {
ViewResponse.Status.LOADING -> { isProgressing.value = true }
ViewResponse.Status.ERROR -> {
isProgressing.value = false
occurredError.value = response.error
}
ViewResponse.Status.SUCCESS -> {
isProgressing.value = false
simpletubeSections.value = response.data
}
}
}
fun isProgressing(): LiveData<Boolean> = isProgressing
fun occurredError(): LiveData<Throwable> = occurredError
fun fetchedData(): LiveData<SimpletubeSectionsView> = simpletubeSections
fun load(title: String) {
browseDetailTitle = title
detailPresenter.start()
}
override fun onCleared() {
detailPresenter.stop()
}
} | 0 | Kotlin | 1 | 2 | 6ee542991cb6d960e30c37b9b279a4f76c37b238 | 2,081 | youtube-like-video-player | MIT License |
app/src/main/java/com/group21/buggycontrol/Bluetooth_handler.kt | danielbara00 | 356,573,998 | false | null | package com.group21.buggycontrol
class Bluetooth_handler {
} | 2 | Kotlin | 0 | 0 | ceef3fbd7246eaa67fe0161f4c4a322d1b16630c | 61 | buggy-remote-controller | The Unlicense |
aoc2020/aoc2020-kotlin/src/main/kotlin/de/havox_design/aoc2020/day17/ConwayCubes.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 967489, "Java": 684008, "Scala": 57186, "Groovy": 40975, "Python": 25970} | package de.havox_design.aoc2020.day17
import de.havox_design.aoc.utils.kotlin.helpers.mapToInt
class ConwayCubes(private var filename: String) {
private val data = getResourceAsText(filename)
lateinit var lowerBounds: IntArray
lateinit var upperBounds: IntArray
lateinit var hyperspace: IntTrie
fun processPart1(): Any {
init()
repeat(6) { this.iteratePart1() }
return hyperspace
.count()
}
fun processPart2(): Any {
init()
repeat(6) { this.iteratePart2() }
return hyperspace
.count()
}
private fun init() {
lowerBounds = intArrayOf(0, 0, 0, 0)
upperBounds = intArrayOf(0, 0, data.lastIndex, data[0].lastIndex)
hyperspace = IntTrie.create(lowerBounds, upperBounds)
data
.forEachIndexed { y, row ->
row
.forEachIndexed { x, c ->
if (c == '#') {
hyperspace.add(intArrayOf(0, 0, y, x))
}
}
}
}
private fun iteratePart1() {
lowerBounds = lowerBounds
.mapToInt { it - 1 }
upperBounds = upperBounds
.mapToInt { it + 1 }
val newHyperspace = IntTrie
.create(lowerBounds, upperBounds)
iterateInner(0, newHyperspace)
hyperspace = newHyperspace
}
private fun iteratePart2() {
lowerBounds = lowerBounds
.mapToInt { it - 1 }
upperBounds = upperBounds
.mapToInt { it + 1 }
val newHyperspace = IntTrie
.create(lowerBounds, upperBounds)
(lowerBounds[0]..upperBounds[0])
.forEach { w ->
iterateInner(w, newHyperspace)
}
hyperspace = newHyperspace
}
private fun iterateInner(w: Int, newHyperspace: IntTrie) {
(lowerBounds[1]..upperBounds[1])
.forEach { z ->
(lowerBounds[2]..upperBounds[2])
.forEach { y ->
(lowerBounds[3]..upperBounds[3])
.forEach { x ->
val point = HyperspacePoint(intArrayOf(w, z, y, x))
val cell = if (hyperspace.contains(point.parts)) ACTIVE else INACTIVE
val count = hyperspace.countWithNeighbours(point.parts) - cell
if ((cell == ACTIVE && count in 2..3) || (cell == INACTIVE && count == 3)) {
newHyperspace.add(point.parts)
}
}
}
}
}
private fun getResourceAsText(path: String): List<String> =
this
.javaClass
.classLoader
.getResourceAsStream(path)!!
.bufferedReader()
.readLines()
companion object {
private const val ACTIVE = 1
private const val INACTIVE = 0
}
}
| 3 | Kotlin | 0 | 1 | 9019bc3c7f7822fbf8423cf689ca8ec76759a223 | 3,067 | advent-of-code | Apache License 2.0 |
app/src/main/java/br/com/siecola/androidproject02/network/OauthTokenInterceptor.kt | siecola | 246,328,556 | false | null | package br.com.siecola.androidproject02.network
import android.util.Log
import br.com.siecola.androidproject02.util.SharedPreferencesUtils
import okhttp3.Interceptor
import okhttp3.Response
private const val TAG = "OauthTokenInterceptor"
class OauthTokenInterceptor() : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val accessToken = SharedPreferencesUtils.getAccessToken()
if (accessToken != null) {
Log.i(TAG, "Using the existing token")
request = request.newBuilder()
.addHeader("Authorization", "Bearer ${accessToken}")
.build()
}
return chain.proceed(request)
}
} | 0 | Kotlin | 0 | 0 | 57fc03a1b0a49359132ce63abb4ea8fa59124230 | 736 | android_project02 | MIT License |
src/main/kotlin/pebloop/zoocraft/ZoocraftData.kt | Pebloop | 838,973,124 | false | {"Kotlin": 65182, "Java": 12951} | package pebloop.zoocraft
import net.minecraft.entity.Entity
import net.minecraft.entity.EntityType
import net.minecraft.entity.passive.RabbitEntity
import net.minecraft.util.TypeFilter
import pebloop.zoocraft.Zoocraft
class ZoocraftData {
val zooEntities: ArrayList<EntityType<*>> = ArrayList()
init {
if (Zoocraft.CONFIG.isRabbitCatchable)
zooEntities.add(EntityType.RABBIT)
if (Zoocraft.CONFIG.isPigCatchable)
zooEntities.add(EntityType.PIG)
if (Zoocraft.CONFIG.isCowCatchable)
zooEntities.add(EntityType.COW)
if (Zoocraft.CONFIG.isChickenCatchable)
zooEntities.add(EntityType.CHICKEN)
if (Zoocraft.CONFIG.isSheepCatchable)
zooEntities.add(EntityType.SHEEP)
}
fun addEntity(entity: EntityType<*>) {
zooEntities.add(entity)
}
fun removeEntity(entity: EntityType<*>) {
zooEntities.remove(entity)
}
fun getEntities(): ArrayList<EntityType<*>> {
return zooEntities
}
fun isCatchable(entity: EntityType<*>): Boolean {
return zooEntities.contains(entity)
}
} | 0 | Kotlin | 0 | 0 | 8bda77c2403e142c1a7f37aee3b7dba64e8b4db3 | 1,137 | zoocraft | Creative Commons Zero v1.0 Universal |
buildSrc/src/main/java/TestLibs.kt | muryno | 557,522,285 | false | {"Kotlin": 79104} | object TestLibs {
private val v = BuildDepVersions
//TEST -----------------------------------------------------------------------------------------------
const val JUNIT = "junit:junit:4.13.2"
const val CORE_TEST = "androidx.arch.core:core-testing:2.1.0"
const val MOCKITO_INLINE = "org.mockito:mockito-inline:4.5.1"
const val MOKITO_KOTLIN = "org.mockito.kotlin:mockito-kotlin:4.0.0"
const val MOCKK = "io.mockk:mockk:1.12.4"
const val IOMOCKK_ANDROID = "io.mockk:mockk-android:1.12.4"
const val TEST_RUNNER = "androidx.test:runner:1.4.0"
const val TEST_RUNNER_EXT = "androidx.test.ext:junit:1.1.3"
const val EXPRESSO_TEST = "androidx.test.espresso:espresso-core:3.4.0"
const val TEST_RULE = "androidx.test:core:1.4.0"
const val MOCKWEBSERVER = "com.squareup.okhttp3:mockwebserver:4.9.0"
const val kOTLINX_COUROUTINE = "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
const val kOTLINX_COUROUTINE_TEST = "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
const val HILT_ANDROID_COMPILER = "com.google.dagger:hilt-android-compiler:2.38.1"
//ANDROID TEST-----------------------------------------------------------------------------------------
const val JUNIT_ANDROID = "junit:junit:4.13.2"
const val TEST_RUNNER_ANDROID = "androidx.test:runner:1.4.0"
const val kOTLINX_COUROUTINE_ANDROID = "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
const val CoreTesting_ANDROID = "androidx.arch.core:core-testing:2.1.0"
const val Hilt_ANDROID = "com.google.dagger:hilt-android-testing:2.44"
const val Truth_ANDROID = "com.google.truth:truth:1.1.3"
const val JUNIT_EXT_ANDROID = "androidx.test.ext:junit:${v.JUNIT_EXT_ANDROID}"
const val EXPRESSO = "androidx.test.espresso:espresso-core:${v.EXPRESSO}"
const val COMPOSE_UI_TEST = "androidx.compose.ui:ui-test-junit4:${v.COMPOSE}"
//DEBUG -----------------------------------------------------------------------------------------
const val COMPOSE_TOOLING = "androidx.compose.ui:ui-tooling:${v.COMPOSE}"
} | 0 | Kotlin | 10 | 80 | 234d61043893bf451a6c71029fef59d48fb705b1 | 2,076 | CleanArchitecture_Modularization | MIT License |
app/src/main/java/com/nativemobilebits/loginflow/screens/LoginScreen.kt | Adith628 | 680,420,322 | false | null | package com.nativemobilebits.loginflow.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.nativemobilebits.loginflow.data.login.LoginViewModel
import com.nativemobilebits.loginflow.R
import com.nativemobilebits.loginflow.components.*
import com.nativemobilebits.loginflow.data.login.LoginUIEvent
import com.nativemobilebits.loginflow.navigation.PostOfficeAppRouter
import com.nativemobilebits.loginflow.navigation.Screen
import com.nativemobilebits.loginflow.navigation.SystemBackButtonHandler
@Composable
fun LoginScreen(loginViewModel: LoginViewModel = viewModel()) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Surface(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
.padding(28.dp)
) {
Column(
modifier = Modifier
.fillMaxSize()
) {
NormalTextComponent(value = stringResource(id = R.string.login))
HeadingTextComponent(value = stringResource(id = R.string.welcome))
Spacer(modifier = Modifier.height(20.dp))
MyTextFieldComponent(labelValue = stringResource(id = R.string.email),
painterResource(id = R.drawable.message),
onTextChanged = {
loginViewModel.onEvent(LoginUIEvent.EmailChanged(it))
},
errorStatus = loginViewModel.loginUIState.value.emailError
)
PasswordTextFieldComponent(
labelValue = stringResource(id = R.string.password),
painterResource(id = R.drawable.lock),
onTextSelected = {
loginViewModel.onEvent(LoginUIEvent.PasswordChanged(it))
},
errorStatus = loginViewModel.loginUIState.value.passwordError
)
Spacer(modifier = Modifier.height(40.dp))
UnderLinedTextComponent(value = stringResource(id = R.string.forgot_password))
Spacer(modifier = Modifier.height(40.dp))
ButtonComponent(
value = stringResource(id = R.string.login),
onButtonClicked = {
loginViewModel.onEvent(LoginUIEvent.LoginButtonClicked)
},
isEnabled = loginViewModel.allValidationsPassed.value
)
Spacer(modifier = Modifier.height(20.dp))
DividerTextComponent()
ClickableLoginTextComponent(tryingToLogin = false, onTextSelected = {
PostOfficeAppRouter.navigateTo(Screen.SignUpScreen)
})
}
}
if(loginViewModel.loginInProgress.value) {
CircularProgressIndicator()
}
}
SystemBackButtonHandler {
PostOfficeAppRouter.navigateTo(Screen.SignUpScreen)
}
}
@Preview
@Composable
fun LoginScreenPreview() {
LoginScreen()
} | 0 | Kotlin | 1 | 0 | 9f5015648d6dc237484a61a385ebe253a09dbaac | 3,653 | HospitalFinder | MIT License |
app/src/main/java/com/rphmelo/routeapp/extensions/CommonExtension.kt | Rphmelo | 278,460,237 | false | null | package com.rphmelo.routeapp.extensions
import android.content.Context
import com.rphmelo.routeapp.util.DialogUtil
fun Context.tryRun(message: String? = null, block: () -> Unit) {
try {
block()
} catch (e: Exception) {
DialogUtil.showMessageDialog(this, message)
}
} | 0 | Kotlin | 0 | 0 | 1ab1ff42f92490f1909606c2c4578f3bcfbda307 | 296 | RouteApp | MIT License |
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleRolesByKey.kt | slatekit | 55,942,000 | false | {"Kotlin": 2307012, "Shell": 14611, "Java": 14216, "Swift": 1555} | package test.setup
import kiit.apis.Api
import kiit.apis.Action
import kiit.apis.AuthModes
import kiit.common.auth.Roles
@Api(area = "samples", name = "roleskey", desc = "sample to test security", roles= ["admin"], auth = AuthModes.KEYED)
class SampleRolesByKey {
@Action(desc = "no roles allows access by anyone")
fun rolesNone(code:Int, tag:String): String {
return "rolesNone $code $tag"
}
@Action(desc = "* roles allows access by any authenticated in user", roles= [ Roles.ALL])
fun rolesAny(code:Int, tag:String): String {
return "rolesAny $code $tag"
}
@Action(desc = "allows access by specific role", roles= ["dev"])
fun rolesSpecific(code:Int, tag:String): String {
return "rolesSpecific $code $tag"
}
@Action(desc = "@parent refers to its parent role", roles= [Roles.PARENT])
fun rolesParent(code:Int, tag:String): String {
return "rolesParent $code $tag"
}
}
| 3 | Kotlin | 13 | 112 | d17b592aeb28c5eb837d894e98492c69c4697862 | 960 | slatekit | Apache License 2.0 |
app/src/main/java/uy/com/temperoni/recipes/ui/model/Recipe.kt | leandro-temperoni | 443,648,979 | false | null | package uy.com.temperoni.recipes.ui.model
/**
* @author <NAME>
*/
data class Recipe(val id: String,
val images: List<String>,
val ingredients: List<Ingredient>,
val introduction: String,
val name: String,
val instructions: List<Instruction>)
| 1 | Kotlin | 0 | 0 | 43253a02591b08e04f9be76abd19c58cfa5b422d | 335 | recipes-android | Apache License 2.0 |
src/main/kotlin/services/endpoints/TournamentStubV4.kt | MiniClem | 278,005,521 | false | null | package services.endpoints
import retrofit2.Call
import retrofit2.http.*
interface TournamentStubV4 {
/**
* Create a mock tournament code for the given tournament.
*
* @param count The number of codes to create (max 1000)
* @param tournamentId The tournament ID
*/
@POST("/lol/tournament-stub/v4/codes")
fun createMockTournamentCode(
@Query("count") count: Int = 1,
@Query("tournamentId") tournamentId: Long,
@Body TournamentCodeParameters: TournamentCodeParameters
): Call<List<String>>
/**
* Gets a mock list of lobby events by tournament code.
*
* @param tournamentCode The short code to look up lobby events for
*/
@GET("/lol/tournament-stub/v4/lobby-events/by-code/{tournamentCode}")
fun getLobbyEventsByCode(@Path("tournamentCode") tournamentCode: String): Call<LobbyEventDtoWrapper>
/**
* Creates a mock tournament provider and returns its ID.
* Providers will need to call this endpoint first to register their callback URL and their API key with the
* tournament system before any other tournament provider endpoints will work.
*/
@POST("/lol/tournament-stub/v4/providers")
fun createTournamentProvider(@Body ProviderRegistrationParameters: ProviderRegistrationParameters): Call<Int>
/**
* Creates a mock tournament and returns its ID.
*/
@POST("/lol/tournament-stub/v4/tournaments")
fun createMockTournament(@Body TournamentRegistrationParameters: TournamentRegistrationParameters): Call<Int>
}
/**
* @param allowedSummonerIds Optional list of encrypted summonerIds in order to validate the players eligible to join
* the lobby. NOTE: We currently do not enforce participants at the team level, but rather the aggregate of teamOne and
* teamTwo. We may add the ability to enforce at the team level in the future.
* @param metadata Optional string that may contain any data in any format, if specified at all. Used to denote any
* custom information about the game.
* @param teamSize The team size of the game. Valid values are 1-5.
* @param pickType The pick type of the game. (Legal values: BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT)
* @param mapType The map type of the game. (Legal values: SUMMONERS_RIFT, TWISTED_TREELINE, HOWLING_ABYSS)
* @param spectatorType The spectator type of the game. (Legal values: NONE, LOBBYONLY, ALL)
*/
data class TournamentCodeParameters(
val allowedSummonerIds: Set<String>,
val metadata: String,
val teamSize: Int,
val pickType: String,
val mapType: String,
val spectatorType: String
)
data class LobbyEventDtoWrapper(
val eventList: List<LobbyEventDto>
)
/**
* @param summonerId The summonerId that triggered the event (Encrypted)
* @param eventType The type of event that was triggered
* @param timestamp Timestamp from the event
*/
data class LobbyEventDto(
val summonerId: String,
val eventType: String,
val timestamp: String
)
/**
* @param region The region in which the provider will be running tournaments. (Legal values: BR, EUNE, EUW, JP, LAN,
* LAS, NA, OCE, PBE, RU, TR)
* @param url The provider's callback URL to which tournament game results in this region should be posted. The URL
* must be well-formed, use the http or https protocol, and use the default port for the protocol (http URLs must
* use port 80, https URLs must use port 443).
*/
data class ProviderRegistrationParameters(
val region: String,
val url: String
)
/**
* @param providerId The provider ID to specify the regional registered provider data to associate this tournament.
* @param name The optional name of the tournament.
*/
data class TournamentRegistrationParameters(
val providerId: Int,
val name: String
) | 0 | null | 1 | 4 | 75f0664713ded855285edb79bf844ff2f5be8665 | 3,830 | Kotlin-Riot-Api-Wrapper | Apache License 2.0 |
plugins/evaluation-plugin/src/com/intellij/cce/evaluable/golf/LineCompletionGolfFeature.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.cce.evaluable.golf
import com.intellij.cce.core.Language
import com.intellij.cce.core.Suggestion
import com.intellij.cce.core.SuggestionKind
import com.intellij.cce.evaluable.EvaluableFeatureBase
import com.intellij.cce.evaluable.StrategySerializer
import com.intellij.cce.evaluation.EvaluationStep
import com.intellij.cce.evaluation.step.SetupCompletionStep
import com.intellij.cce.evaluation.step.SetupFullLineStep
import com.intellij.cce.interpreter.FeatureInvoker
import com.intellij.cce.metric.Metric
import com.intellij.cce.metric.SuggestionsComparator
import com.intellij.cce.metric.createBenchmarkMetrics
import com.intellij.cce.processor.GenerateActionsProcessor
import com.intellij.cce.report.GeneratorDirectories
import com.intellij.cce.report.LineCompletionFileReportGenerator
import com.intellij.cce.workspace.storages.FeaturesStorage
import com.intellij.cce.workspace.storages.FullLineLogsStorage
import com.intellij.openapi.project.Project
class LineCompletionFeature : EvaluableFeatureBase<CompletionGolfStrategy>("line-completion") {
override fun getGenerateActionsProcessor(strategy: CompletionGolfStrategy): GenerateActionsProcessor = LineCompletionProcessor()
override fun getFeatureInvoker(project: Project, language: Language, strategy: CompletionGolfStrategy): FeatureInvoker =
LineCompletionActionsInvoker(project, language, strategy, true)
override fun getStrategySerializer(): StrategySerializer<CompletionGolfStrategy> = LineCompletionStrategySerializer()
override fun getFileReportGenerator(suggestionsComparators: List<SuggestionsComparator>,
filterName: String,
comparisonFilterName: String,
featuresStorages: List<FeaturesStorage>,
fullLineStorages: List<FullLineLogsStorage>,
dirs: GeneratorDirectories): LineCompletionFileReportGenerator {
return LineCompletionFileReportGenerator(filterName, comparisonFilterName, featuresStorages, fullLineStorages, dirs)
}
override fun getMetrics(): List<Metric> = createBenchmarkMetrics() + super.getMetrics()
override fun getSuggestionsComparator(language: Language): SuggestionsComparator = object : SuggestionsComparator {
override fun accept(suggestion: Suggestion, expected: String): Boolean = suggestion.kind != SuggestionKind.ANY
}
override fun getEvaluationSteps(language: Language, strategy: CompletionGolfStrategy): List<EvaluationStep> =
listOf(
SetupCompletionStep(
language = language.name,
completionType = strategy.completionType,
pathToZipModel = strategy.pathToZipModel
),
SetupFullLineStep()
)
} | 229 | null | 4931 | 15,571 | 92c8aad1c748d6741e2c8e326e76e68f3832f649 | 2,904 | intellij-community | Apache License 2.0 |
sdk-incubator-lib/src/main/java/cash/z/ecc/android/sdk/WalletCoordinator.kt | zcash | 151,763,639 | false | null | package cash.z.ecc.android.sdk.demoapp
import android.content.Context
import cash.z.ecc.android.sdk.Synchronizer
import cash.z.ecc.android.sdk.demoapp.model.PersistableWallet
import cash.z.ecc.android.sdk.demoapp.util.Twig
import cash.z.ecc.android.sdk.demoapp.util.fromResources
import cash.z.ecc.android.sdk.ext.onFirst
import cash.z.ecc.android.sdk.model.ZcashNetwork
import cash.z.ecc.android.sdk.model.defaultForNetwork
import co.electriccoin.lightwallet.client.model.LightWalletEndpoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.UUID
/**
* @param persistableWallet flow of the user's stored wallet. Null indicates that no wallet has been stored.
*/
class WalletCoordinator(context: Context, val persistableWallet: Flow<PersistableWallet?>) {
private val applicationContext = context.applicationContext
/*
* We want a global scope that is independent of the lifecycles of either
* WorkManager or the UI.
*/
@OptIn(DelicateCoroutinesApi::class)
private val walletScope = CoroutineScope(GlobalScope.coroutineContext + Dispatchers.Main)
private val synchronizerMutex = Mutex()
private val lockoutMutex = Mutex()
private val synchronizerLockoutId = MutableStateFlow<UUID?>(null)
private sealed class InternalSynchronizerStatus {
object NoWallet : InternalSynchronizerStatus()
class Available(val synchronizer: Synchronizer) : InternalSynchronizerStatus()
class Lockout(val id: UUID) : InternalSynchronizerStatus()
}
private val synchronizerOrLockoutId: Flow<Flow<InternalSynchronizerStatus>> = persistableWallet
.combine(synchronizerLockoutId) { persistableWallet: PersistableWallet?, lockoutId: UUID? ->
if (null != lockoutId) { // this one needs to come first
flowOf(InternalSynchronizerStatus.Lockout(lockoutId))
} else if (null == persistableWallet) {
flowOf(InternalSynchronizerStatus.NoWallet)
} else {
callbackFlow<InternalSynchronizerStatus.Available> {
val closeableSynchronizer = Synchronizer.new(
context = context,
zcashNetwork = persistableWallet.network,
lightWalletEndpoint = LightWalletEndpoint.defaultForNetwork(persistableWallet.network),
birthday = persistableWallet.birthday,
seed = persistableWallet.seedPhrase.toByteArray(),
alias = NEW_UI_SYNCHRONIZER_ALIAS
)
trySend(InternalSynchronizerStatus.Available(closeableSynchronizer))
awaitClose {
Twig.info { "Closing flow and stopping synchronizer" }
closeableSynchronizer.close()
}
}
}
}
/**
* Synchronizer for the Zcash SDK. Emits null until a wallet secret is persisted.
*
* Note that this synchronizer is closed as soon as it stops being collected. For UI use
* cases, see [WalletViewModel].
*/
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
val synchronizer: StateFlow<Synchronizer?> = synchronizerOrLockoutId
.flatMapLatest {
it
}
.map {
when (it) {
is InternalSynchronizerStatus.Available -> it.synchronizer
is InternalSynchronizerStatus.Lockout -> null
InternalSynchronizerStatus.NoWallet -> null
}
}
.stateIn(
walletScope,
SharingStarted.WhileSubscribed(),
null
)
/**
* Rescans the blockchain.
*
* In order for a rescan to occur, the synchronizer must be loaded already
* which would happen if the UI is collecting it.
*
* @return True if the rescan was performed and false if the rescan was not performed.
*/
suspend fun rescanBlockchain(): Boolean {
synchronizerMutex.withLock {
synchronizer.value?.let {
it.latestBirthdayHeight?.let { height ->
it.rewindToNearestHeight(height, true)
return true
}
}
}
return false
}
/**
* Resets persisted data in the SDK, but preserves the wallet secret. This will cause the
* WalletCoordinator to emit a new synchronizer instance.
*/
@OptIn(FlowPreview::class)
fun resetSdk() {
walletScope.launch {
lockoutMutex.withLock {
val lockoutId = UUID.randomUUID()
synchronizerLockoutId.value = lockoutId
synchronizerOrLockoutId
.flatMapConcat { it }
.filterIsInstance<InternalSynchronizerStatus.Lockout>()
.filter { it.id == lockoutId }
.onFirst {
synchronizerMutex.withLock {
val didDelete = Synchronizer.erase(
appContext = applicationContext,
network = ZcashNetwork.fromResources(applicationContext)
)
Twig.info { "SDK erase result: $didDelete" }
}
}
synchronizerLockoutId.value = null
}
}
}
// Allows for extension functions
companion object {
internal const val NEW_UI_SYNCHRONIZER_ALIAS = "new_ui"
}
}
| 2 | null | 9 | 51 | 45f1c473b2531ca47213657c9ef26d25fffeda1d | 6,451 | zcash-android-wallet-sdk | MIT License |
app/src/main/java/com/example/androiddevchallenge/ui/Shared.kt | natieklopper | 348,878,504 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.ui.theme.gutter
import dev.chrisbanes.accompanist.coil.CoilImage
@Composable
fun UrlImage(
url: String,
modifier: Modifier = Modifier
) {
CoilImage(
data = url,
contentDescription = "Image from the following URL: $url",
fadeIn = true,
alignment = Alignment.Center,
modifier = modifier,
contentScale = ContentScale.Crop
)
}
@Composable
fun Circle(
color: Color,
modifier: Modifier = Modifier
) {
Box(
modifier = modifier
.aspectRatio(1f)
.fillMaxWidth()
.padding(gutter * 2)
.composed {
size(50.dp)
.clip(CircleShape)
.background(color)
}
)
}
| 0 | Kotlin | 0 | 0 | f50a565b747e1116f142389ebb81a293870f2969 | 2,111 | compose-weatherbee | Apache License 2.0 |
compiler/testData/diagnostics/tests/callableReference/generic/genericFunctionsWithNullableTypes.kt | JakeWharton | 99,388,807 | false | null | // !CHECK_TYPE
// !DIAGNOSTICS: -UNUSED_PARAMETER, -UNUSED_VARIABLE
fun <T, R> foo(x: T): R = TODO()
fun <T, R> bar(x: T, y: R, f: (T) -> R): Pair<T, R?> = TODO()
inline fun <reified T, reified R> baz(x: T, y: R, f: (T) -> R) {}
data class Pair<A, B>(val a: A, val b: B)
fun <T> test(x: T) {
bar(1, "", ::foo).checkType { _<Pair<Int, String?>>() }
bar(null, "", ::foo).checkType { _<Pair<Nothing?, String?>>() }
bar(1, null, ::foo).checkType { _<Pair<Int, Nothing?>>() }
bar(null, null, ::foo).checkType { _<Pair<Nothing?, Nothing?>>() }
bar(1, x, ::foo).checkType { _<Pair<Int, T?>>() }
val s1: Pair<Int, String?> = bar(1, "", ::foo)
val (a: Int, b: String?) = bar(1, "", ::foo)
val s2: Pair<Int?, String?> = bar(null, null, ::foo)
baz<Int?, String?>(null, null, ::foo)
baz<Int, String?>(<!NULL_FOR_NONNULL_TYPE!>null<!>, null, ::foo)
baz<Int?, String>(null, <!NULL_FOR_NONNULL_TYPE!>null<!>, ::foo)
baz(null, "", ::foo)
baz(1, null, ::foo)
baz(null, null, ::foo)
val s3: Pair<Int, String?> = <!TYPE_MISMATCH, TYPE_MISMATCH!>bar(null, null, ::foo)<!>
val s4: Pair<Int?, String> = <!INITIALIZER_TYPE_MISMATCH, TYPE_MISMATCH, TYPE_MISMATCH!>bar(null, null, ::foo)<!>
val s5: Pair<Int, String> = <!INITIALIZER_TYPE_MISMATCH, TYPE_MISMATCH!>bar(1, "", ::foo)<!>
val (a1: Int, b1: String) = <!COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH!>bar(1, "", ::foo)<!>
}
| 184 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,435 | kotlin | Apache License 2.0 |
lite/examples/image_segmentation/android/lib_interpreter/src/main/java/org/tensorflow/lite/examples/imagesegmentation/tflite/ModelExecutionResult.kt | tensorflow | 141,200,054 | false | null | /*
* Copyright 2019 Google LLC
*
* 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.tensorflow.lite.examples.imagesegmentation.tflite
import android.graphics.Bitmap
data class ModelExecutionResult(
val bitmapResult: Bitmap,
val bitmapOriginal: Bitmap,
val bitmapMaskOnly: Bitmap,
val executionLog: String,
val itemsFound: Set<Int>
)
| 78 | null | 6061 | 5,860 | 56524742e739278cc52e2fcfc978e81d64cfcbd3 | 869 | examples | Apache License 2.0 |
app/src/main/java/com/roadster/roam/basesetup/base/BaseUseCase.kt | Atul206 | 510,028,347 | false | {"Kotlin": 118252} | package com.roadster.roam.basesetup.base
import com.neev.owner.network.ErrorEntity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
abstract class BaseUseCase<out Type, in Params> {
/**
* this should be called from Coroutine Context and implemented by all Use cases
* */
abstract suspend fun run(param: Params): Either<ErrorEntity, Type>
/**
* This is an operator function which is invoked from the viewModel ,
* it collects data from repo and pass the concrete data to viewModel
*/
operator fun invoke(
viewModelScope: CoroutineScope,
params: Params,
onResult: (Either<ErrorEntity, Type>) -> Unit
) {
viewModelScope.launch {
CoroutineScope(Dispatchers.IO)
.launch {
val result = run(params)
withContext(Dispatchers.Main)
{
onResult(result)
}
}
}
}
/**
* When our Network Call don't need any parameter pass this class
*/
class None
}
| 0 | Kotlin | 1 | 0 | 46ed3bd53e40ec7edf5a6063c6f8f8e556dc2225 | 1,201 | baserepo | MIT License |
Dispatcher/src/main/kotlin/net/milosvasic/dispatcher/executors/TaskExecutor.kt | milos85vasic | 81,421,926 | false | {"HTML": 324249, "Kotlin": 39697, "Shell": 174} | package net.milosvasic.dispatcher.executors
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
internal class TaskExecutor private constructor(corePoolSize: Int, maximumPoolSize: Int, queue: BlockingQueue<Runnable>) : ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0, TimeUnit.MILLISECONDS, queue) {
companion object {
fun instance(capacity: Int): TaskExecutor {
return TaskExecutor(capacity, capacity * 2, LinkedBlockingDeque<Runnable>())
}
}
} | 0 | HTML | 0 | 4 | bd446682d021bcf06892622aa7b620d4b8d4db9b | 611 | Dispatcher | Apache License 2.0 |
src/test/kotlin/ii887522/oxy/collection/LinkedListTest.kt | ii887522 | 350,205,715 | false | null | package ii887522.oxy.collection
import org.junit.Assert.*
import org.junit.Test
class LinkedListTest {
@Test fun `test set`() {
val numbers = LinkedList<Int>()
numbers.append(0)
numbers.append(1)
numbers.append(2)
assertThrows(IllegalArgumentException::class.java) { numbers[-1] = 3 }
assertThrows(IllegalArgumentException::class.java) { numbers[3] = 3 }
numbers[0] = 3
numbers[1] = 4
numbers[2] = 5
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(5, numberIterator.next())
}
@Test fun `test get`() {
val numbers = LinkedList<Int>()
numbers.append(0)
numbers.append(1)
numbers.append(2)
assertThrows(IllegalArgumentException::class.java) { numbers[-1] }
assertThrows(IllegalArgumentException::class.java) { numbers[3] }
assertEquals(0, numbers[0])
assertEquals(1, numbers[1])
assertEquals(2, numbers[2])
assertEquals(3, numbers.size)
}
@Test fun `test append`() {
val numbers = LinkedList<Int>()
numbers.append(0)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(1, numbers.size)
}
numbers.append(1)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(2, numbers.size)
}
numbers.append(2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(3, numbers.size)
}
}
@Test fun `test prepend`() {
val numbers = LinkedList<Int>()
numbers.prepend(0)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(1, numbers.size)
}
numbers.prepend(1)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(2, numbers.size)
}
numbers.prepend(2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(3, numbers.size)
}
}
@Test fun `test insert`() {
val numbers = LinkedList<Int>()
numbers.append(0)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(1, numbers.size)
}
numbers.append(1)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(2, numbers.size)
}
numbers.append(2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(3, numbers.size)
}
assertThrows(IllegalArgumentException::class.java) { numbers.insert(-1, 3) }
assertThrows(IllegalArgumentException::class.java) { numbers.insert(4, 3) }
numbers.insert(0, 3)
numbers.insert(4, 4)
numbers.insert(1, 5)
numbers.insert(2, 6)
numbers.insert(3, 7)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(5, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(6, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(7, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(8, numbers.size)
}
}
@Test fun `test remove`() {
val numbers = LinkedList<Int>()
assertThrows(IllegalStateException::class.java) { numbers.remove(0) }
numbers.append(0)
numbers.append(1)
numbers.append(2)
numbers.append(3)
numbers.append(4)
numbers.append(5)
numbers.append(6)
numbers.append(7)
numbers.append(8)
numbers.append(9)
numbers.append(10)
numbers.append(11)
numbers.append(12)
numbers.append(13)
numbers.append(14)
numbers.append(15)
assertThrows(IllegalArgumentException::class.java) { numbers.remove(-1) }
assertThrows(IllegalArgumentException::class.java) { numbers.remove(16) }
assertEquals(0, numbers.remove(0))
assertEquals(15, numbers.remove(14))
assertEquals(2, numbers.remove(1))
assertEquals(4, numbers.remove(2))
assertEquals(6, numbers.remove(3))
assertEquals(11, numbers.size)
}
@Test fun `test remove back`() {
val numbers = LinkedList<Int>()
assertThrows(IllegalStateException::class.java) { numbers.removeBack() }
numbers.append(0)
numbers.append(1)
numbers.append(2)
numbers.append(3)
numbers.append(4)
numbers.append(5)
assertEquals(5, numbers.removeBack())
assertEquals(4, numbers.removeBack())
assertEquals(3, numbers.removeBack())
assertEquals(2, numbers.removeBack())
assertEquals(1, numbers.removeBack())
assertEquals(0, numbers.removeBack())
assertFalse(numbers.iterator().hasNext())
assertEquals(0, numbers.size)
}
@Test fun `test remove front`() {
val numbers = LinkedList<Int>()
assertThrows(IllegalStateException::class.java) { numbers.removeFront() }
numbers.append(0)
numbers.append(1)
numbers.append(2)
numbers.append(3)
numbers.append(4)
numbers.append(5)
assertEquals(0, numbers.removeFront())
assertEquals(1, numbers.removeFront())
assertEquals(2, numbers.removeFront())
assertEquals(3, numbers.removeFront())
assertEquals(4, numbers.removeFront())
assertEquals(5, numbers.removeFront())
assertFalse(numbers.iterator().hasNext())
assertEquals(0, numbers.size)
}
@Test fun `test clear`() {
val numbers = LinkedList<Int>()
numbers.clear()
assertEquals(0, numbers.size)
numbers.append(0)
numbers.clear()
assertEquals(0, numbers.size)
}
@Test fun `test swap`() {
val numbers = LinkedList<Int>()
numbers.append(0)
numbers.append(1)
numbers.append(2)
numbers.append(3)
numbers.append(4)
numbers.swap(0, 0)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(0, 1)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(0, 2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(1, 2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(2, 2)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(2, 3)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(2, 4)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
numbers.swap(3, 4)
run {
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(4, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(3, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertFalse(numberIterator.hasNext())
}
assertThrows(java.lang.IllegalArgumentException::class.java) { numbers.swap(-1, 0) }
assertThrows(java.lang.IllegalArgumentException::class.java) { numbers.swap(5, 0) }
assertThrows(java.lang.IllegalArgumentException::class.java) { numbers.swap(0, -1) }
assertThrows(java.lang.IllegalArgumentException::class.java) { numbers.swap(0, 5) }
assertThrows(java.lang.IllegalArgumentException::class.java) { numbers.swap(1, 0) }
}
@Test fun `test iterator`() {
val numbers = LinkedList<Int>()
numbers.append(0)
numbers.append(1)
numbers.append(2)
val numberIterator = numbers.iterator()
assertTrue(numberIterator.hasNext())
assertEquals(0, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(1, numberIterator.next())
assertTrue(numberIterator.hasNext())
assertEquals(2, numberIterator.next())
assertFalse(numberIterator.hasNext())
assertEquals(3, numbers.size)
}
}
| 0 | Kotlin | 0 | 0 | 12dc0748d78e95dc6f465fa337378bd32b465191 | 13,573 | oxy | MIT License |
app/src/main/java/com/msg/gcms/presentation/base/BaseActivity.kt | GSM-MSG | 465,292,111 | false | null | package com.msg.gfo_v2.gfo.ui.base
import android.os.Bundle
import android.os.PersistableBundle
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
abstract class BaseActivity<T: ViewDataBinding>(
@LayoutRes private val layoutResId: Int
): AppCompatActivity() {
protected lateinit var binding: T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, layoutResId)
binding.lifecycleOwner = this
viewSetting()
observeEvent()
}
abstract fun viewSetting()
abstract fun observeEvent()
protected fun shortToast(msg: String){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
protected fun longToast(msg: String){
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
} | 8 | Kotlin | 0 | 8 | 65ba9a3e762676b9032ae8031f937e2b338b78f0 | 1,000 | GCMS-Android | MIT License |
ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt | ktorio | 40,136,600 | false | null | package io.ktor.auth.jwt
import com.auth0.jwk.*
import com.auth0.jwt.*
import com.auth0.jwt.algorithms.*
import com.nhaarman.mockito_kotlin.*
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.testing.*
import org.junit.Test
import java.security.*
import java.security.interfaces.*
import java.util.concurrent.*
import kotlin.test.*
class JWTAuthTest {
@Test
fun testJwtNoAuth() {
withApplication {
application.configureServerJwt()
val response = handleRequest {
uri = "/"
}
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtSuccess() {
withApplication {
application.configureServerJwt()
val token = getToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtSuccessWithCustomScheme() {
withApplication {
application.configureServerJwt {
authSchemes("Bearer", "Token")
}
val token = getToken(scheme = "Token")
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtSuccessWithCustomSchemeWithDifferentCases() {
withApplication {
application.configureServerJwt {
authSchemes("Bearer", "tokEN")
}
val token = getToken(scheme = "TOKen")
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtAlgorithmMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false"))
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAudienceMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtIssuerMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkNoAuth() {
withApplication {
application.configureServerJwk()
val response = handleRequest {
uri = "/"
}
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkSuccess() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwkSuccessNoIssuer() {
withApplication {
application.configureServerJwkNoIssuer(mock = true)
val token = getJwkToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtAuthSchemeMismatch() {
withApplication {
application.configureServerJwt()
val token = getToken().removePrefix("Bearer ")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAuthSchemeMismatch2() {
withApplication {
application.configureServerJwt()
val token = getToken("Token")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAuthSchemeMistake() {
withApplication {
application.configureServerJwt()
val token = getToken().replace("Bearer", "Bearer:")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtBlobPatternMismatch() {
withApplication {
application.configureServerJwt()
val token = getToken().let {
val i = it.length - 2
it.replaceRange(i..i + 1, " ")
}
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAuthSchemeMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(false)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAuthSchemeMistake() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(true).replace("Bearer", "Bearer:")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkBlobPatternMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(true).let {
val i = it.length - 2
it.replaceRange(i..i + 1, " ")
}
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAlgorithmMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false"))
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAudienceMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkIssuerMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun verifyWithMock() {
val token = getJwkToken(prefix = false)
val provider = getJwkProviderMock()
val kid = JWT.decode(token).keyId
val jwk = provider.get(kid)
val algorithm = jwk.makeAlgorithm()
val verifier = JWT.require(algorithm).withIssuer(issuer).build()
verifier.verify(token)
}
@Test
fun verifyNullAlgorithmWithMock() {
val token = getJwkToken(prefix = false)
val provider = getJwkProviderNullAlgorithmMock()
val kid = JWT.decode(token).keyId
val jwk = provider.get(kid)
val algorithm = jwk.makeAlgorithm()
val verifier = JWT.require(algorithm).withIssuer(issuer).build()
verifier.verify(token)
}
private fun verifyResponseUnauthorized(response: TestApplicationCall) {
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.Unauthorized, response.response.status())
assertNull(response.response.content)
}
private fun TestApplicationEngine.handleRequestWithToken(token: String): TestApplicationCall {
return handleRequest {
uri = "/"
addHeader(HttpHeaders.Authorization, token)
}
}
private fun Application.configureServerJwk(mock: Boolean = false) = configureServer {
jwt {
[email protected] = [email protected]
verifier(if (mock) getJwkProviderMock() else makeJwkProvider(), issuer)
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
}
}
private fun Application.configureServerJwkNoIssuer(mock: Boolean = false) = configureServer {
jwt {
[email protected] = [email protected]
verifier(if (mock) getJwkProviderMock() else makeJwkProvider())
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
}
}
private fun Application.configureServerJwt(extra: JWTAuthenticationProvider.() -> Unit = {}) = configureServer {
jwt {
[email protected] = [email protected]
verifier(makeJwtVerifier())
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
extra()
}
}
private fun Application.configureServer(authBlock: (Authentication.Configuration.() -> Unit)) {
install(Authentication) {
authBlock(this)
}
routing {
authenticate {
get("/") {
val principal = call.authentication.principal<JWTPrincipal>()!!
principal.payload
//val subjectString = principal.payload.subject.removePrefix("auth0|")
//println(subjectString)
call.respondText("Secret info")
}
}
}
}
private val algorithm = Algorithm.HMAC256("secret")
private val keyPair = KeyPairGenerator.getInstance("RSA").apply {
initialize(2048, SecureRandom())
}.generateKeyPair()
private val jwkAlgorithm = Algorithm.RSA256(keyPair.public as RSAPublicKey, keyPair.private as RSAPrivateKey)
private val issuer = "https://jwt-provider-domain/"
private val audience = "jwt-audience"
private val realm = "ktor jwt auth test"
private fun makeJwkProvider(): JwkProvider = JwkProviderBuilder(issuer)
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
private fun makeJwtVerifier(): JWTVerifier = JWT
.require(algorithm)
.withAudience(audience)
.withIssuer(issuer)
.build()
private val kid = "<KEY>"
private fun getJwkProviderNullAlgorithmMock(): JwkProvider {
val jwk = mock<Jwk> {
on { publicKey } doReturn keyPair.public
}
return mock {
on { get(kid) } doReturn jwk
}
}
private fun getJwkProviderMock(): JwkProvider {
val jwk = mock<Jwk> {
on { algorithm } doReturn jwkAlgorithm.name
on { publicKey } doReturn keyPair.public
}
return mock {
on { get(kid) } doReturn jwk
}
}
private fun getJwkToken(prefix: Boolean = true) = (if (prefix) "Bearer " else "") + JWT.create()
.withAudience(audience)
.withIssuer(issuer)
.withKeyId(kid)
.sign(jwkAlgorithm)
private fun getToken(scheme: String = "Bearer") = "$scheme " + JWT.create()
.withAudience(audience)
.withIssuer(issuer)
.sign(algorithm)
}
| 302 | null | 806 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 12,614 | ktor | Apache License 2.0 |
ktor-server/ktor-server-plugins/ktor-server-auth-jwt/jvm/test/io/ktor/server/auth/jwt/JWTAuthTest.kt | ktorio | 40,136,600 | false | null | package io.ktor.auth.jwt
import com.auth0.jwk.*
import com.auth0.jwt.*
import com.auth0.jwt.algorithms.*
import com.nhaarman.mockito_kotlin.*
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.testing.*
import org.junit.Test
import java.security.*
import java.security.interfaces.*
import java.util.concurrent.*
import kotlin.test.*
class JWTAuthTest {
@Test
fun testJwtNoAuth() {
withApplication {
application.configureServerJwt()
val response = handleRequest {
uri = "/"
}
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtSuccess() {
withApplication {
application.configureServerJwt()
val token = getToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtSuccessWithCustomScheme() {
withApplication {
application.configureServerJwt {
authSchemes("Bearer", "Token")
}
val token = getToken(scheme = "Token")
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtSuccessWithCustomSchemeWithDifferentCases() {
withApplication {
application.configureServerJwt {
authSchemes("Bearer", "tokEN")
}
val token = getToken(scheme = "TOKen")
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtAlgorithmMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false"))
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAudienceMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtIssuerMismatch() {
withApplication {
application.configureServerJwt()
val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkNoAuth() {
withApplication {
application.configureServerJwk()
val response = handleRequest {
uri = "/"
}
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkSuccess() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwkSuccessNoIssuer() {
withApplication {
application.configureServerJwkNoIssuer(mock = true)
val token = getJwkToken()
val response = handleRequestWithToken(token)
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.OK, response.response.status())
assertNotNull(response.response.content)
}
}
@Test
fun testJwtAuthSchemeMismatch() {
withApplication {
application.configureServerJwt()
val token = getToken().removePrefix("Bearer ")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAuthSchemeMismatch2() {
withApplication {
application.configureServerJwt()
val token = getToken("Token")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtAuthSchemeMistake() {
withApplication {
application.configureServerJwt()
val token = getToken().replace("Bearer", "Bearer:")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwtBlobPatternMismatch() {
withApplication {
application.configureServerJwt()
val token = getToken().let {
val i = it.length - 2
it.replaceRange(i..i + 1, " ")
}
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAuthSchemeMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(false)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAuthSchemeMistake() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(true).replace("Bearer", "Bearer:")
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkBlobPatternMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = getJwkToken(true).let {
val i = it.length - 2
it.replaceRange(i..i + 1, " ")
}
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAlgorithmMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience(audience).withIssuer(issuer).sign(Algorithm.HMAC256("false"))
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkAudienceMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience("wrong").withIssuer(issuer).sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun testJwkIssuerMismatch() {
withApplication {
application.configureServerJwk(mock = true)
val token = JWT.create().withAudience(audience).withIssuer("wrong").sign(algorithm)
val response = handleRequestWithToken(token)
verifyResponseUnauthorized(response)
}
}
@Test
fun verifyWithMock() {
val token = getJwkToken(prefix = false)
val provider = getJwkProviderMock()
val kid = JWT.decode(token).keyId
val jwk = provider.get(kid)
val algorithm = jwk.makeAlgorithm()
val verifier = JWT.require(algorithm).withIssuer(issuer).build()
verifier.verify(token)
}
@Test
fun verifyNullAlgorithmWithMock() {
val token = getJwkToken(prefix = false)
val provider = getJwkProviderNullAlgorithmMock()
val kid = JWT.decode(token).keyId
val jwk = provider.get(kid)
val algorithm = jwk.makeAlgorithm()
val verifier = JWT.require(algorithm).withIssuer(issuer).build()
verifier.verify(token)
}
private fun verifyResponseUnauthorized(response: TestApplicationCall) {
assertTrue(response.requestHandled)
assertEquals(HttpStatusCode.Unauthorized, response.response.status())
assertNull(response.response.content)
}
private fun TestApplicationEngine.handleRequestWithToken(token: String): TestApplicationCall {
return handleRequest {
uri = "/"
addHeader(HttpHeaders.Authorization, token)
}
}
private fun Application.configureServerJwk(mock: Boolean = false) = configureServer {
jwt {
[email protected] = [email protected]
verifier(if (mock) getJwkProviderMock() else makeJwkProvider(), issuer)
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
}
}
private fun Application.configureServerJwkNoIssuer(mock: Boolean = false) = configureServer {
jwt {
[email protected] = [email protected]
verifier(if (mock) getJwkProviderMock() else makeJwkProvider())
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
}
}
private fun Application.configureServerJwt(extra: JWTAuthenticationProvider.() -> Unit = {}) = configureServer {
jwt {
[email protected] = [email protected]
verifier(makeJwtVerifier())
validate { credential ->
when {
credential.payload.audience.contains(audience) -> JWTPrincipal(credential.payload)
else -> null
}
}
extra()
}
}
private fun Application.configureServer(authBlock: (Authentication.Configuration.() -> Unit)) {
install(Authentication) {
authBlock(this)
}
routing {
authenticate {
get("/") {
val principal = call.authentication.principal<JWTPrincipal>()!!
principal.payload
//val subjectString = principal.payload.subject.removePrefix("auth0|")
//println(subjectString)
call.respondText("Secret info")
}
}
}
}
private val algorithm = Algorithm.HMAC256("secret")
private val keyPair = KeyPairGenerator.getInstance("RSA").apply {
initialize(2048, SecureRandom())
}.generateKeyPair()
private val jwkAlgorithm = Algorithm.RSA256(keyPair.public as RSAPublicKey, keyPair.private as RSAPrivateKey)
private val issuer = "https://jwt-provider-domain/"
private val audience = "jwt-audience"
private val realm = "ktor jwt auth test"
private fun makeJwkProvider(): JwkProvider = JwkProviderBuilder(issuer)
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
private fun makeJwtVerifier(): JWTVerifier = JWT
.require(algorithm)
.withAudience(audience)
.withIssuer(issuer)
.build()
private val kid = "<KEY>"
private fun getJwkProviderNullAlgorithmMock(): JwkProvider {
val jwk = mock<Jwk> {
on { publicKey } doReturn keyPair.public
}
return mock {
on { get(kid) } doReturn jwk
}
}
private fun getJwkProviderMock(): JwkProvider {
val jwk = mock<Jwk> {
on { algorithm } doReturn jwkAlgorithm.name
on { publicKey } doReturn keyPair.public
}
return mock {
on { get(kid) } doReturn jwk
}
}
private fun getJwkToken(prefix: Boolean = true) = (if (prefix) "Bearer " else "") + JWT.create()
.withAudience(audience)
.withIssuer(issuer)
.withKeyId(kid)
.sign(jwkAlgorithm)
private fun getToken(scheme: String = "Bearer") = "$scheme " + JWT.create()
.withAudience(audience)
.withIssuer(issuer)
.sign(algorithm)
}
| 302 | null | 806 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 12,614 | ktor | Apache License 2.0 |
frontend/analyzer/src/commonMain/kotlin/checker/CheckExpr.kt | aripiprazole | 328,030,547 | false | null | package org.plank.analyzer.checker
import org.plank.analyzer.element.TypedAccessExpr
import org.plank.analyzer.element.TypedAssignExpr
import org.plank.analyzer.element.TypedBlockExpr
import org.plank.analyzer.element.TypedCallExpr
import org.plank.analyzer.element.TypedConstExpr
import org.plank.analyzer.element.TypedDerefExpr
import org.plank.analyzer.element.TypedExpr
import org.plank.analyzer.element.TypedGetExpr
import org.plank.analyzer.element.TypedGroupExpr
import org.plank.analyzer.element.TypedIfExpr
import org.plank.analyzer.element.TypedInstanceExpr
import org.plank.analyzer.element.TypedMatchExpr
import org.plank.analyzer.element.TypedRefExpr
import org.plank.analyzer.element.TypedSetExpr
import org.plank.analyzer.element.TypedSizeofExpr
import org.plank.analyzer.infer.AppTy
import org.plank.analyzer.infer.FunTy
import org.plank.analyzer.infer.PtrTy
import org.plank.analyzer.infer.Scheme
import org.plank.analyzer.infer.Subst
import org.plank.analyzer.infer.Ty
import org.plank.analyzer.infer.VarTy
import org.plank.analyzer.infer.ap
import org.plank.analyzer.infer.arr
import org.plank.analyzer.infer.boolTy
import org.plank.analyzer.infer.chainParameters
import org.plank.analyzer.infer.nullSubst
import org.plank.analyzer.infer.ty
import org.plank.analyzer.infer.ungeneralize
import org.plank.analyzer.infer.unitTy
import org.plank.syntax.element.AccessExpr
import org.plank.syntax.element.AssignExpr
import org.plank.syntax.element.BlockExpr
import org.plank.syntax.element.CallExpr
import org.plank.syntax.element.ConstExpr
import org.plank.syntax.element.DerefExpr
import org.plank.syntax.element.Expr
import org.plank.syntax.element.GetExpr
import org.plank.syntax.element.GroupExpr
import org.plank.syntax.element.IfExpr
import org.plank.syntax.element.InstanceExpr
import org.plank.syntax.element.MatchExpr
import org.plank.syntax.element.RefExpr
import org.plank.syntax.element.SetExpr
import org.plank.syntax.element.SizeofExpr
import org.plank.syntax.element.orEmpty
import org.plank.syntax.element.toIdentifier
fun TypeCheck.checkExpr(expr: Expr): TypedExpr {
return when (expr) {
is SizeofExpr -> TypedSizeofExpr(checkTy(expr.type.ty()), expr.loc)
is RefExpr -> TypedRefExpr(checkExpr(expr.value), expr.loc)
is GroupExpr -> TypedGroupExpr(checkExpr(expr.value), expr.loc)
is DerefExpr -> {
val value = checkExpr(expr.value)
val ty = value.ty as? PtrTy ?: return violate(expr.value, TypeIsNotPointer(value.ty))
TypedDerefExpr(value, ty.arg, expr.loc)
}
is ConstExpr -> {
val (ty) = infer(expr)
TypedConstExpr(expr.value, ty, expr.loc)
}
is BlockExpr -> scoped(ClosureScope("Block".toIdentifier(), scope)) {
val stmts = expr.stmts.map(::checkStmt)
val value = checkExpr(expr.value ?: ConstExpr(Unit))
TypedBlockExpr(stmts, value, references, expr.loc)
}
is AccessExpr -> {
val scope = scope.lookupModule(expr.module.orEmpty().toIdentifier()) ?: scope
val variable = scope.lookupVariable(expr.name)
?: return violate(expr, UnresolvedVariable(expr.name))
if (!variable.isInScope && !variable.declaredIn.isTopLevelScope) {
scope.references[variable.name] = variable.ty
}
TypedAccessExpr(variable, nullSubst(), instantiate(variable.scheme), expr.loc)
}
is IfExpr -> {
val location = expr.loc
val cond = checkExpr(expr.cond)
if (boolTy != cond.ty) {
return violate(cond, TypeMismatch(boolTy, cond.ty))
}
val thenBranch = checkBranch(expr.thenBranch)
val elseBranch = expr.elseBranch?.let { checkBranch(it) }
?: return TypedIfExpr(cond, thenBranch, null, thenBranch.ty, location)
val subst = unify(thenBranch.ty, elseBranch.ty)
val ty = thenBranch.ty ap subst
if (ty != elseBranch.ty ap subst) {
return violate(elseBranch, TypeMismatch(ty, elseBranch.ty ap subst))
}
TypedIfExpr(cond, thenBranch, elseBranch, ty, location) ap subst
}
is AssignExpr -> {
val value = checkExpr(expr.value)
val scope = scope.lookupModule(expr.module.orEmpty().toIdentifier()) ?: scope
val variable = scope.lookupVariable(expr.name)
?: return violate(expr, UnresolvedVariable(expr.name))
TypedAccessExpr(variable, nullSubst(), instantiate(variable.scheme), expr.loc)
if (!variable.mutable) {
violate<TypedExpr>(expr.value, CanNotReassignImmutableVariable(variable.name))
}
val t1 = variable.ty
val s1 = unify(value.ty, t1)
if (t1 ap s1 != value.ty) {
return violate(value, TypeMismatch(t1 ap s1, value.ty))
}
return TypedAssignExpr(scope, variable.name, value, value.ty, expr.loc)
}
is GetExpr -> {
val receiver = checkExpr(expr.receiver)
val property = expr.property
val info = lookupInfo(receiver.ty)
?: return violate(receiver, UnresolvedType(receiver.ty))
val struct = info.getAs<StructInfo>()
?: return violate(receiver, TypeIsNotStructAndCanNotGet(expr.property, receiver.ty))
val member = struct.members[expr.property]
?: return violate(property, UnresolvedStructMember(expr.property, struct))
TypedGetExpr(receiver, member.name, struct, member.ty, expr.loc)
}
is SetExpr -> {
val receiver = checkExpr(expr.receiver)
val value = checkExpr(expr.value)
val property = expr.property
val info = lookupInfo(receiver.ty)
?: return violate(receiver, UnresolvedType(receiver.ty))
val struct = info.getAs<StructInfo>()
?: return violate(receiver, TypeIsNotStructAndCanNotGet(expr.property, receiver.ty))
val member = struct.members[expr.property]
?: return violate(property, UnresolvedStructMember(expr.property, struct))
if (!member.mutable) {
violate<TypedExpr>(property, CanNotReassignImmutableStructMember(member.name, struct))
}
if (member.ty != value.ty) {
violate<TypedExpr>(value, TypeMismatch(member.ty, value.ty))
}
TypedSetExpr(receiver, member.name, value, struct, member.ty, expr.loc)
}
is InstanceExpr -> {
val structTy = checkTy(expr.type.ty())
val info = lookupInfo(structTy) ?: return violate(expr.type, UnresolvedType(structTy))
val struct = info.getAs<StructInfo>() ?: return violate(expr.type, TypeIsNotStruct(structTy))
val ty = instantiate(
Scheme(
struct.generics.map { it.text }.toSet(),
struct.generics.fold(structTy.ungeneralize() as Ty) { acc, next ->
AppTy(acc, VarTy(next.text))
}
),
)
var subst = Subst()
val arguments = expr.arguments.mapValues { (name, expr) ->
val value = checkExpr(expr)
val property = struct.members[name]
?: return violate(name, UnresolvedStructMember(name, struct))
subst = subst compose unify(property.ty, value.ty)
val propertyTy = property.ty ap subst
if (propertyTy != value.ty) {
return violate(value, TypeMismatch(propertyTy, value.ty))
}
value
}
TypedInstanceExpr(arguments, struct, ty, expr.loc) ap subst
}
is CallExpr -> {
val callee = checkExpr(expr.callee)
val ty = callee.ty as? FunTy ?: return violate(callee, TypeIsNotCallable(callee.ty))
val parameters = ty.chainParameters()
if (
callee is TypedAccessExpr &&
callee.variable is InlineVariable &&
parameters.size == expr.arguments.size
) {
val variable = callee.variable
val arguments = expr.arguments.map(::checkExpr)
arguments.zip(parameters).forEach { (arg, param) ->
if (param != arg.ty) {
violate<TypedExpr>(arg, TypeMismatch(param, arg.ty))
}
}
return variable.inlineCall(arguments)
}
expr.arguments
.ifEmpty { listOf(ConstExpr(Unit)) }
.map { checkExpr(it) }
.foldIndexed(callee) { i, acc, argument ->
val t1 = acc.ty
val tv = fresh()
val t2 = parameters.elementAtOrNull(i) ?: run {
violate<TypedExpr>(argument, IncorrectArity(parameters.size, i + 1))
argument.ty
}
val s1 = unify(t2, argument.ty)
val s2 = unify((t2 ap s1) arr tv, t1 ap s1)
TypedCallExpr(acc, argument, tv ap s2, expr.loc) ap (s2 compose s1)
}
}
is MatchExpr -> {
val subject = checkExpr(expr.subject)
when {
expr.patterns.isEmpty() -> {
TypedMatchExpr(subject, emptyMap(), unitTy, expr.loc)
}
else -> {
val patterns = expr.patterns.entries.associate { (pattern, value) ->
scoped(PatternScope(pattern, scope)) {
checkPattern(pattern, subject) to checkExpr(value)
}
}
var s = nullSubst()
val fst = patterns.values.first()
val ty = patterns.values.drop(1).fold(fst.ty) { acc, next ->
s = s compose unify(next.ty, acc)
if (acc != next.ty ap s) {
violate<TypedExpr>(next, TypeMismatch(acc, next.ty ap s))
}
acc
}
TypedMatchExpr(subject, patterns, ty ap s, expr.loc) ap s
}
}
}
}
}
| 3 | null | 1 | 56 | df1e88540f19f6a3878b6395084c7508070ab41d | 9,365 | plank | MIT License |
examples/QuickStart/app/src/main/java/com/ntt/skyway/example/quickstart/MainActivity.kt | skyway | 594,002,280 | false | null | package com.ntt.skyway.example.quickstart
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.ntt.skyway.core.SkyWayContext
import com.ntt.skyway.core.channel.Publication
import com.ntt.skyway.core.content.Stream
import com.ntt.skyway.core.content.local.source.AudioSource
import com.ntt.skyway.core.content.local.source.CameraSource
import com.ntt.skyway.core.content.remote.RemoteVideoStream
import com.ntt.skyway.core.content.sink.SurfaceViewRenderer
import com.ntt.skyway.core.util.Logger
import com.ntt.skyway.room.RoomPublication
import com.ntt.skyway.room.member.LocalRoomMember
import com.ntt.skyway.room.member.RoomMember
import com.ntt.skyway.room.p2p.P2PRoom
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
class MainActivity : AppCompatActivity() {
private val scope = CoroutineScope(Dispatchers.IO)
private var localRoomMember: LocalRoomMember? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
scope.launch {
val option = SkyWayContext.Options(
authToken = "YOUR_TOKEN",
logLevel = Logger.LogLevel.VERBOSE
)
val result = SkyWayContext.setup(applicationContext, option)
if (result) {
Log.d("App", "Setup succeed")
}
val device = CameraSource.getFrontCameras(applicationContext).first()
// camera映像のキャプチャを開始します
val cameraOption = CameraSource.CapturingOptions(800, 800)
CameraSource.startCapturing(applicationContext, device, cameraOption)
// 描画やpublishが可能なStreamを作成します
val localVideoStream = CameraSource.createStream()
// SurfaceViewRenderer を取得して描画します。
runOnUiThread {
val localVideoRenderer = findViewById<SurfaceViewRenderer>(R.id.local_renderer)
localVideoRenderer.setup()
localVideoStream.addRenderer(localVideoRenderer)
}
AudioSource.start()
// publishが可能なStreamを作成します
val localAudioStream = AudioSource.createStream()
val room = P2PRoom.findOrCreate(name = "room")
val memberInit = RoomMember.Init(name = "member" + UUID.randomUUID())
localRoomMember = room?.join(memberInit)
room?.publications?.forEach {
if(it.publisher?.id == localRoomMember?.id) return@forEach
subscribe(it)
}
room?.onStreamPublishedHandler = Any@{
Log.d("room", "onStreamPublished: ${it.id}")
if (it.publisher?.id == localRoomMember?.id) {
return@Any
}
subscribe(it)
}
localRoomMember?.publish(localVideoStream)
}
}
private fun subscribe(publication: RoomPublication) {
scope.launch {
// Publicationをsubscribeします
val subscription = localRoomMember?.subscribe(publication)
runOnUiThread {
val remoteVideoRenderer =
findViewById<SurfaceViewRenderer>(R.id.remote_renderer)
remoteVideoRenderer.setup()
val remoteStream = subscription?.stream
when(remoteStream?.contentType) {
// コンポーネントへの描画
Stream.ContentType.VIDEO -> (remoteStream as RemoteVideoStream).addRenderer(remoteVideoRenderer)
else -> {}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 38a7202a2c3e7a2367a332f822b1f54a8c7bb5de | 3,728 | android-sdk | MIT License |
app/src/androidTest/java/com/steleot/jetpackcompose/playground/compose/ui/LocalLifecycleOwnerScreenTest.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.compose.ui
import androidx.compose.ui.test.junit4.createComposeRule
import com.steleot.jetpackcompose.playground.compose.theme.TestTheme
import org.junit.Rule
import org.junit.Test
class LocalLifecycleOwnerScreenTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun testLocalLifecycleOwnerScreen() {
composeTestRule.setContent {
TestTheme {
LocalLifecycleOwnerScreen()
}
}
// todo
}
} | 1 | null | 46 | 346 | 0161d9c7bf2eee53270ba2227a61d71ba8292ad0 | 533 | Jetpack-Compose-Playground | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/client/smtss/SmtssClient.kt | navikt | 192,538,863 | false | {"Kotlin": 412342, "Dockerfile": 277} | package no.nav.syfo.client
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.accept
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import net.logstash.logback.argument.StructuredArguments
import no.nav.syfo.log
import no.nav.syfo.util.LoggingMeta
import java.net.http.HttpResponse
class SmtssClient(
private val endpointUrl: String,
private val accessTokenClientV2: AccessTokenClientV2,
private val resourceId: String,
private val httpClient: HttpClient,
) {
suspend fun findBestTssIdEmottak(
samhandlerFnr: String,
samhandlerOrgName: String,
loggingMeta: LoggingMeta,
sykmeldingId: String,
): String? {
val accessToken = accessTokenClientV2.getAccessTokenV2(resourceId)
val httpResponse = httpClient.get("$endpointUrl/api/v1/samhandler/emottak") {
accept(ContentType.Application.Json)
header("Authorization", "Bearer $accessToken")
header("requestId", sykmeldingId)
header("samhandlerFnr", samhandlerFnr)
header("samhandlerOrgName", samhandlerOrgName)
}
return getResponse(httpResponse, loggingMeta)
}
suspend fun findBestTssInfotrygdId(
samhandlerFnr: String,
samhandlerOrgName: String,
loggingMeta: LoggingMeta,
sykmeldingId: String,
): String? {
val accessToken = accessTokenClientV2.getAccessTokenV2(resourceId)
val httpResponse = httpClient.get("$endpointUrl/api/v1/samhandler/infotrygd") {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
header("Authorization", "Bearer $accessToken")
header("requestId", sykmeldingId)
header("samhandlerFnr", samhandlerFnr)
header("samhandlerOrgName", samhandlerOrgName)
}
return getResponse(httpResponse, loggingMeta)
}
private suspend fun getResponse(httpResponse: io.ktor.client.statement.HttpResponse, loggingMeta: LoggingMeta): String? {
return when (httpResponse.status) {
HttpStatusCode.OK -> {
httpResponse.body<TSSident>().tssid
}
HttpStatusCode.NotFound -> {
log.info(
"smtss responded with {} for {}",
httpResponse.status,
StructuredArguments.fields(loggingMeta),
)
null
}
else -> {
log.error("Error getting TSS-id ${httpResponse.status}")
throw RuntimeException("Error getting TSS-id")
}
}
}
}
data class TSSident(
val tssid: String,
)
| 1 | Kotlin | 1 | 0 | c549d53ac0e30228ec430c5798699ea7b142d28d | 2,849 | syfosmmottak | MIT License |
json-schema-validator/src/commonMain/kotlin/io/github/optimumcode/json/schema/internal/factories/object/PatternPropertiesAssertionFactory.kt | OptimumCode | 665,024,908 | false | {"Kotlin": 701490, "Shell": 919} | package io.github.optimumcode.json.schema.internal.factories.`object`
import io.github.optimumcode.json.pointer.JsonPointer
import io.github.optimumcode.json.schema.AnnotationKey
import io.github.optimumcode.json.schema.OutputCollector
import io.github.optimumcode.json.schema.internal.AnnotationKeyFactory
import io.github.optimumcode.json.schema.internal.AssertionContext
import io.github.optimumcode.json.schema.internal.JsonSchemaAssertion
import io.github.optimumcode.json.schema.internal.LoadingContext
import io.github.optimumcode.json.schema.internal.factories.AbstractAssertionFactory
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
internal object PatternPropertiesAssertionFactory : AbstractAssertionFactory("patternProperties") {
val ANNOTATION: AnnotationKey<Set<String>> = AnnotationKeyFactory.createAggregatable(property) { a, b -> a + b }
override fun createFromProperty(
element: JsonElement,
context: LoadingContext,
): JsonSchemaAssertion {
require(element is JsonObject) { "$property must be an object" }
val propAssertions: Map<Regex, JsonSchemaAssertion> =
element.asSequence().associate { (prop, element) ->
require(context.isJsonSchema(element)) { "$prop must be a valid JSON schema" }
val regex =
try {
prop.toRegex()
} catch (exOrJsError: Throwable) {
// because of JsError
throw IllegalArgumentException("$prop must be a valid regular expression", exOrJsError)
}
regex to context.at(prop).schemaFrom(element)
}
return PatternAssertion(context.schemaPath, propAssertions)
}
}
private class PatternAssertion(
private val location: JsonPointer,
private val assertionsByRegex: Map<Regex, JsonSchemaAssertion>,
) : JsonSchemaAssertion {
override fun validate(
element: JsonElement,
context: AssertionContext,
errorCollector: OutputCollector<*>,
): Boolean {
return errorCollector.updateKeywordLocation(location).use {
if (element !is JsonObject) {
return@use true
}
if (assertionsByRegex.isEmpty()) {
return@use true
}
var result = true
var checkedProps: MutableSet<String>? = null
for ((prop, value) in element) {
val matchedRegex =
assertionsByRegex.filter { (regex) ->
regex.find(prop) != null
}
if (matchedRegex.isEmpty()) {
continue
}
if (checkedProps == null) {
// initialize props
checkedProps = hashSetOf()
}
checkedProps.add(prop)
val propContext = context.at(prop)
updateLocation(propContext.objectPath).use {
for ((_, assertion) in matchedRegex) {
val valid =
assertion.validate(
value,
propContext,
this,
)
result = result && valid
}
}
}
checkedProps?.also {
context.annotationCollector.annotate(PatternPropertiesAssertionFactory.ANNOTATION, it)
}
result
}
}
} | 8 | Kotlin | 3 | 33 | 20ad6e2e642ad7c98554c1788392bbbfc423c068 | 3,149 | json-schema-validator | MIT License |
app/src/main/java/com/zasa/hashr/HomeViewModel.kt | zansangeeth | 507,636,039 | false | {"Kotlin": 8260} | package com.zasa.hashr
import android.util.Log
import androidx.lifecycle.ViewModel
import java.security.MessageDigest
/**
**@Project -> HashR
**@Author -> Sangeeth on 6/27/2022
*/
class HomeViewModel : ViewModel() {
fun getHash(etPlainText : String, algorithm : String) : String{
val bytes = MessageDigest.getInstance(algorithm).digest(etPlainText.toByteArray())
return toHex(bytes)
}
private fun toHex(byteArray: ByteArray) : String{
return byteArray.joinToString("") { "%02x".format(it) }
}
} | 0 | Kotlin | 0 | 0 | 80d30fb75e88ba67cdd25df0ef6e524569e9775f | 542 | HashR | Apache License 2.0 |
src/commonMain/kotlin/org/angproj/crypt/sec/Secp256Random1.kt | angelos-project | 677,062,617 | false | {"Kotlin": 9244687} | /**
* Copyright (c) 2023 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.crypt.sec
import org.angproj.aux.util.BinHex
public object Secp256Random1 : SecPRandom {
public override val name: String = "secp256r1"
public override val strength: Int = 128
public override val size: Int = 256
private val _p: ByteArray by lazy { BinHex.decodeToBin(
"FFFFFFFF" +
"00000001" +
"00000000" +
"00000000" +
"00000000" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFF"
) }
private val _a: ByteArray by lazy { BinHex.decodeToBin(
"FFFFFFFF" +
"00000001" +
"00000000" +
"00000000" +
"00000000" +
"FFFFFFFF" +
"FFFFFFFF" +
"FFFFFFFC"
) }
private val _b: ByteArray by lazy { BinHex.decodeToBin(
"5AC635D8" +
"AA3A93E7" +
"B3EBBD55" +
"769886BC" +
"651D06B0" +
"CC53B0F6" +
"3BCE3C3E" +
"27D2604B"
) }
private val _S: ByteArray by lazy { BinHex.decodeToBin(
"C49D3608" +
"86E70493" +
"6A6678E1" +
"139D26B7" +
"819F7E90"
) }
private val _G: ByteArray by lazy { BinHex.decodeToBin(
"03" +
"6B17D1F2" +
"E12C4247" +
"F8BCE6E5" +
"63A440F2" +
"77037D81" +
"2DEB33A0" +
"F4A13945" +
"D898C296"
) }
private val _Gc: ByteArray by lazy { BinHex.decodeToBin(
"04" +
"6B17D1F2" +
"E12C4247" +
"F8BCE6E5" +
"63A440F2" +
"77037D81" +
"2DEB33A0" +
"F4A13945" +
"D898C296" +
"4FE342E2" +
"FE1A7F9B" +
"8EE7EB4A" +
"7C0F9E16" +
"2BCE3357" +
"6B315ECE" +
"CBB64068" +
"37BF51F5"
) }
private val _n: ByteArray by lazy { BinHex.decodeToBin(
"FFFFFFFF" +
"00000000" +
"FFFFFFFF" +
"FFFFFFFF" +
"BCE6FAAD" +
"A7179E84" +
"F3B9CAC2" +
"FC632551"
) }
private val _h: ByteArray = BinHex.decodeToBin(
"01"
)
override val p: ByteArray
get() = _p.copyOf()
override val a: ByteArray
get() = _a.copyOf()
override val b: ByteArray
get() = _b.copyOf()
override val S: ByteArray
get() = _S.copyOf()
override val G: ByteArray
get() = _G.copyOf()
override val Gc: ByteArray
get() = _Gc.copyOf()
override val n: ByteArray
get() = _n.copyOf()
override val h: ByteArray
get() = _h.copyOf()
} | 0 | Kotlin | 0 | 0 | e59676c8cbf2a612573ff0fc93389184633d4ace | 3,411 | angelos-project-crypt | MIT License |
auth/data/src/main/java/com/google/android/horologist/auth/data/googlesignin/AuthUserMapper.kt | google | 451,563,714 | 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.auth.data.googlesignin
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.horologist.auth.data.ExperimentalHorologistAuthDataApi
import com.google.android.horologist.auth.data.common.model.AuthUser
/**
* Functions to map models from other layers and / or packages into an [AuthUser].
*/
@ExperimentalHorologistAuthDataApi
public object AuthUserMapper {
/**
* Maps from a [GoogleSignInAccount].
*/
public fun map(googleSignInAccount: GoogleSignInAccount?): AuthUser? =
googleSignInAccount?.let {
AuthUser(
displayName = it.displayName,
email = it.email,
avatarUri = it.photoUrl.toString()
)
}
}
| 71 | null | 69 | 430 | bcfd31399a85d9eef772947fec6765a905d3529c | 1,402 | horologist | Apache License 2.0 |
solana/src/main/java/org/p2p/solanaj/model/types/EpochInfo.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4750125, "HTML": 3064848, "Java": 296719, "Groovy": 1601, "Shell": 1252, "JavaScript": 1067} | package org.p2p.solanaj.model.types
import com.google.gson.annotations.SerializedName
import java.math.BigInteger
data class EpochInfo(
@SerializedName("absoluteSlot")
val absoluteSlot: BigInteger,
@SerializedName("blockHeight")
val blockHeight: BigInteger,
@SerializedName("epoch")
val epoch: BigInteger,
@SerializedName("slotIndex")
val slotIndex: BigInteger,
@SerializedName("slotsInEpoch")
val slotsInEpoch: BigInteger,
@SerializedName("transactionCount")
val transactionCount: Long
)
| 4 | Kotlin | 18 | 33 | 1fe956b7969902842ea8ce235a00054136573fe6 | 539 | key-app-android | MIT License |
ui/src/main/java/io/snabble/sdk/ui/payment/CreditCardInputFragment.kt | snabble | 124,525,499 | false | null | package io.snabble.sdk.ui.payment
import android.os.Bundle
import android.view.View
import io.snabble.sdk.PaymentMethod
import io.snabble.sdk.ui.BaseFragment
import io.snabble.sdk.ui.R
open class CreditCardInputFragment : BaseFragment(
layoutResId = R.layout.snabble_fragment_cardinput_creditcard,
waitForProject = false
) {
companion object {
const val ARG_PROJECT_ID = CreditCardInputView.ARG_PROJECT_ID
const val ARG_PAYMENT_TYPE = CreditCardInputView.ARG_PAYMENT_TYPE
}
var projectId: String? = null
var paymentMethod: PaymentMethod? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
projectId = arguments?.getString(ARG_PROJECT_ID, null)
paymentMethod = arguments?.getSerializable(ARG_PAYMENT_TYPE) as PaymentMethod?
}
override fun onActualViewCreated(view: View, savedInstanceState: Bundle?) {
val v = view as CreditCardInputView
v.load(projectId, paymentMethod)
}
} | 1 | Kotlin | 0 | 6 | a91cf68f7837ffdd9aa41d0e1e58d84fb85a41cc | 1,019 | Android-SDK | MIT License |
src/main/kotlin/no/nav/bidrag/vedtak/api/grunnlag/HentGrunnlagResponse.kt | navikt | 331,260,160 | false | null | package no.nav.bidrag.vedtak.api.grunnlag
import com.fasterxml.jackson.annotation.JsonRawValue
import io.swagger.v3.oas.annotations.media.Schema
@Schema
data class HentGrunnlagResponse(
@Schema(description = "Grunnlag-id")
val grunnlagId: Int = 0,
@Schema(description = "Referanse til grunnlaget")
val grunnlagReferanse: String = "",
@Schema(description = "Grunnlagstype")
val grunnlagType: String = "",
@Schema(description = "Innholdet i grunnlaget")
@JsonRawValue
val grunnlagInnhold: String = ""
)
| 1 | Kotlin | 0 | 1 | 1c992bec3115c84742b3b1fb944ce76912dd1f80 | 543 | bidrag-vedtak | MIT License |
forgerock-auth/src/test/java/org/forgerock/android/auth/FRLifeCycleListenerTest.kt | ForgeRock | 215,203,638 | false | null | /*
* Copyright (c) 2023 ForgeRock. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package org.forgerock.android.auth
import android.content.Context
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.squareup.okhttp.mockwebserver.MockResponse
import org.assertj.core.api.Assertions
import org.forgerock.android.auth.callback.NameCallback
import org.forgerock.android.auth.callback.PasswordCallback
import org.json.JSONException
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.text.ParseException
import java.util.concurrent.ExecutionException
@RunWith(AndroidJUnit4::class)
class FRLifeCycleListenerTest : BaseTest() {
@Test
@Throws(InterruptedException::class,
ExecutionException::class,
MalformedURLException::class,
ParseException::class,
JSONException::class)
fun testListener() {
val onSSOTokenUpdated = intArrayOf(0)
val onCookiesUpdated = intArrayOf(0)
val onLogout = intArrayOf(0)
val lifecycleListener: FRLifecycleListener = object : FRLifecycleListener {
override fun onSSOTokenUpdated(ssoToken: SSOToken) {
Assertions.assertThat(ssoToken.value)
.isEqualTo("C4VbQPUtfu76IvO_JRYbqtGt2hc.*AAJTSQACMDEAAlNLABxQQ1U3VXZXQ0FoTUNCSnFjbzRYeWh4WHYzK0E9AAR0eXBlAANDVFMAAlMxAAA.*")
onSSOTokenUpdated[0]++
}
override fun onCookiesUpdated(cookies: Collection<String>) {
onCookiesUpdated[0]++
}
override fun onLogout() {
onLogout[0]++
}
}
FRLifecycle.registerFRLifeCycleListener(lifecycleListener)
authenticate()
FRLifecycle.unregisterFRLifeCycleListener(lifecycleListener)
//Assert that FRLifeCycleListener is invoked
Assertions.assertThat(onSSOTokenUpdated[0]).isEqualTo(1)
Assertions.assertThat(onCookiesUpdated[0]).isEqualTo(1)
Assertions.assertThat(onLogout[0]).isEqualTo(1)
}
@Test
@Throws(InterruptedException::class,
ExecutionException::class,
MalformedURLException::class,
ParseException::class,
JSONException::class)
fun testUnRegister() {
val onSSOTokenUpdated = intArrayOf(0)
val onCookiesUpdated = intArrayOf(0)
val onLogout = intArrayOf(0)
val lifecycleListener: FRLifecycleListener = object : FRLifecycleListener {
override fun onSSOTokenUpdated(ssoToken: SSOToken) {
Assertions.assertThat(ssoToken.value)
.isEqualTo("C4VbQPUtfu76IvO_JRYbqtGt2hc.*AAJTSQACMDEAAlNLABxQQ1U3VXZXQ0FoTUNCSnFjbzRYeWh4WHYzK0E9AAR0eXBlAANDVFMAAlMxAAA.*")
onSSOTokenUpdated[0]++
}
override fun onCookiesUpdated(cookies: Collection<String>) {
onCookiesUpdated[0]++
}
override fun onLogout() {
onLogout[0]++
}
}
FRLifecycle.registerFRLifeCycleListener(lifecycleListener)
FRLifecycle.unregisterFRLifeCycleListener(lifecycleListener)
authenticate()
//Assert that FRLifeCycleListener is invoked
Assertions.assertThat(onSSOTokenUpdated[0]).isEqualTo(0)
Assertions.assertThat(onCookiesUpdated[0]).isEqualTo(0)
Assertions.assertThat(onLogout[0]).isEqualTo(0)
}
@Throws(ExecutionException::class, InterruptedException::class)
private fun authenticate() {
enqueue("/authTreeMockTest_Authenticate_NameCallback.json", HttpURLConnection.HTTP_OK)
enqueue("/authTreeMockTest_Authenticate_PasswordCallback.json", HttpURLConnection.HTTP_OK)
server.enqueue(MockResponse()
.setResponseCode(HttpURLConnection.HTTP_OK)
.addHeader("Content-Type", "application/json")
.addHeader("Set-Cookie",
"iPlanetDirectoryPro=C4VbQPUtfu76IvO_JRYbqtGt2hc.*AAJTSQACMDEAAlNLABxQQ1U3VXZXQ0FoTUNCSnFjbzRYeWh4WHYzK0E9AAR0eXBlAANDVFMAAlMxAAA.*; Path=/; Domain=localhost; HttpOnly")
.setBody(getJson("/authTreeMockTest_Authenticate_success.json")))
Config.getInstance().sharedPreferences = context.getSharedPreferences(
DEFAULT_TOKEN_MANAGER_TEST, Context.MODE_PRIVATE)
Config.getInstance().ssoSharedPreferences = context.getSharedPreferences(
DEFAULT_SSO_TOKEN_MANAGER_TEST, Context.MODE_PRIVATE)
Config.getInstance().url = url
val nodeListenerFuture: NodeListenerFuture<FRUser> =
object : NodeListenerFuture<FRUser>() {
override fun onCallbackReceived(state: Node) {
if (state.getCallback(NameCallback::class.java) != null) {
state.getCallback(NameCallback::class.java).setName("tester")
state.next(context, this)
return
}
if (state.getCallback(PasswordCallback::class.java) != null) {
state.getCallback(PasswordCallback::class.java)
.setPassword("password".toCharArray())
state.next(context, this)
}
}
}
FRUser.login(context, nodeListenerFuture)
server.takeRequest()
server.takeRequest()
server.takeRequest()
val request = server.takeRequest()
val state = Uri.parse(request.path).getQueryParameter("state")
server.enqueue(MockResponse()
.addHeader("Location",
"http://www.example.com:8080/callback?code=PmxwECH3mBobKuPEtPmq6Xorgzo&iss=http://openam.example.com:8080/openam/oauth2&" +
"state=" + state + "&client_id=andy_app")
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP))
enqueue("/authTreeMockTest_Authenticate_accessToken.json", HttpURLConnection.HTTP_OK)
enqueue("/userinfo_success.json", HttpURLConnection.HTTP_OK)
Assert.assertNotNull(nodeListenerFuture.get())
Assert.assertNotNull(FRUser.getCurrentUser())
FRUser.getCurrentUser().logout()
}
companion object {
private const val DEFAULT_TOKEN_MANAGER_TEST = "DefaultTokenManagerTest"
private const val DEFAULT_SSO_TOKEN_MANAGER_TEST = "DefaultSSOTokenManagerTest"
}
} | 24 | null | 23 | 35 | b59cfab7ccd80b1b2b877bf9caa0f31fed1f2c37 | 6,565 | forgerock-android-sdk | MIT License |
demo/src/main/java/com/michaelflisar/composethemer/demo/composables/Drawer.kt | MFlisar | 616,470,400 | false | null | package com.michaelflisar.composethemer.demo.composables
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ColorLens
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Style
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.michaelflisar.composedebugdrawer.core.*
import com.michaelflisar.composedebugdrawer.plugin.materialpreferences.DebugDrawerSettingCheckbox
import com.michaelflisar.composedebugdrawer.plugin.materialpreferences.DebugDrawerSettingSegmentedButtons
import com.michaelflisar.composedebugdrawer.plugin.materialpreferences.getDebugLabel
import com.michaelflisar.composedialogs.core.rememberDialogState
import com.michaelflisar.composedialogs.dialogs.color.DialogColor
import com.michaelflisar.composethemer.ComposeThemePrefs
import com.michaelflisar.composethemer.Theme
import com.michaelflisar.composethemer.collectAsState
import com.michaelflisar.composethemer.preferences.ThemePrefs
import com.michaelflisar.composethemer.preferences.ThemePrefsDark
import com.michaelflisar.composethemer.preferences.ThemePrefsLight
import com.michaelflisar.materialpreferences.core.interfaces.StorageSetting
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun Drawer(
drawerState: DebugDrawerState
) {
val scope = rememberCoroutineScope()
DebugDrawerRegion(
icon = Icons.Default.Style,
label = "App Theme",
collapsible = false,
drawerState = drawerState
) {
DebugDrawerSettingSegmentedButtons(
setting = ThemePrefs.theme,
items = Theme.values()
//label = "Theme"
)
DebugDrawerSettingCheckbox(
setting = ThemePrefs.dynamicTheme,
label = "Dynamic Colors"
)
DebugDrawerButton(label = "Reset Colors") {
scope.launch(Dispatchers.IO) {
ThemePrefsLight.reset()
ThemePrefsDark.reset()
}
}
}
val theme by ThemePrefs.theme.collectAsState()
val dynamicTheme by ThemePrefs.dynamicTheme.collectAsState()
val isDark = theme.isDark()
val info = if (isDark) {
"dark"
} else {
"light"
}
if (dynamicTheme) {
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Colors",
id = "colors",
collapsible = true,
drawerState = drawerState
) {
DebugDrawerInfo(
title = "Dynamic Theme Selected",
info = "Colors are calculated automatically, there are no color settings in this mode!"
)
}
} else {
DebugDrawerInfo(
title = "Color Info",
info = "Selected colors are applied to $info theme"
)
// Main Colors
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Main",
id = "colors",
collapsible = true,
drawerState = drawerState
) {
DebugColorSetting(ComposeThemePrefs::primary, isDark)
DebugColorSetting(ComposeThemePrefs::onPrimary, isDark)
DebugColorSetting(ComposeThemePrefs::secondary, isDark)
DebugColorSetting(ComposeThemePrefs::onSecondary, isDark)
DebugColorSetting(ComposeThemePrefs::tertiary, isDark)
DebugColorSetting(ComposeThemePrefs::onTertiary, isDark)
}
// Container
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Container",
collapsible = true,
drawerState = drawerState
) {
DebugColorSetting(ComposeThemePrefs::primaryContainer, isDark)
DebugColorSetting(ComposeThemePrefs::onPrimaryContainer, isDark)
DebugColorSetting(ComposeThemePrefs::secondaryContainer, isDark)
DebugColorSetting(ComposeThemePrefs::onSecondaryContainer, isDark)
DebugColorSetting(ComposeThemePrefs::tertiaryContainer, isDark)
DebugColorSetting(ComposeThemePrefs::onTertiaryContainer, isDark)
}
// Background/Surface
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Background/Surface",
collapsible = true,
drawerState = drawerState
) {
DebugColorSetting(ComposeThemePrefs::background, isDark)
DebugColorSetting(ComposeThemePrefs::onBackground, isDark)
DebugColorSetting(ComposeThemePrefs::surface, isDark)
DebugColorSetting(ComposeThemePrefs::onSurface, isDark)
DebugColorSetting(ComposeThemePrefs::surfaceVariant, isDark)
DebugColorSetting(ComposeThemePrefs::onSurfaceVariant, isDark)
DebugColorSetting(ComposeThemePrefs::surfaceTint, isDark)
}
// Inverse
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Inverse",
collapsible = true,
drawerState = drawerState
) {
DebugColorSetting(ComposeThemePrefs::inversePrimary, isDark)
DebugColorSetting(ComposeThemePrefs::inverseSurface, isDark)
DebugColorSetting(ComposeThemePrefs::inverseOnSurface, isDark)
}
// Specials
DebugDrawerRegion(
icon = Icons.Default.ColorLens,
label = "Specials",
collapsible = true,
drawerState = drawerState
) {
DebugColorSetting(ComposeThemePrefs::error, isDark)
DebugColorSetting(ComposeThemePrefs::onError, isDark)
DebugColorSetting(ComposeThemePrefs::errorContainer, isDark)
DebugColorSetting(ComposeThemePrefs::onErrorContainer, isDark)
DebugColorSetting(ComposeThemePrefs::outline, isDark)
DebugColorSetting(ComposeThemePrefs::outlineVariant, isDark)
DebugColorSetting(ComposeThemePrefs::scrim, isDark)
}
}
}
@Composable
private fun DebugColorSetting(
field: ComposeThemePrefs.() -> StorageSetting<Int>,
darkTheme: Boolean
) {
val scope = rememberCoroutineScope()
val dialog = rememberDialogState()
val field =
if (darkTheme) ThemePrefsDark.field() else ThemePrefsLight.field()
val colorDark by ThemePrefsDark.field().collectAsState()
val colorLight by ThemePrefsLight.field().collectAsState()
val currentColor by remember(darkTheme, colorDark, colorLight) {
derivedStateOf {
Color(if (darkTheme) colorDark else colorLight)
}
}
val resettable by remember(field.value) {
derivedStateOf {
field.value != field.defaultValue
}
}
val label = field.getDebugLabel()
Row(
modifier = Modifier
.clip(MaterialTheme.shapes.small)
.clickable {
dialog.show()
}
.padding(all = DebugDrawerDefaults.ITEM_PADDING),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Box(
modifier = Modifier
.size(36.dp)
.clip(MaterialTheme.shapes.small)
.background(currentColor)
)
Column(
modifier = Modifier.weight(1f)
) {
Text(
modifier = Modifier.fillMaxWidth(),
text = label,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "#${Integer.toHexString(currentColor.toArgb())}",
style = MaterialTheme.typography.bodySmall
)
}
if (resettable) {
IconButton(
modifier = Modifier.size(36.dp),
onClick = {
scope.launch(Dispatchers.IO) {
field.reset()
}
}) {
Icon(imageVector = Icons.Default.Restore, contentDescription = null)
}
}
}
if (dialog.showing) {
val color = remember { mutableStateOf(currentColor) }
DialogColor(state = dialog, color = color) {
if (it.isPositiveButton) {
scope.launch(Dispatchers.IO) {
field.update(color.value.toArgb())
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 3ebcc33c3f0bceb86abc960c92202ef86536dfb6 | 9,029 | ComposeThemer | Apache License 2.0 |
common/core/src/commonMain/kotlin/com/trafi/maas.account.ui.internal/RequirementsListViewConstants.kt | trafi | 287,312,105 | false | null | package com.trafi.maas.account.ui.internal
import com.trafi.ui.theme.internal.CurrentTheme
class RequirementsListViewConstants(theme: CurrentTheme) {
val textStyle = theme.typographyScale.textM
val textColor = theme.colorPalette.grayScale.gray600
}
| 4 | Kotlin | 2 | 9 | a471fed0a538a7de45193be6fe0f0c0798e6cf2f | 259 | maas-components | Apache License 2.0 |
app/src/main/java/com/thetechsamurai/foodonwheelz/orderHandling/CartActivity.kt | himanshu-1608 | 276,752,026 | false | null | package com.thetechsamurai.foodonwheelz.orderHandling
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.SystemClock
import android.provider.Settings
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.thetechsamurai.foodonwheelz.R
import com.thetechsamurai.foodonwheelz.adapters.RecyclerAdapterCartList
import com.thetechsamurai.foodonwheelz.orderHandling.orderDatabase.DBAsyncTaskOrder
import com.thetechsamurai.foodonwheelz.orderHandling.orderDatabase.GetOrderList
import com.thetechsamurai.foodonwheelz.orderHandling.orderDatabase.OrderItemEntity
import com.thetechsamurai.foodonwheelz.sideUtils.ConnectionManager
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
class CartActivity : AppCompatActivity() {
private lateinit var sp1: SharedPreferences
private lateinit var sp2: SharedPreferences
private lateinit var recyclerView: RecyclerView
private lateinit var cartInfoList : ArrayList<OrderItemEntity>
private lateinit var progressLayout: RelativeLayout
private lateinit var progressBar: ProgressBar
private lateinit var resID: String
private lateinit var btnOrder: Button
private lateinit var txtResName: TextView
private lateinit var resName: String
private var mLastClickTime: Long = 0
private lateinit var layoutManager: LinearLayoutManager
private lateinit var recyclerCartAdapter: RecyclerAdapterCartList
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cart)
sp1 = getSharedPreferences("OrderMetaData",MODE_PRIVATE)
sp2 = getSharedPreferences("DataFile",MODE_PRIVATE)
resID = sp1.getString("ResID","").toString()
resName = sp1.getString("ResName","").toString()
progressLayout = findViewById(R.id.progressLayout)
progressBar = findViewById(R.id.progressBar)
recyclerView = findViewById(R.id.recyclerCart)
txtResName = findViewById(R.id.txtResName)
txtResName.text = getString(R.string.f5,resName)
btnOrder = findViewById(R.id.btnOrder)
layoutManager = LinearLayoutManager(this@CartActivity)
progressLayout.visibility = View.VISIBLE
progressBar.visibility = View.VISIBLE
cartInfoList = GetOrderList(applicationContext).execute().get()
var totalCost = 0
for(i in 0 until cartInfoList.size) {
totalCost += Integer.parseInt(cartInfoList[i].itemCost)
}
btnOrder.text = getString(R.string.f6,totalCost)
btnOrder.setOnClickListener {
if(SystemClock.elapsedRealtime() - mLastClickTime < 2000){
return@setOnClickListener
}
mLastClickTime = SystemClock.elapsedRealtime()
if(ConnectionManager().checkConnectivity(this@CartActivity)) {
val queue = Volley.newRequestQueue(this@CartActivity)
val url = "http://13.235.250.119/v2/place_order/fetch_result/"
val jsonParams = JSONObject()
jsonParams.put("user_id",sp2.getString("UserID",""))
jsonParams.put("restaurant_id",resID)
jsonParams.put("total_cost",""+totalCost)
val jsonArray = JSONArray()
for(i in 0 until cartInfoList.size) {
jsonArray.put(JSONObject().put("food_item_id",""+cartInfoList[i].item_id))
}
jsonParams.put("food",jsonArray)
val jsonObjectRequest = object : JsonObjectRequest(Method.POST,url,jsonParams,Response.Listener {
DBAsyncTaskOrder(applicationContext,OrderItemEntity(0,"Nuke","The","Table"),4).execute().get()
try {
val obj = it.getJSONObject("data")
if(obj.getBoolean("success")){
val intent = Intent(this@CartActivity, OrderConfirm::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
} else {
Toast.makeText(this@CartActivity,obj.getString("errorMessage"), Toast.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Toast.makeText(this@CartActivity,"Some unexpected error occurred!", Toast.LENGTH_SHORT).show()
}
},Response.ErrorListener {
Toast.makeText(this@CartActivity,"Oops!! A Network error appeared!!", Toast.LENGTH_SHORT).show()
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String,String>()
headers["Content-type"] = "application/json"
headers["token"] = "ec7d33dcf400a8"
return headers
}
}
queue.add(jsonObjectRequest)
} else {
val dialog = AlertDialog.Builder(this@CartActivity)
dialog.setTitle("Error")
.setCancelable(false)
dialog.setMessage("Internet connection not found!")
dialog.setPositiveButton("Open Settings"){ _, _ ->
val settingIntent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
startActivity(settingIntent)
finish()
}
dialog.setNeutralButton("Exit"){_,_ ->
ActivityCompat.finishAffinity(this@CartActivity)
}
dialog.show()
}
}
progressLayout.visibility = View.GONE
progressBar.visibility = View.GONE
recyclerCartAdapter = RecyclerAdapterCartList(this@CartActivity, cartInfoList)
recyclerView.adapter = recyclerCartAdapter
recyclerView.layoutManager = layoutManager
}
}
| 1 | Kotlin | 0 | 0 | eb33ddb90b55aa50d06d51616aded73e2fc8a48b | 6,454 | food-on-wheelz | MIT License |
compiler/fir/tree/src/org/jetbrains/kotlin/fir/declarations/FirFile.kt | damenez | 189,964,139 | true | {"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1} | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.declarations
import org.jetbrains.kotlin.fir.BaseTransformedType
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.VisitedSupertype
import org.jetbrains.kotlin.fir.expressions.FirAnnotationContainer
import org.jetbrains.kotlin.fir.visitors.FirVisitor
import org.jetbrains.kotlin.name.FqName
@BaseTransformedType
interface FirFile : @VisitedSupertype FirPackageFragment, FirDeclaration, FirAnnotationContainer {
@Suppress("DEPRECATION")
val fileSession: FirSession
get() = session
val name: String
val packageFqName: FqName
val imports: List<FirImport>
override fun <R, D> accept(visitor: FirVisitor<R, D>, data: D): R =
visitor.visitFile(this, data)
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
acceptAnnotations(visitor, data)
for (import in imports) {
import.accept(visitor, data)
}
super<FirPackageFragment>.acceptChildren(visitor, data)
}
} | 0 | Kotlin | 1 | 2 | dca23f871cc22acee9258c3d58b40d71e3693858 | 1,194 | kotlin | Apache License 2.0 |
lithic-kotlin-core/src/test/kotlin/com/lithic/api/models/CardProvisionResponseTest.kt | lithic-com | 658,974,440 | false | null | // File generated from our OpenAPI spec by Stainless.
package com.lithic.api.models
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class CardProvisionResponseTest {
@Test
fun createCardProvisionResponse() {
val cardProvisionResponse =
CardProvisionResponse.builder().provisioningPayload("provisioning_payload").build()
assertThat(cardProvisionResponse).isNotNull
assertThat(cardProvisionResponse.provisioningPayload()).isEqualTo("provisioning_payload")
}
}
| 1 | null | 0 | 2 | 68cf1467469c6794e6dcb24a4a6e2542563d44c0 | 546 | lithic-kotlin | Apache License 2.0 |
core/domain/src/main/java/com/hellguy39/hellnotes/core/domain/use_case/note/DeleteNoteUseCase.kt | HellGuy39 | 572,830,054 | false | null | package com.hellguy39.hellnotes.core.domain.use_case.note
import com.hellguy39.hellnotes.core.domain.repository.local.ChecklistRepository
import com.hellguy39.hellnotes.core.domain.repository.local.LabelRepository
import com.hellguy39.hellnotes.core.domain.repository.local.NoteRepository
import com.hellguy39.hellnotes.core.domain.repository.local.ReminderRepository
import com.hellguy39.hellnotes.core.model.repository.local.database.Note
import javax.inject.Inject
class DeleteNoteUseCase @Inject constructor(
private val noteRepository: NoteRepository,
private val labelRepository: LabelRepository,
private val checklistRepository: ChecklistRepository,
private val reminderRepository: ReminderRepository,
) {
suspend operator fun invoke(note: Note) {
note.id?.let { id ->
noteRepository.deleteNoteById(id)
labelRepository.deleteNoteIdFromLabels(id)
reminderRepository.deleteReminderByNoteId(id)
checklistRepository.deleteChecklistByNoteId(id)
}
}
} | 1 | Kotlin | 0 | 9 | 548d59c0f641df6e1f3ddd9c220904631ca5351b | 1,042 | HellNotes | Apache License 2.0 |
felles-test/src/main/kotlin/no/nav/helsearbeidsgiver/felles/test/mock/MockData.kt | navikt | 495,713,363 | false | null | package no.nav.helsearbeidsgiver.felles.test.mock
import no.nav.helsearbeidsgiver.felles.ForespoerselType
import no.nav.helsearbeidsgiver.felles.ForespurtData
import no.nav.helsearbeidsgiver.felles.ForrigeInntekt
import no.nav.helsearbeidsgiver.felles.ForslagInntekt
import no.nav.helsearbeidsgiver.felles.ForslagRefusjon
import no.nav.helsearbeidsgiver.felles.TrengerInntekt
import no.nav.helsearbeidsgiver.felles.til
import no.nav.helsearbeidsgiver.utils.test.date.februar
import no.nav.helsearbeidsgiver.utils.test.date.januar
fun mockForespurtData(): ForespurtData =
ForespurtData(
arbeidsgiverperiode = ForespurtData.Arbeidsgiverperiode(
paakrevd = true
),
inntekt = ForespurtData.Inntekt(
paakrevd = true,
forslag = ForslagInntekt.Grunnlag(forrigeInntekt = null)
),
refusjon = ForespurtData.Refusjon(
paakrevd = true,
forslag = ForslagRefusjon(
perioder = listOf(
ForslagRefusjon.Periode(
fom = 10.januar(2017),
beloep = 10.48
),
ForslagRefusjon.Periode(
fom = 2.februar(2017),
beloep = 98.26
)
),
opphoersdato = 26.februar(2017)
)
)
)
fun mockForespurtDataMedForrigeInntekt(): ForespurtData =
ForespurtData(
arbeidsgiverperiode = ForespurtData.Arbeidsgiverperiode(
paakrevd = false
),
inntekt = ForespurtData.Inntekt(
paakrevd = true,
forslag = ForslagInntekt.Grunnlag(
forrigeInntekt = ForrigeInntekt(
skjæringstidspunkt = 1.januar.minusYears(1),
kilde = "INNTEKTSMELDING",
beløp = 10000.0
)
)
),
refusjon = ForespurtData.Refusjon(
paakrevd = true,
forslag = ForslagRefusjon(
perioder = listOf(
ForslagRefusjon.Periode(
fom = 10.januar(2017),
beloep = 10.48
),
ForslagRefusjon.Periode(
fom = 2.februar(2017),
beloep = 98.26
)
),
opphoersdato = 26.februar(2017)
)
)
)
fun mockForespurtDataMedFastsattInntekt(): ForespurtData =
ForespurtData(
arbeidsgiverperiode = ForespurtData.Arbeidsgiverperiode(
paakrevd = true
),
inntekt = ForespurtData.Inntekt(
paakrevd = false,
forslag = ForslagInntekt.Fastsatt(
fastsattInntekt = 31415.92
)
),
refusjon = ForespurtData.Refusjon(
paakrevd = true,
forslag = ForslagRefusjon(
perioder = listOf(
ForslagRefusjon.Periode(
fom = 1.januar,
beloep = 31415.92
),
ForslagRefusjon.Periode(
fom = 15.januar,
beloep = 3.14
)
),
opphoersdato = null
)
)
)
fun mockTrengerInntekt(): TrengerInntekt =
TrengerInntekt(
type = ForespoerselType.KOMPLETT,
orgnr = "123",
fnr = "456",
skjaeringstidspunkt = 11.januar(2018),
sykmeldingsperioder = listOf(2.januar til 31.januar),
egenmeldingsperioder = listOf(1.januar til 1.januar),
forespurtData = mockForespurtData(),
erBesvart = false
)
| 18 | Kotlin | 0 | 2 | e3e267c925349c7285289b94b9806cace5112008 | 3,780 | helsearbeidsgiver-inntektsmelding | MIT License |
packages/HilltopCrawler/src/main/kotlin/nz/govt/eop/hilltop_crawler/api/parsers/HilltopMeasurments.kt | Greater-Wellington-Regional-Council | 528,176,417 | false | {"Kotlin": 248210, "TypeScript": 206033, "Batchfile": 66171, "Shell": 54151, "PLpgSQL": 42581, "ASL": 6123, "SCSS": 4684, "JavaScript": 4383, "Dockerfile": 2524, "HTML": 1578, "CSS": 860} | package nz.govt.eop.hilltop_crawler.api.parsers
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
data class HilltopMeasurements(
@JacksonXmlProperty(localName = "DataSource")
@JacksonXmlElementWrapper(useWrapping = false)
val datasources: List<HilltopDatasource>
)
data class HilltopDatasource(
@JacksonXmlProperty(localName = "Name", isAttribute = true) val name: String,
@JacksonXmlProperty(localName = "Site", isAttribute = true) val siteName: String,
@JacksonXmlProperty(localName = "From") val from: String,
@JacksonXmlProperty(localName = "To") val to: String,
@JacksonXmlProperty(localName = "TSType") val type: String,
@JacksonXmlProperty(localName = "Measurement")
@JacksonXmlElementWrapper(useWrapping = false)
val measurements: List<HilltopMeasurement> = emptyList()
)
data class HilltopMeasurement(
@JacksonXmlProperty(localName = "Name", isAttribute = true) val name: String,
@JacksonXmlProperty(localName = "RequestAs") val requestAs: String,
@JacksonXmlProperty(localName = "Item") val itemNumber: Int,
@JacksonXmlProperty(localName = "VM") val vm: Int? = null
)
| 13 | Kotlin | 3 | 5 | 292ce1c7eb3039957f0774e018832625c7a336d5 | 1,247 | Environmental-Outcomes-Platform | MIT License |
layout-ui/src/main/java/com/android/tools/componenttree/treetable/TreeTableHeader.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 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 com.android.tools.componenttree.treetable
import com.android.tools.componenttree.api.ColumnInfo
import com.intellij.ui.JBColor
import com.intellij.util.IJSwingUtilities
import com.intellij.util.ui.UIUtil
import java.awt.Component
import java.awt.Cursor
import java.awt.Dimension
import java.awt.Graphics
import java.awt.KeyboardFocusManager
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.MouseWheelEvent
import javax.swing.JComponent
import javax.swing.SwingUtilities
import javax.swing.table.JTableHeader
/**
* A [JTableHeader] that is using [TreeTableHeaderUI] and paints divider lines.
*
* The default [JTableHeader] using DarculaTableHeaderUI will unconditionally paint column divider
* lines between all columns. We only want them where they are defined by the specified [ColumnInfo] instances.
*
* Draw a divider between the header and the table content see [paintBottomSeparator].
*
* The component keeps track of the hover column and will use the tooltipText and cursor for the component found
* under the mouse pointer. Also: all mouse clicks will be forwarded.
*
* This implementation supports editing columns. However, only focus navigation (usually though the keyboard) will
* use column editors. Currently, the component from the renderer is used as the editor. This only works as long as
* that component is not shared with other column renderers.
*/
class TreeTableHeader(private val treeTable: TreeTableImpl) : JTableHeader(treeTable.columnModel) {
private var hoverColumn = -1
private var hoverCachedComponent: Component? = null
var editingColumn = -1
private set
val isEditing: Boolean
get() = editingColumn >= 0
val columnCount: Int
get() = treeTable.columnCount
init {
reorderingAllowed = false
isFocusTraversalPolicyProvider = true
focusTraversalPolicy = TreeTableHeaderTraversalPolicy(this)
background = UIUtil.TRANSPARENT_COLOR
isOpaque = false
val mouseListener = HoverMouseListener()
addMouseListener(mouseListener)
addMouseMotionListener(mouseListener)
}
fun editCellAt(columnIndex: Int): Boolean {
val column = columnModel.getColumn(columnIndex)
val component = column.headerRenderer.getTableCellRendererComponent(treeTable, null, false, false, 0, columnIndex)
val x = columnModel.columns.asSequence().take(columnIndex).sumOf { it.width }
component.setBounds(x, 0, column.width, height - 1)
removeEditor()
add(component)
component.validate()
component.repaint()
editingColumn = columnIndex
return true
}
fun removeEditor() {
// Remove focus from the current editor if it has it. Do this to avoid endless recursion.
// Auto focus transfer is a common problem for applications. See JDK-6210779.
val editor = components.firstOrNull()
if (editor != null && IJSwingUtilities.hasFocus(editor)) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearFocusOwner()
}
removeAll()
editingColumn = -1
}
override fun getPreferredSize(): Dimension {
val size = super.getPreferredSize()
size.height++
return size
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
treeTable.paintColumnDividers(g)
paintBottomSeparator(g)
}
override fun updateUI() {
setUI(TreeTableHeaderUI())
// In case the render components are cached, update them now:
columnModel.columns.asSequence().forEach {
val component = it.headerRenderer?.getTableCellRendererComponent(table, null, false, false, 0, it.modelIndex)
IJSwingUtilities.updateComponentTreeUI(component)
}
}
override fun getToolTipText(event: MouseEvent): String? {
updateHoverColumn(event)
return hoverComponentAt(event)?.toolTipText
}
private fun paintBottomSeparator(g: Graphics) {
val g2 = g.create()
g2.color = JBColor.border()
g2.drawLine(0, height - 1, width, height - 1)
g2.dispose()
}
private fun updateHoverColumn(event: MouseEvent) {
val column = table.columnAtPoint(event.point)
if (column != hoverColumn) {
hoverColumn = column
hoverCachedComponent = null
}
cursor = hoverComponentAt(event)?.cursor ?: Cursor.getDefaultCursor()
}
private fun hoverComponentAt(event: MouseEvent): JComponent? {
val columnComponent = hoverComponent ?: return null
val cellRect = getHeaderRect(hoverColumn)
columnComponent.setBounds(0, 0, cellRect.width, cellRect.height)
columnComponent.doLayout()
val point = event.point.also { it.translate(-cellRect.x, -cellRect.y) }
return SwingUtilities.getDeepestComponentAt(columnComponent, point.x, point.y) as? JComponent
}
private val hoverComponent: Component?
get() {
if (hoverCachedComponent == null && hoverColumn != -1) {
val aColumn = columnModel.getColumn(hoverColumn)
val renderer = aColumn.headerRenderer ?: defaultRenderer
hoverCachedComponent = renderer.getTableCellRendererComponent(table, aColumn.headerValue, false, false, -1, hoverColumn)
}
return hoverCachedComponent
}
private inner class HoverMouseListener : MouseAdapter() {
override fun mouseEntered(event: MouseEvent) {
updateHoverColumn(event)
}
override fun mouseMoved(event: MouseEvent) {
updateHoverColumn(event)
}
override fun mouseWheelMoved(event: MouseWheelEvent) {
updateHoverColumn(event)
}
override fun mouseExited(event: MouseEvent) {
hoverColumn = -1
hoverCachedComponent = null
}
override fun mousePressed(event: MouseEvent) = redispatchMouseEvent(event)
override fun mouseReleased(event: MouseEvent) = redispatchMouseEvent(event)
override fun mouseClicked(event: MouseEvent) = redispatchMouseEvent(event)
private fun redispatchMouseEvent(event: MouseEvent) {
updateHoverColumn(event)
val component = hoverComponentAt(event) ?: return
val cellRect = getHeaderRect(hoverColumn)
val point = event.point.also { it.translate(-cellRect.x, -cellRect.y) }
generateSequence(component) { it.parent as JComponent? }.forEach { point.translate(-it.x, -it.y) }
@Suppress("DEPRECATION")
val newEvent = MouseEvent(component,
event.id,
event.getWhen(), event.modifiers or event.modifiersEx,
point.x, point.y,
event.xOnScreen,
event.yOnScreen,
event.clickCount,
event.isPopupTrigger,
event.button)
component.dispatchEvent(newEvent)
}
}
}
| 5 | Kotlin | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 7,362 | android | Apache License 2.0 |
app/src/main/java/com/chen/app/navigationtest/MainActivity.kt | justine0423 | 275,700,085 | true | {"Kotlin": 2115008} | package com.chen.app.navigationtest
import android.os.Bundle
import androidx.navigation.findNavController
import androidx.navigation.fragment.FragmentNavigator
import androidx.navigation.fragment.findNavController
import com.chen.app.R
import com.chen.app.ui.simple.toolbar.SimpleFirstFragment
import com.chen.basemodule.basem.BaseSimActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.reflect.jvm.jvmName
/**
* @author CE Chen
*/
class MainActivity : BaseSimActivity() {
override val contentLayoutId = R.layout.activity_main
} | 0 | null | 0 | 0 | 383dbd509b344910abd998ddab141614b113cf5b | 560 | EasyAndroid | Apache License 2.0 |
src/me/anno/io/zip/InnerLazyImageFile.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 9469405, "C": 236481, "GLSL": 9454, "Java": 7643, "Lua": 4315} | package me.anno.io.files.inner.lazy
import me.anno.image.Image
import me.anno.image.ImageReadable
import me.anno.image.bmp.BMPWriter
import me.anno.io.files.FileReference
import me.anno.io.files.Signature
import me.anno.io.files.inner.InnerFile
import me.anno.io.files.inner.SignatureFile
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.nio.charset.Charset
open class InnerLazyImageFile(
absolutePath: String, relativePath: String, _parent: FileReference,
val cpuImage: Lazy<Image>, val gpuImage: () -> Image,
) : InnerFile(absolutePath, relativePath, false, _parent), ImageReadable, SignatureFile {
override var signature: Signature? = Signature.bmp
override fun hasInstantGPUImage(): Boolean {
return false
}
override fun hasInstantCPUImage(): Boolean {
return cpuImage.isInitialized() && super.hasInstantCPUImage()
}
init {
size = Int.MAX_VALUE.toLong() // unknown
compressedSize = size // unknown until we compress it
}
val bytes by lazy {
BMPWriter.createBMP(readCPUImage())
}
override fun readCPUImage(): Image {
return cpuImage.value
}
override fun readGPUImage(): Image {
return gpuImage()
}
override fun readBytes(callback: (it: ByteArray?, exc: Exception?) -> Unit) {
callback(readBytesSync(), null)
}
override fun readBytesSync(): ByteArray {
return bytes
}
override fun readText(charset: Charset, callback: (String?, Exception?) -> Unit) {
callback(String(bytes, charset), null)
}
override fun readTextSync(): String {
return String(bytes) // what are you doing? ;)
}
override fun getInputStream(callback: (InputStream?, Exception?) -> Unit) {
callback(inputStreamSync(), null)
}
override fun inputStreamSync(): InputStream {
return ByteArrayInputStream(bytes)
}
} | 0 | Kotlin | 3 | 16 | f33d03ccf246b8ba27f47bac4671ddafb7e027a3 | 1,930 | RemsEngine | Apache License 2.0 |
app/src/main/java/com/example/androidboilderplatecode/utils/AppConstants.kt | tusharthetruth | 444,371,856 | false | {"Kotlin": 18036} | package com.example.androidboilderplatecode.utils
object AppConstants {
const val BASE_URL:String="https://google.com"
const val SAMPLE_ENTRIES:String="https://api.publicapis.org/entries"
} | 0 | Kotlin | 0 | 0 | eb5586ac93cee18bc97ea84861eab88e261b1f8a | 198 | MVVM-Hilt-Retrofit-Coroutine | Apache License 2.0 |
core/data/src/main/java/org/the_chance/honeymart/data/source/remote/models/StatusResponse.kt | TheChance101 | 647,400,117 | false | {"Kotlin": 1218713} | package org.the_chance.honeymart.data.source.remote.models
data class StatusResponse(
val message: String?,
val code: Int
)
| 3 | Kotlin | 7 | 21 | 50200e0ec0802cdadc282b09074a19c96df3220c | 133 | Honey-Mart-Android-Client | Apache License 2.0 |
shared/models/src/commonMain/kotlin/com/paligot/confily/models/inputs/CreatingEventInput.kt | GerardPaligot | 444,230,272 | false | null | package org.gdglille.devfest.models.inputs
import kotlinx.datetime.Clock
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class CreatingEventInput(
val name: String,
val year: String,
val address: String,
@SerialName("open_feedback_id")
val openFeedbackId: String?,
@SerialName("billet_web_config")
val billetWebConfig: BilletWebConfigInput?,
@SerialName("wld_config")
val wldConfig: WldConfigInput?,
@SerialName("start_date")
val startDate: String,
@SerialName("end_date")
val endDate: String,
@SerialName("contact_phone")
val contactPhone: String?,
@SerialName("contact_email")
val contactEmail: String,
@SerialName("twitter_url")
val twitterUrl: String?,
@SerialName("linkedin_url")
val linkedinUrl: String?,
@SerialName("faq_link")
val faqLink: String,
@SerialName("code_of_conduct_link")
val codeOfConductLink: String,
@SerialName("update_at")
val updatedAt: Long = Clock.System.now().epochSeconds
) : Validator {
override fun validate(): List<String> {
val errors = arrayListOf<String>()
if (twitterUrl?.contains("twitter.com") == false) errors.add("Your twitter url is malformed")
if (linkedinUrl?.contains("linkedin.com") == false) errors.add("Your linkedin url is malformed")
return errors
}
}
| 9 | null | 6 | 143 | 8c0985b73422d6b388012d79c7ab33c054dc55c1 | 1,405 | Confily | Apache License 2.0 |
examples/e2e/src/main/kotlin/dev/s7a/example/gofile/Main.kt | sya-ri | 517,628,038 | false | {"Kotlin": 98972, "HTML": 44707} | @file:JvmName("Main")
package dev.s7a.example.gofile
import dev.s7a.gofile.GofileClient
import dev.s7a.gofile.GofileFolderOption
import dev.s7a.gofile.GofileTier
import dev.s7a.gofile.uploadFile
import java.util.Calendar
import kotlin.io.path.createTempFile
import kotlin.io.path.writeText
suspend fun main() {
val client = GofileClient()
var token: String? = System.getenv("GOFILE_TOKEN")
val file = createTempFile(suffix = ".txt").apply {
writeText("Hello world.")
}.toFile()
val uploadFile = client.uploadFile(file, token = token).getOrThrow()
println("uploadFile: $uploadFile")
if (token == null) token = uploadFile.guestToken ?: return
val accountDetails = client.getAccountDetails(token).getOrThrow()
println("accountDetails: $accountDetails")
val createFolder = client.createFolder(uploadFile.parentFolder, "new-folder", token).getOrThrow()
println("createFolder: $createFolder")
client.setFolderOption(createFolder.id, GofileFolderOption.Description("description"), token).getOrThrow()
client.setFolderOption(createFolder.id, GofileFolderOption.Expire(Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, 1) }.toInstant().epochSecond), token).getOrThrow()
client.setFolderOption(createFolder.id, GofileFolderOption.Password("<PASSWORD>"), token).getOrThrow()
client.setFolderOption(createFolder.id, GofileFolderOption.Tags("t", "a", "g", "s"), token).getOrThrow()
if (accountDetails.tier == GofileTier.Donor) {
client.copyContent(uploadFile.fileId, createFolder.id, token).getOrThrow()
val getContentFile = client.getContent(uploadFile.fileId, token).getOrThrow()
println("getContentFile: $getContentFile")
val getContentFolder = client.getContent(createFolder.id, token).getOrThrow()
println("getContentFolder: $getContentFolder")
}
val deleteContent = client.deleteContent(uploadFile.fileId, token).getOrThrow()
println("deleteContent: $deleteContent")
}
| 2 | Kotlin | 0 | 5 | d38f084ddd5244ce36422fb44db6a2d420c9eb28 | 1,997 | Gofile.kt | Apache License 2.0 |
shared/common/src/main/java/com/sadri/common/compose/CardItem.kt | sepehrsadri | 577,511,564 | false | {"Kotlin": 57847} | package com.sadri.common.compose
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.sadri.common.theme.Typography
@Composable
fun CardItem(
modifier: Modifier = Modifier,
title: String? = null,
subtitle: String? = null,
imageUrl: String? = null,
imageResource: Int? = null,
onCardClick: () -> Unit
) {
Card(
modifier = modifier
.fillMaxWidth()
.clickable {
onCardClick.invoke()
},
elevation = 8.dp
) {
Column(
modifier = Modifier
.padding(8.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (!imageUrl.isNullOrEmpty()) {
AsyncImage(
model = imageUrl,
contentDescription = "$title image",
contentScale = ContentScale.Crop,
modifier = Modifier
.clip(CircleShape)
.size(120.dp)
)
}
if (imageResource != null) {
Image(
painter = painterResource(id = imageResource),
contentDescription = "loaded from image resources",
contentScale = ContentScale.Crop,
modifier = Modifier
.clip(CircleShape)
.size(120.dp)
)
}
if (title.isNullOrEmpty().not()) {
Spacer(modifier = Modifier.size(8.dp))
Column(
modifier = Modifier
.padding(start = 8.dp)
) {
Text(
text = title!!,
style = Typography.body1,
color = MaterialTheme.colors.onSurface
)
Spacer(modifier = Modifier.size(8.dp))
if (!subtitle.isNullOrEmpty()) {
Text(
text = subtitle,
style = Typography.subtitle1,
color = MaterialTheme.colors.onBackground
)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 2ee26111d7ff892d2f1d23c182894245cb7e8258 | 2,691 | KittenAppComposeUI | Apache License 2.0 |
app/src/main/java/com/rokoblak/gittrendingcompose/data/repo/GitRepoDetailsRepo.kt | oblakr24 | 641,592,280 | false | {"Kotlin": 146539} | package com.rokoblak.gittrendingcompose.data.repo
import com.rokoblak.gittrendingcompose.data.datasource.RemoteRepoDetailsDataSource
import com.rokoblak.gittrendingcompose.domain.model.ExpandedGitRepositoryDetails
import com.rokoblak.gittrendingcompose.data.model.RepoDetailsInput
import com.rokoblak.gittrendingcompose.data.repo.model.LoadableResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
interface GitRepoDetailsRepo {
fun loadResults(input: RepoDetailsInput): Flow<LoadableResult<ExpandedGitRepositoryDetails>>
suspend fun reload()
}
@OptIn(ExperimentalCoroutinesApi::class)
class AppGitRepoDetailsRepo @Inject constructor(
private val source: RemoteRepoDetailsDataSource,
) : GitRepoDetailsRepo {
private val inputs = MutableStateFlow<RepoDetailsInput?>(null)
private var refreshing = MutableStateFlow(RefreshSignal())
private val loadResults = combine(inputs.filterNotNull(), refreshing) { input, _ ->
source.load(input)
}.flatMapLatest { loadFlow ->
flow {
emit(LoadableResult.Loading)
emitAll(loadFlow)
}
}
override fun loadResults(input: RepoDetailsInput): Flow<LoadableResult<ExpandedGitRepositoryDetails>> {
return loadResults.also {
inputs.value = input
}
}
override suspend fun reload() {
refreshing.value = RefreshSignal()
}
class RefreshSignal
}
| 0 | Kotlin | 0 | 0 | 46b9059ec372952253f0b310eac51f69f0574967 | 1,733 | GitTrendingCompose | Apache License 2.0 |
app/src/main/java/org/nekomanga/presentation/components/dialog/RemoveFilterDialog.kt | nekomangaorg | 182,704,531 | false | null | /*
package org.nekomanga.presentation.components.dialog
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.kanade.tachiyomi.R
import jp.wasabeef.gap.Gap
import org.nekomanga.presentation.screens.ThemeColorState
*/
/** Simple Dialog to save a filter */
/*
@Composable
fun RemoveFilterDialog(themeColorState: ThemeColorState, currentFilter: String, onDismiss: () -> Unit, onRemove: (String) -> Unit, onDefault: (String) -> Unit) {
CompositionLocalProvider(LocalRippleTheme provides themeColorState.rippleTheme, LocalTextSelectionColors provides themeColorState.textSelectionColors) {
AlertDialog(
title = {
},
text = {
Column {
OutlinedTextField(
value = saveFilterText,
onValueChange = { saveFilterText = it },
label = { Text(text = stringResource(id = R.string.name)) },
singleLine = true,
maxLines = 1,
colors = TextFieldDefaults.outlinedTextFieldColors(
cursorColor = themeColorState.buttonColor,
focusedLabelColor = themeColorState.buttonColor,
focusedBorderColor = themeColorState.buttonColor,
),
)
Gap(2.dp)
Text(text = errorMessage, style = MaterialTheme.typography.labelSmall.copy(color = MaterialTheme.colorScheme.error))
}
},
onDismissRequest = onDismiss,
confirmButton = {
TextButton(
onClick = {
onConfirm(saveFilterText)
onDismiss()
},
enabled = saveEnabled,
colors = ButtonDefaults.textButtonColors(contentColor = themeColorState.buttonColor),
) {
Text(text = stringResource(id = R.string.save))
}
},
dismissButton = {
TextButton(onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = themeColorState.buttonColor)) {
Text(text = stringResource(id = R.string.cancel))
}
},
)
}
}
*/
| 83 | null | 119 | 2,261 | 3e0f16dd125e6d173e29defa7fcb62410358239d | 3,022 | Neko | Apache License 2.0 |
src/aoc22/Day17.kt | mihassan | 575,356,150 | false | {"Kotlin": 103728} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day17
import aoc22.day17.Direction.Companion.move
import aoc22.day17.Direction.Companion.toDirection
import kotlin.math.ceil
import lib.Collections.histogram
import lib.Collections.repeat
import lib.Point
import lib.Solution
import lib.Ranges.contains
// Not using lib.Direction here as the y direction is inverted.
enum class Direction {
LEFT, // Decrement x
RIGHT, // Increment x
DOWN; // Decrement y
companion object {
fun Char.toDirection(): Direction = when (this) {
'<' -> LEFT
'>' -> RIGHT
'V' -> DOWN
else -> error("Invalid jet pattern.")
}
fun Point.move(direction: Direction) = when (direction) {
LEFT -> Point(x - 1, y)
RIGHT -> Point(x + 1, y)
DOWN -> Point(x, y - 1)
}
}
}
enum class Rock(pattern: String) {
ROCK__("####"), ROCK_X(
"""
.#.
###
.#.
""".trimIndent()
),
ROCK_J(
"""
..#
..#
###
""".trimIndent()
),
ROCK_I(
"""
#
#
#
#
""".trimIndent()
),
ROCK_O(
"""
##
##
""".trimIndent()
);
// The y coordinate decreases as we go downward. As such, we need to reverse the rock patterns so
// that last line has y = 0.
val cells: Set<Point> = pattern.lines().reversed().flatMapIndexed { r, line ->
line.withIndex().filter { it.value == '#' }.map { Point(it.index, r) }
}.toSet()
val boundingBox: Pair<IntRange, IntRange> = run {
val xRange = cells.minOf { it.x }..cells.maxOf { it.x }
val yRange = cells.minOf { it.y }..cells.maxOf { it.y }
xRange to yRange
}
}
data class FallingRock(private val rock: Rock, private var bottomLeft: Point) {
private var lastBottomLeft: Point? = null
fun getCells(): List<Point> = rock.cells.map { it + bottomLeft }
fun getBoundingBox(): Pair<IntRange, IntRange> = run {
val (xRange, yRange) = rock.boundingBox
val newXRange = xRange.first + bottomLeft.x..xRange.last + bottomLeft.x
val newYRange = yRange.first + bottomLeft.y..yRange.last + bottomLeft.y
newXRange to newYRange
}
fun move(direction: Direction) {
lastBottomLeft = bottomLeft
bottomLeft = bottomLeft.move(direction)
}
fun undoMove() {
lastBottomLeft?.let {
bottomLeft = it
}
}
}
data class Chamber(private val grid: MutableSet<Point> = EMPTY_GRID.toMutableSet()) {
fun add(rock: Rock): FallingRock = FallingRock(rock, Point(2, height() + 4))
fun canPlace(rock: FallingRock): Boolean {
val (xRange, yRange) = rock.getBoundingBox()
if (yRange.any { it <= FLOOR_Y }) return false
if (xRange !in BOUNDARY) return false
return (rock.getCells() intersect grid).isEmpty()
}
fun place(rock: FallingRock) {
grid += rock.getCells()
}
fun height(): Int = grid.maxOf { it.y }
companion object {
private val BOUNDARY = 0..6
private const val FLOOR_Y = 0
private val EMPTY_GRID = BOUNDARY.map { Point(it, FLOOR_Y) }.toSet()
}
}
typealias Input = List<Direction>
typealias Output = Long
private val solution = object : Solution<Input, Output>(2022, "Day17") {
override fun parse(input: String): Input = input.map { it.toDirection() }
override fun format(output: Output): String = "$output"
private fun chamberHeights(input: Input): Sequence<Int> = sequence {
val rockProducer = Rock.values().asSequence().repeat().iterator()
val jetProducer = input.asSequence().repeat().iterator()
val chamber = Chamber()
yield(chamber.height())
while (true) {
val fallingRock = chamber.add(rockProducer.next())
while (true) {
fallingRock.move(jetProducer.next())
if (!chamber.canPlace(fallingRock)) {
fallingRock.undoMove()
}
fallingRock.move(Direction.DOWN)
if (!chamber.canPlace(fallingRock)) {
fallingRock.undoMove()
break
}
}
chamber.place(fallingRock)
yield(chamber.height())
}
}
override fun part1(input: Input): Output {
return chamberHeights(input).elementAt(2022).toLong()
}
override fun part2(input: Input): Output {
// We needed trial and error to find that 10000 rocks is enough to find a pattern.
val chamberHeights = chamberHeights(input).take(10000).toList()
val heightPatterns = chamberHeights
.zipWithNext { a, b -> b - a }
// Window step corresponds to number of rocks and size is a multiple of that.
// Bigger the window size, less likely to find a false positive for a repeat.
// Assuming at least 4 variations in height increase for a round of 5 rocks,
// 10 rounds should be enough to detect unique repetition.
.windowed(10 * Rock.values().size, Rock.values().size)
val cycleLength = heightPatterns.mapIndexed { i, h ->
i - heightPatterns.take(i).indexOfLast { h2 -> h == h2 }
}.histogram().maxBy { it.value }.key * Rock.values().size
val heightIncreasePerCycle =
chamberHeights.takeLast(cycleLength + 1).run { last() - first() }
val target = 1_000_000_000_000L
val targetCycles = ceil((target - chamberHeights.size) / cycleLength.toDouble()).toLong()
val baseHeight = chamberHeights.elementAt((target - targetCycles * cycleLength).toInt())
return baseHeight + targetCycles * heightIncreasePerCycle
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 65ff26890731046a7201f79b79247c8202a75014 | 5,379 | aoc-kotlin | Apache License 2.0 |
compiler/fir/analysis-tests/testData/resolve/problems/secondaryConstructorCfg.kt | JetBrains | 3,432,266 | false | null | // IGNORE_REVERSED_RESOLVE
// !DUMP_CFG
class B(p0: String) {
val p1 = p0
val p2: Int = p0.length
var p3: String
constructor(p0: String, p1: String) : this(p0) {
p3 = p1
}
init {
<!VAL_REASSIGNMENT!>p1<!> = <!ASSIGNMENT_TYPE_MISMATCH!>p0.length<!>
p3 = ""
}
}
| 176 | null | 5601 | 47,397 | a47dcc227952c0474d27cc385021b0c9eed3fb67 | 312 | kotlin | Apache License 2.0 |
src/main/kotlin/com/igorini/togepibot/gui/keyword/TiredKeyword.kt | igorini | 123,990,696 | false | null | package com.igorini.togepibot.gui.keyword
/** Represents a keyword for text and sound associated with "Tired" */
object TiredKeyword : Keyword() {
override fun folder() = "tired"
override fun voiceRus() = listOf("уставать", "устал", "утомило", "утомился", "утомилась", "устала", "усталый", "усталая", "устали")
override fun voiceEng() = listOf("tired")
override fun textRus() = voiceRus()
override fun textEng() = voiceEng()
override fun emotes() = listOf("tired")
}
| 0 | Kotlin | 0 | 0 | 80de398881b5999dfd107b12c9a279915788306b | 492 | togepi-bot | Apache License 2.0 |
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/builder/FieldSetBuilder.kt | apache | 6,935,442 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.builder
import io.kvision.form.FormPanel
import org.apache.causeway.client.kroviz.to.TObject
import org.apache.causeway.client.kroviz.to.TypeMapper
import org.apache.causeway.client.kroviz.to.bs3.FieldSet
import org.apache.causeway.client.kroviz.ui.core.FormItem
import org.apache.causeway.client.kroviz.ui.core.FormPanelFactory
class FieldSetBuilder {
fun create(
fieldSetLayout: FieldSet,
tObject: TObject,
tab: RoDisplay
): FormPanel<String>? {
val members = tObject.getProperties()
val items = mutableListOf<FormItem>()
for (p in fieldSetLayout.propertyList) {
val label = p.id
val member = members.firstOrNull() { it.id == label }
if (member != null) {
val memberType = TypeMapper().forType(member.type!!)
val size = maxOf(1, p.multiLine)
val fi = FormItem(
label = p.named,
type = memberType,
content = member.value?.content,
size = size,
description = p.describedAs,
member = member,
dspl = tab)
items.add(fi)
}
}
return FormPanelFactory(items).panel
}
}
| 4 | null | 294 | 751 | cfb994d281118effa2363528c6d5cf74c8c64cae | 2,207 | causeway | Apache License 2.0 |
library/analytics/analytics-api-no-op/src/main/java/reactivecircus/analytics/noop/NoOpAnalyticsApi.kt | ReactiveCircus | 142,655,149 | false | null | package reactivecircus.analytics.noop
import reactivecircus.analytics.AnalyticsApi
object NoOpAnalyticsApi : AnalyticsApi {
override fun setCurrentScreenName(screenName: String, screenClass: String) = Unit
override fun setEnableAnalytics(enable: Boolean) = Unit
override fun setUserId(userId: String?) = Unit
override fun setUserProperty(name: String, value: String) = Unit
override fun logEvent(name: String, params: Map<String, *>?) = Unit
}
| 7 | Kotlin | 5 | 8 | b97fb5b8f161f29b70db1de6446af76166f42aa4 | 471 | release-probe | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.