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/hegoudai/plugins/Security.kt
|
hegoudai
| 645,038,095
| false
| null |
package com.hegoudai.plugins
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
fun Application.configureSecurity() {
authentication {
jwt {
val jwtAudience =
this@configureSecurity.environment.config.property("jwt.audience").getString()
val issuer =
this@configureSecurity.environment.config.property("jwt.issuer").getString()
val secret =
this@configureSecurity.environment.config.property("jwt.secret").getString()
authHeader { call -> call.request.authHeaderFromParamsOrHeader() }
verifier(
JWT.require(Algorithm.HMAC256(secret))
.withAudience(jwtAudience)
.withIssuer(issuer)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(jwtAudience))
JWTPrincipal(credential.payload)
else null
}
challenge { _, _ ->
call.respond(
HttpStatusCode(401, "test custom http"),
"Token is not valid or has expired"
)
}
}
}
}
fun ApplicationRequest.authHeaderFromParamsOrHeader() =
try {
// try to get token from params first, for websocket validate
this.call.parameters["token"]?.let {
return io.ktor.http.auth.parseAuthorizationHeader(it)
}
authorization()?.let { parseAuthorizationHeader() }
} catch (cause: IllegalArgumentException) {
// log error
this.call.application.environment.log.error(cause.message, cause)
null
}
| 0
|
Kotlin
|
0
| 0
|
89c392f0d212702cbffb91613751f2ecb053aef0
| 2,012
|
dchat-server
|
MIT License
|
kt/godot-library/src/main/kotlin/godot/gen/godot/CanvasTexture.kt
|
utopia-rise
| 289,462,532
| false
|
{"Kotlin": 1455718, "C++": 480143, "GDScript": 464697, "C#": 10278, "C": 8523, "Shell": 7976, "Java": 2136, "CMake": 939, "Python": 75}
|
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.CoreTypeHelper
import godot.`annotation`.CoreTypeLocalCopy
import godot.`annotation`.GodotBaseType
import godot.core.Color
import godot.core.VariantType.COLOR
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.memory.TransferContext
import kotlin.Boolean
import kotlin.Double
import kotlin.Float
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
import kotlin.Unit
/**
* Texture with optional normal and specular maps for use in 2D rendering.
*
* [godot.CanvasTexture] is an alternative to [godot.ImageTexture] for 2D rendering. It allows using normal maps and specular maps in any node that inherits from [godot.CanvasItem]. [godot.CanvasTexture] also allows overriding the texture's filter and repeat mode independently of the node's properties (or the project settings).
*
* **Note:** [godot.CanvasTexture] cannot be used in 3D rendering. For physically-based materials in 3D, use [godot.BaseMaterial3D] instead.
*/
@GodotBaseType
public open class CanvasTexture : Texture2D() {
/**
* The diffuse (color) texture to use. This is the main texture you want to set in most cases.
*/
public var diffuseTexture: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_DIFFUSE_TEXTURE,
OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as Texture2D?)
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_DIFFUSE_TEXTURE,
NIL)
}
/**
* The normal map texture to use. Only has a visible effect if [godot.Light2D]s are affecting this [godot.CanvasTexture].
*
* **Note:** Godot expects the normal map to use X+, Y+, and Z+ coordinates. See [this page](http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates) for a comparison of normal map coordinates expected by popular engines.
*/
public var normalTexture: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_NORMAL_TEXTURE,
OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as Texture2D?)
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_NORMAL_TEXTURE,
NIL)
}
/**
* The specular map to use for [godot.Light2D] specular reflections. This should be a grayscale or colored texture, with brighter areas resulting in a higher [specularShininess] value. Using a colored [specularTexture] allows controlling specular shininess on a per-channel basis. Only has a visible effect if [godot.Light2D]s are affecting this [godot.CanvasTexture].
*/
public var specularTexture: Texture2D?
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_SPECULAR_TEXTURE, OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as Texture2D?)
}
set(`value`) {
TransferContext.writeArguments(OBJECT to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_SPECULAR_TEXTURE, NIL)
}
/**
* The multiplier for specular reflection colors. The [godot.Light2D]'s color is also taken into account when determining the reflection color. Only has a visible effect if [godot.Light2D]s are affecting this [godot.CanvasTexture].
*/
@CoreTypeLocalCopy
public var specularColor: Color
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_SPECULAR_COLOR,
COLOR)
return (TransferContext.readReturnValue(COLOR, false) as Color)
}
set(`value`) {
TransferContext.writeArguments(COLOR to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_SPECULAR_COLOR,
NIL)
}
/**
* The specular exponent for [godot.Light2D] specular reflections. Higher values result in a more glossy/"wet" look, with reflections becoming more localized and less visible overall. The default value of `1.0` disables specular reflections entirely. Only has a visible effect if [godot.Light2D]s are affecting this [godot.CanvasTexture].
*/
public var specularShininess: Float
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_SPECULAR_SHININESS, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value.toDouble())
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_SPECULAR_SHININESS, NIL)
}
/**
* The texture filtering mode to use when drawing this [godot.CanvasTexture].
*/
public var textureFilter: CanvasItem.TextureFilter
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_TEXTURE_FILTER,
LONG)
return CanvasItem.TextureFilter.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_TEXTURE_FILTER,
NIL)
}
/**
* The texture repeat mode to use when drawing this [godot.CanvasTexture].
*/
public var textureRepeat: CanvasItem.TextureRepeat
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_GET_TEXTURE_REPEAT,
LONG)
return CanvasItem.TextureRepeat.from(TransferContext.readReturnValue(LONG) as Long)
}
set(`value`) {
TransferContext.writeArguments(LONG to value.id)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_CANVASTEXTURE_SET_TEXTURE_REPEAT,
NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_CANVASTEXTURE, scriptIndex)
return true
}
/**
* The multiplier for specular reflection colors. The [godot.Light2D]'s color is also taken into account when determining the reflection color. Only has a visible effect if [godot.Light2D]s are affecting this [godot.CanvasTexture].
*
* This is a helper function to make dealing with local copies easier.
*
* For more information, see our
* [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types).
*
* Allow to directly modify the local copy of the property and assign it back to the Object.
*
* Prefer that over writing:
* ``````
* val myCoreType = canvastexture.specularColor
* //Your changes
* canvastexture.specularColor = myCoreType
* ``````
*/
@CoreTypeHelper
public open fun specularColorMutate(block: Color.() -> Unit): Color = specularColor.apply{
block(this)
specularColor = this
}
public companion object
}
| 47
|
Kotlin
|
28
| 412
|
fe7379a450ed32ad069f3b672709a2520b86f092
| 7,768
|
godot-kotlin-jvm
|
MIT License
|
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/exceptions/InvoiceChargedException.kt
|
godgav
| 394,659,595
| true
|
{"Kotlin": 43148, "Shell": 1322, "Dockerfile": 904}
|
package io.pleo.antaeus.core.exceptions
class InvoiceChargedException(invoiceId: Int):
Exception("Invoice '$invoiceId' has been already charged")
| 0
|
Kotlin
|
0
| 0
|
a1087e8d356009dad2cdde34a6050fff56938082
| 150
|
antaeus
|
Creative Commons Zero v1.0 Universal
|
plugins/settings-sync/src/com/intellij/settingsSync/plugins/SettingsSyncPluginCategoryFinder.kt
|
ingokegel
| 72,937,917
| false
| null |
package com.intellij.settingsSync.plugins
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.openapi.components.SettingsCategory
internal object SettingsSyncPluginCategoryFinder {
val UI_CATEGORIES = setOf(
"Theme",
"Editor Color Schemes")
val UI_EXTENSIONS = setOf(
"com.intellij.bundledColorScheme",
"com.intellij.themeProvider"
)
fun getPluginCategory(descriptor: IdeaPluginDescriptor): SettingsCategory {
if (UI_CATEGORIES.contains(descriptor.category)|| containsOnlyUIExtensions(descriptor)) {
return SettingsCategory.UI
}
return SettingsCategory.PLUGINS
}
private fun containsOnlyUIExtensions(descriptor: IdeaPluginDescriptor) : Boolean {
if (descriptor is IdeaPluginDescriptorImpl) {
return descriptor.epNameToExtensions?.all {
UI_EXTENSIONS.contains(it.key)
} ?: false
}
return false
}
}
| 191
| null |
4372
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 960
|
intellij-community
|
Apache License 2.0
|
core/function-core/src/main/kotlin/com/teamplay/core/function/error/ConflictError.kt
|
YAPP-16th
| 235,351,938
| false
|
{"Gradle Kotlin DSL": 10, "Gradle": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 5, "XML": 8, "Kotlin": 185, "Java": 4, "Java Properties": 1, "YAML": 6}
|
package com.teamplay.core.function.error
open class ConflictError(message: String = "Conflict") : CanHaveStatusError(message, 409)
| 2
|
Kotlin
|
0
| 1
|
a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2
| 131
|
Team_Android_2_Backend
|
MIT License
|
domene/src/main/kotlin/no/nav/tiltakspenger/vedtak/InnsendingHendelse.kt
|
navikt
| 487,246,438
| false
|
{"Kotlin": 955973, "Dockerfile": 495, "Shell": 150, "HTML": 45}
|
package no.nav.tiltakspenger.vedtak
interface IInnsendingHendelse : KontekstLogable, IAktivitetslogg {
val aktivitetslogg: Aktivitetslogg
fun journalpostId(): String
fun toLogString(): String
}
abstract class InnsendingHendelse protected constructor(
override val aktivitetslogg: Aktivitetslogg = Aktivitetslogg()
) : IAktivitetslogg by aktivitetslogg, IInnsendingHendelse {
init {
aktivitetslogg.addKontekst(this)
}
override fun opprettKontekst(): Kontekst {
return this.javaClass.canonicalName.split('.').last().let {
Kontekst(it, mapOf("journalpostId" to journalpostId()))
}
}
override fun toLogString() = aktivitetslogg.toString()
}
| 6
|
Kotlin
|
0
| 2
|
dde1b0532caed17b6bad77e1de4917f829adea1c
| 714
|
tiltakspenger-vedtak
|
MIT License
|
library-kotlin/src/main/java/com/pij/horrocks/kotlin/Engine.kt
|
pijpijpij
| 117,426,879
| false
| null |
package com.pij.horrocks.kotlin
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.helpers.NOPLogger
class Engine<S : Any>(
initialState: S,
private val clearEventProperties: S.() -> S = { this },
foreground: Scheduler? = null,
log4J: Logger? = Companion.logger,
private val features: Collection<Feature<*, S>>
) {
companion object {
private val logger: Logger by lazy { LoggerFactory.getLogger(Engine::class.java) }
fun <S : Any> create(
initialState: S,
clearEventProperties: S.() -> S,
foreground: Scheduler,
logger: Logger,
vararg features: Feature<*, S>
) = Engine(
initialState = initialState,
clearEventProperties = clearEventProperties,
foreground = foreground,
log4J = logger,
features = features.toList()
)
fun <S : Any> create(
initialState: S,
clearEventProperties: S.() -> S,
logger: Logger,
vararg features: Feature<*, S>
) = Engine(
initialState = initialState,
clearEventProperties = clearEventProperties,
log4J = logger,
features = features.toList()
)
fun <S : Any> create(
initialState: S,
clearEventProperties: S.() -> S,
vararg features: Feature<*, S>
) = Engine(
initialState = initialState,
clearEventProperties = clearEventProperties,
features = features.toList()
)
fun <S : Any> create(
initialState: S,
clearEventProperties: S.() -> S,
foreground: Scheduler,
vararg features: Feature<*, S>
) = Engine(
initialState = initialState,
clearEventProperties = clearEventProperties,
foreground = foreground,
features = features.toList()
)
fun <S : Any> create(
initialState: S,
clearEventProperties: S.() -> S,
logger: Logger,
foreground: Scheduler,
vararg features: Feature<*, S>
) = Engine(
initialState = initialState,
clearEventProperties = clearEventProperties,
log4J = logger,
foreground = foreground,
features = features.toList()
)
internal fun <T> Observable<T>.subscribeSafely(display: (T) -> Unit, logger: Logger = NOPLogger.NOP_LOGGER, stallingAction: (Throwable) -> Unit = {}): Disposable = this
.subscribe({
try {
display(it)
} catch (e: Throwable) {
logger.warn("${Engine::class.java} Failure while displaying '$it'", e)
}
}, {
logger.error("${Engine::class.java} Engine failure", it)
try {
stallingAction(it)
} catch (ignored: Throwable) {
logger.error("${Engine::class.java} Could not perform a last ditch action before stalling.", ignored)
}
})
}
private val logger: Logger = log4J ?: NOPLogger.NOP_LOGGER
private fun reducers() = features.map {
it.reducers.doOnError { error -> logger.warn("$javaClass Failed to emit a reducer", error) }
}
fun subscribe(display: (S) -> Unit, stallingAction: (Throwable) -> Unit = {}): Disposable = states.subscribeSafely(display, logger, stallingAction)
internal val states: Observable<S>
init {
require(features.isNotEmpty()) { "Must provide a least one feature to spin" }
states = Observable.merge(reducers())
.scan(initialState) { state, reducer: Reducer<S> -> reducer.reduceSafely(state) }
.doOnNext { logger.debug("$javaClass $it") }
.doAfterNext { state -> features.forEach { it.context.onNext(state) } }
.run { if (foreground == null) this else observeOn(foreground) }
.replay(1)
.refCount()
}
private fun Reducer<S>.reduceSafely(state: S) = try {
invoke(state.clearEventProperties())
} catch (e: Throwable) {
logger.warn("$javaClass Failed reducer", e)
throw e
}
}
| 2
| null |
1
| 1
|
b669781b83b2ebfa4a706dd8c2b7d91f9b1f277a
| 4,708
|
Horrocks
|
Apache License 2.0
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/WifiOutlined.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/WifiOutlined")
package mui.icons.material
@JsName("default")
external val WifiOutlined: SvgIconComponent
| 1
|
Kotlin
|
5
| 35
|
eb68a042133a7d025aef8450151ee0150cbc9b1b
| 188
|
mui-kotlin
|
Apache License 2.0
|
app/src/main/java/com/fantasyfang/developmenttool/di/repository/IdInfoModule.kt
|
fantasy1022
| 257,029,907
| false
| null |
package com.fantasyfang.developmenttool.di.repository
import com.fantasyfang.developmenttool.data.IdInfo
import com.fantasyfang.developmenttool.repository.InfoRepository
import com.fantasyfang.developmenttool.repository.id.IdInfoLocalDataStore
import com.fantasyfang.developmenttool.repository.id.IdInfoRepositoryImpl
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
object IdInfoModule {
@Provides
@Singleton
fun provideIdInfoRepository(idInfoLocalDataStore: IdInfoLocalDataStore): InfoRepository<List<IdInfo>> =
IdInfoRepositoryImpl(idInfoLocalDataStore)
}
| 0
|
Kotlin
|
0
| 0
|
1bca4516624b4c8c04986245806046a969e69486
| 614
|
DevelopmentTool
|
Apache License 2.0
|
src/jsMain/kotlin/baaahs/mapper/MapperStyles.kt
|
baaahs
| 174,897,412
| false
| null |
package baaahs.mapper
import kotlinx.css.*
import kotlinx.css.properties.border
import kotlinx.css.properties.scaleX
import kotlinx.css.properties.transform
import mui.material.styles.Theme
import styled.StyleSheet
class MapperStyles(val theme: Theme) : StyleSheet("mapper", isStatic = true) {
val green = Color("#00ff00")
val screen by css {
width = 100.pct
height = 100.pct
}
val controls by css {
position = Position.absolute
zIndex = 1
}
val mapping2dCanvas by css {
position = Position.absolute
display = Display.block
top = 0.px
bottom = 0.px
left = 0.px
right = 0.px
margin = "auto"
}
val mapping3dContainer by css {
canvas {
position = Position.absolute
display = Display.block
top = 0.px
bottom = 0.px
left = 0.px
right = 0.px
margin = "auto"
put("mix-blend-mode", "lighten")
}
}
val snapshotDiv by css {
position = Position.absolute
top = 0.pct + 10.px
right = 10.px
border = "1px groove white"
}
val baseDiv by css {
position = Position.absolute
top = 25.pct + 20.px
right = 10.px
border = "1px groove white"
}
val diffDiv by css {
position = Position.absolute
top = 50.pct + 30.px
right = 10.px
border = "1px groove white"
}
val panelMaskDiv by css {
position = Position.absolute
top = 75.pct + 40.px
right = 10.px
border = "1px groove white"
}
private val statusText by css {
fontFamily = "'Press Start 2P', sans-serif"
color = green
put("textShadow", "1px 1px 3px black, -1px -1px 3px black")
}
val thumbnailTitle by css(statusText) {
position = Position.absolute
bottom = .5.em
left = 1.em
fontSize = 8.pt
}
val stats by css(statusText) {
position = Position.absolute
right = 20.px
padding = "20px"
fontSize = 8.pt
textAlign = TextAlign.right
width = 100.pct
}
val perfStats by css(statusText) {
position = Position.absolute
bottom = 10.em
left = 1.em
padding = "1.em"
fontSize = 8.pt
transform { scaleX(.75) }
whiteSpace = WhiteSpace.pre
border(1.px, BorderStyle.solid, green, 2.px)
}
val message by css(statusText) {
position = Position.absolute
bottom = 20.px
padding = "20px"
fontSize = 16.pt
textAlign = TextAlign.center
width = 100.pct
}
val message2 by css(statusText) {
position = Position.absolute
bottom = 0.px
padding = "20px"
fontSize = 7.pt
textAlign = TextAlign.center
width = 100.pct
}
val table by css {
position = Position.absolute
top = 30.px
padding = "20px"
fontSize = 7.pt
width = 400.px
background = "rgba(0, 0, 0, .5)"
height = 250.px
}
}
| 83
|
Kotlin
|
5
| 24
|
01aa9e9530ff9acbada165a2d7048c4ad67ed74f
| 3,197
|
sparklemotion
|
MIT License
|
recycler-decorator/sample/src/main/java/ru/surfstudio/android/recycler/decorator/sample/UiKtx.kt
|
surfstudio
| 139,034,657
| false
| null |
package ru.surfstudio.android.recycler.decorator.sample
import android.content.res.Resources
val Int.toPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
| 5
| null |
30
| 249
|
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
| 186
|
SurfAndroidStandard
|
Apache License 2.0
|
core/src/main/java/tmidev/core/data/source/local/UserPreferencesDataSource.kt
|
tminet
| 499,620,414
| false
| null |
package tmidev.core.data.source.local
import kotlinx.coroutines.flow.Flow
interface UserPreferencesDataSource {
val isAppThemeDarkMode: Flow<Boolean?>
val isOrderListAscending: Flow<Boolean>
suspend fun updateAppTheme(darkMode: Boolean)
suspend fun switchOrderList()
}
| 0
|
Kotlin
|
0
| 1
|
7971807d88dcde4f6ab982040e4a5f1ccde605f7
| 286
|
CustomerBase
|
MIT License
|
app/src/main/java/xyz/palaocorona/ui/features/liveupdates/LiveUpdatesViewModel.kt
|
SaadAAkash
| 251,509,106
| false
| null |
package xyz.palaocorona.ui.features.liveupdates
import androidx.lifecycle.MutableLiveData
import com.orhanobut.logger.Logger
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import xyz.palaocorona.base.ui.BaseViewModel
import xyz.palaocorona.data.liveupdates.LiveUpdateRepository
import xyz.palaocorona.data.liveupdates.model.LiveUpdateDataModelDGHS
import xyz.palaocorona.data.liveupdates.model.LiveUpdateResponse
import javax.inject.Inject
class LiveUpdatesViewModel @Inject constructor(val repository: LiveUpdateRepository): BaseViewModel() {
var liveUpdates = MutableLiveData<LiveUpdateResponse>()
var liveUpdatesDGHS = MutableLiveData<LiveUpdateDataModelDGHS>()
fun getLiveUpdates() {
if(liveUpdates.value == null) {
val disposable = repository.getLiveUpdate()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { loader.value = true }
.doAfterTerminate { loader.value = false }
.subscribe({
Logger.d(it)
liveUpdates.value = it
}, {
it.printStackTrace()
})
compositeDisposable.add(disposable)
}
}
fun getLiveUpdatesDGHS() {
if(liveUpdates.value == null) {
val disposable = repository.getLiveUpdateDGHS()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { loader.value = true }
.doAfterTerminate { loader.value = false }
.subscribe({
Logger.d(it)
liveUpdatesDGHS.value = it
}, {
it.printStackTrace()
})
compositeDisposable.add(disposable)
}
}
}
| 0
|
Kotlin
|
7
| 57
|
80f69ecfd5941962d7e5bd5f02d5cf36064e6fc5
| 1,939
|
COVID-19-Bangladesh-Android
|
MIT License
|
knot3/src/main/kotlin/de/halfbit/knot3/CompositeKnot.kt
|
sergejsha
| 168,983,284
| false
| null |
package de.halfbit.knot3
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.plugins.RxJavaPlugins
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import io.reactivex.rxjava3.subjects.Subject
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.reflect.KClass
/**
* If your [Knot] becomes big and you want to improve its readability and maintainability,
* you may consider to decompose it. You start decomposition by grouping related
* concerns into, in a certain sense, indecomposable pieces called `Delegate`.
*
* [Flowchart diagram](https://github.com/beworker/knot/raw/master/docs/diagrams/flowchart-composite-knot.png)
*
* Each `Delegate` is isolated from the other `Delegates`. It defines its own set of
* `Changes`, `Actions` and `Reducers`. It's only the `State`, that is shared between
* the `Delegates`. In that respect each `Delegate` can be seen as a separate [Knot] instance.
*
* Once all `Delegates` are registered at a `CompositeKnot`, the knot can be finally
* composed using [compose] function and start operating.
*
* See [Composite ViewModel](https://www.halfbit.de/posts/composite-viewmodel/) for more details.
*/
interface CompositeKnot<State : Any> : Knot<State, Any> {
/** Registers a new `Delegate` in this composite knot. */
@Deprecated(
"Primes were renamed into Delegates. Use registerDelegate(block) instead.",
ReplaceWith("registerDelegate(other)"),
DeprecationLevel.WARNING
)
fun <Change : Any, Action : Any> registerPrime(
block: DelegateBuilder<State, Change, Action>.() -> Unit
)
/** Registers a new `Delegate` in this composite knot. */
fun <Change : Any, Action : Any> registerDelegate(
block: DelegateBuilder<State, Change, Action>.() -> Unit
)
/** Finishes composition of `Delegates` and moves this knot into the operational mode. */
fun compose()
}
internal class DefaultCompositeKnot<State : Any>(
initialState: State,
observeOn: Scheduler?,
reduceOn: Scheduler?,
stateInterceptors: MutableList<Interceptor<State>>,
changeInterceptors: MutableList<Interceptor<Any>>,
actionInterceptors: MutableList<Interceptor<Any>>,
actionSubject: Subject<Any>
) : CompositeKnot<State> {
private val coldEventSources = lazy { mutableListOf<EventSource<Any>>() }
private val composition = AtomicReference(
Composition(
initialState,
observeOn,
reduceOn,
stateInterceptors,
changeInterceptors,
actionInterceptors,
actionSubject
)
)
private val stateSubject = BehaviorSubject.create<State>()
private val changeSubject = PublishSubject.create<Any>()
private val disposables = CompositeDisposable()
private val subscriberCount = AtomicInteger()
private var coldEventsDisposable: Disposable? = null
private var coldEventsObservable: Observable<Any>? = null
override fun <Change : Any, Action : Any> registerPrime(
block: DelegateBuilder<State, Change, Action>.() -> Unit
) = registerDelegate(block)
@Suppress("UNCHECKED_CAST")
override fun <Change : Any, Action : Any> registerDelegate(
block: DelegateBuilder<State, Change, Action>.() -> Unit
) {
composition.get()?.let {
DelegateBuilder(
it.reducers,
it.eventSources,
coldEventSources,
it.actionTransformers,
it.stateInterceptors,
it.changeInterceptors,
it.actionInterceptors
).also(block as DelegateBuilder<State, Any, Any>.() -> Unit)
} ?: error("Delegates cannot be registered after compose() was called")
}
override fun isDisposed(): Boolean = disposables.isDisposed
override fun dispose() = disposables.dispose()
override val state: Observable<State> = stateSubject
.doOnSubscribe { if (subscriberCount.getAndIncrement() == 0) maybeSubscribeColdEvents() }
.doFinally { if (subscriberCount.decrementAndGet() == 0) maybeUnsubscribeColdEvents() }
override val change: Consumer<Any> = Consumer {
check(composition.get() == null) { "compose() must be called before emitting any change." }
changeSubject.onNext(it)
}
@Synchronized
private fun maybeSubscribeColdEvents() {
if (coldEventSources.isInitialized() &&
coldEventsDisposable == null &&
subscriberCount.get() > 0
) {
val coldEventsObservable =
this.coldEventsObservable
?: coldEventSources
.mergeIntoObservable()
.also { this.coldEventsObservable = it }
coldEventsDisposable =
coldEventsObservable
.subscribe(
changeSubject::onNext,
changeSubject::onError
)
}
}
@Synchronized
private fun maybeUnsubscribeColdEvents() {
coldEventsDisposable?.let {
it.dispose()
coldEventsDisposable = null
}
}
override fun compose() {
composition.getAndSet(null)?.let { composition ->
disposables.add(
Observable
.merge(
mutableListOf<Observable<Any>>().apply {
this += changeSubject
composition.actionSubject
.intercept(composition.actionInterceptors)
.bind(composition.actionTransformers) { this += it }
composition.eventSources
.map { source -> this += source() }
}
)
.let { stream -> composition.reduceOn?.let { stream.observeOn(it) } ?: stream }
.serialize()
.intercept(composition.changeInterceptors)
.scan(composition.initialState) { state, change ->
val reducer = composition.reducers[change::class]
?: error("Cannot find reducer for $change")
reducer(state, change).emitActions(composition.actionSubject)
}
.distinctUntilChanged { prev, curr -> prev === curr }
.let { stream -> composition.observeOn?.let { stream.observeOn(it) } ?: stream }
.intercept(composition.stateInterceptors)
.subscribe(
stateSubject::onNext,
RxJavaPlugins::onError
)
)
maybeSubscribeColdEvents()
} ?: error("compose() must be called just once.")
}
private class Composition<State : Any>(
val initialState: State,
val observeOn: Scheduler?,
val reduceOn: Scheduler?,
val stateInterceptors: MutableList<Interceptor<State>>,
val changeInterceptors: MutableList<Interceptor<Any>>,
val actionInterceptors: MutableList<Interceptor<Any>>,
val actionSubject: Subject<Any>
) {
val reducers = mutableMapOf<KClass<out Any>, Reducer<State, Any, Any>>()
val actionTransformers = mutableListOf<ActionTransformer<Any, Any>>()
val eventSources = mutableListOf<EventSource<Any>>()
}
}
| 0
|
Kotlin
|
20
| 232
|
f82aa576159e5dbe1ced2cec231dd4e589d69d6e
| 7,808
|
knot
|
Apache License 2.0
|
android/app/src/main/java/com/algorand/android/ui/confirmation/ConfirmationBottomSheet.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.ui.confirmation
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.navigation.fragment.navArgs
import com.algorand.android.models.ConfirmationBottomSheetResult
import com.algorand.android.utils.BaseDoubleButtonBottomSheet
import com.algorand.android.utils.setNavigationResult
import com.google.android.material.button.MaterialButton
class ConfirmationBottomSheet : BaseDoubleButtonBottomSheet() {
private val args by navArgs<ConfirmationBottomSheetArgs>()
override fun setTitleText(textView: TextView) {
textView.setText(args.parameters.titleResId)
}
override fun setDescriptionText(textView: TextView) {
textView.text = args.parameters.descriptionText
}
override fun setAcceptButton(materialButton: MaterialButton) {
materialButton.apply {
text = getString(args.parameters.confirmButtonTextResId)
setOnClickListener { setResultAndNavigateBack(true) }
}
}
override fun setCancelButton(materialButton: MaterialButton) {
materialButton.apply {
text = getString(args.parameters.rejectButtonTextResId)
setOnClickListener { setResultAndNavigateBack(false) }
}
}
override fun setIconImageView(imageView: ImageView) {
imageView.apply {
setImageResource(args.parameters.iconDrawableResId)
imageTintList = ContextCompat.getColorStateList(context, args.parameters.imageTintResId)
}
}
private fun setResultAndNavigateBack(isAccepted: Boolean) {
val result = ConfirmationBottomSheetResult(args.parameters.confirmationIdentifier, isAccepted)
setNavigationResult(RESULT_KEY, result)
navBack()
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 2,388
|
pera-wallet
|
Apache License 2.0
|
payment-starter/src/main/kotlin/com/labijie/application/payment/PaymentCallbackRequest.kt
|
hongque-pro
| 309,874,586
| false
|
{"Kotlin": 1051148, "Java": 72766}
|
package com.labijie.application.payment
import java.math.BigDecimal
/**
* 第三方平台的回调处理结果
*/
data class PaymentCallbackRequest(
val appid:String,
val tradeId:String,
val platformTradeId:String,
val status: PaymentTradeStatus,
val timePaid: Long,
val amount:BigDecimal,
val platformBuyerId:String? = null,
val originalPayload:Map<String, String> = mapOf())
| 0
|
Kotlin
|
0
| 8
|
f2f709ee8fff5b6d416bc35c5d7e234a4781b096
| 388
|
application-framework
|
Apache License 2.0
|
sample/src/main/java/com/palatin/cardinalsample/ui/login/LoginActivity.kt
|
palatin
| 282,827,304
| false
| null |
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palatin.cardinalsample.ui.login
import android.app.Activity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.material.snackbar.Snackbar
import com.palatin.cardinal.*
import com.palatin.cardinalsample.R
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.launch
class LoginActivity : AppCompatActivity() {
private val vm: LoginViewModel by viewModels { LoginViewModel.LoginViewModelFactory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
vm.subscribeOnState(this, Observer {
btn_login.isEnabled = it.isFormCorrect
if(et_username.text.toString() != it.email)
et_username.setText(it.email)
if(et_password.text.toString() != it.password)
et_password.setText(it.password)
loading.visibility = if(it.isLoading) View.VISIBLE else View.GONE
})
lifecycleScope.launch {
vm.subscribeOnSideEffects(this) {
when(it) {
is LoginViewModel.SideEffect.ShowSnack -> Snackbar.make(container, it.message, Snackbar.LENGTH_SHORT).show()
}
}
vm.bindActions(this@LoginActivity,
et_username.textChangesAction { text, start, before, count -> LoginViewModel.Action.AccountFormChanged.EmailChanged(text?.toString() ?: "" ) },
et_password.textChangesAction { text, start, before, count -> LoginViewModel.Action.AccountFormChanged.PasswordChanged(text?.toString() ?: "" ) },
btn_login.clickAction { LoginViewModel.Action.OnLoginClicked }
)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
6d9b6de7fd1650f1d47767cfcb6c007064cec861
| 2,809
|
cardinal
|
Apache License 2.0
|
kcrud-base/src/main/kotlin/kcrud/base/plugins/ContentNegotiation.kt
|
perracodex
| 682,128,013
| false
|
{"Kotlin": 552738, "JavaScript": 17898, "CSS": 7959, "Dockerfile": 3297, "HTML": 579}
|
/*
* Copyright (c) 2024-Present Perracodex. All rights reserved.
* This work is licensed under the terms of the MIT license.
* For a copy, see <https://opensource.org/licenses/MIT>
*/
package kcrud.base.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.json.Json
/**
* The [ContentNegotiation] plugin serves two primary purposes:
*
* 1. Negotiating media types between the client and server.
* For this, it uses the Accept and Content-Type headers.
*
* 2. Serializing/deserializing the content in a specific format.
* Ktor supports the following formats out-of-the-box: JSON, XML, CBOR, and ProtoBuf.
*
* See: [Content negotiation and serialization](https://ktor.io/docs/serialization.html#0)
*
* See: [Kotlin Serialization Guide](https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serialization-guide.md)
*/
fun Application.configureContentNegotiation() {
install(plugin = ContentNegotiation) {
// Define the behavior and characteristics for JSON serialization.
json(Json {
prettyPrint = true // Format JSON output for easier reading.
encodeDefaults = true // Serialize properties with default values.
ignoreUnknownKeys = false // Fail on unknown keys in the incoming JSON.
})
}
}
| 0
|
Kotlin
|
0
| 2
|
7faa3d74588e41a48ac48bb56e80bb02c48f0ba3
| 1,417
|
Kcrud
|
MIT License
|
app/src/main/java/com/android/ranks/ui/adapter/BaseAdapter.kt
|
ArtyomMashkin
| 335,926,220
| false
| null |
package com.android.ranks.ui.adapter
import android.view.View
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<ItemType>(diffCallback: DiffUtil.ItemCallback<ItemType>) :
PagedListAdapter<ItemType, BaseViewHolder<ItemType>>(diffCallback) {
override fun onBindViewHolder(holder: BaseViewHolder<ItemType>, position: Int) {
getItem(position)?.let { holder.bindView(it) }
}
}
abstract class BaseViewHolder<ItemType>(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bindView(item: ItemType)
}
| 0
|
Kotlin
|
0
| 0
|
ff9d9e126249ceb13c32760a06b85845485a14f6
| 646
|
Ranks
|
Apache License 2.0
|
app/src/main/java/hu/mczinke/nasa_apod_viewer/search/presentation/components/ApodListItem.kt
|
CzinkeM
| 503,428,423
| false
|
{"Kotlin": 41835}
|
package hu.mczinke.nasa_apod_viewer.search.presentation.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Card
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import hu.mczinke.nasa_apod_viewer.core.domain.Apod
@Composable
fun ApodListItem(
modifier: Modifier = Modifier,
apod: Apod
) {
Box(modifier = Modifier.size(100.dp))
}
| 0
|
Kotlin
|
0
| 0
|
8e62a96662df86c65453e395836b6b1cf9e0ae25
| 493
|
android-apod-viewer
|
MIT License
|
src/main/kotlin/de/flapdoodle/sqlextract/config/TableAndColumn.kt
|
flapdoodle-oss
| 363,965,979
| false
| null |
package de.flapdoodle.sqlextract.config
import de.flapdoodle.sqlextract.db.Name
typealias TableAndColumn = Pair<Name, String>
object TableAndColumns {
fun parse(schema: String, tableAndColumn: String): TableAndColumn {
val idx = tableAndColumn.indexOf(':')
require(idx != -1) { "wrong format: $tableAndColumn != <TABLE:COLUMN>" }
require(idx > 0) { "missing SCHEMA.TABLE: $tableAndColumn != <TABLE:COLUMN>" }
require(idx < tableAndColumn.length) { "missing COLUMN: $tableAndColumn != <TABLE:COLUMN>" }
return Name(tableAndColumn.substring(0, idx), schema) to tableAndColumn.substring(idx + 1)
}
}
| 0
|
Kotlin
|
0
| 0
|
69aa6dd554dc011d3bbc75fabcddfad173b41a79
| 647
|
de.flapdoodle.sqlextract
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/autoscaling/BlockDeviceVolume.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 142794926}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.autoscaling
import io.cloudshiftdev.awscdk.common.CdkObject
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.jvm.JvmName
/**
* Describes a block device mapping for an EC2 instance or Auto Scaling group.
*
* Example:
*
* ```
* Vpc vpc;
* InstanceType instanceType;
* IMachineImage machineImage;
* AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
* .vpc(vpc)
* .instanceType(instanceType)
* .machineImage(machineImage)
* .blockDevices(List.of(BlockDevice.builder()
* .deviceName("gp3-volume")
* .volume(BlockDeviceVolume.ebs(15, EbsDeviceOptions.builder()
* .volumeType(EbsDeviceVolumeType.GP3)
* .throughput(125)
* .build()))
* .build()))
* .build();
* ```
*/
public open class BlockDeviceVolume(
cdkObject: software.amazon.awscdk.services.autoscaling.BlockDeviceVolume,
) : CdkObject(cdkObject) {
/**
* EBS device info.
*/
public open fun ebsDevice(): EbsDeviceProps? =
unwrap(this).getEbsDevice()?.let(EbsDeviceProps::wrap)
/**
* Virtual device name.
*/
public open fun virtualName(): String? = unwrap(this).getVirtualName()
public companion object {
public fun ebs(volumeSize: Number): BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.ebs(volumeSize).let(BlockDeviceVolume::wrap)
public fun ebs(volumeSize: Number, options: EbsDeviceOptions): BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.ebs(volumeSize,
options.let(EbsDeviceOptions.Companion::unwrap)).let(BlockDeviceVolume::wrap)
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("e337c12e70e7c20d7a26e3d77c0a74a51127cce07791566196e75f0d43459d0c")
public fun ebs(volumeSize: Number, options: EbsDeviceOptions.Builder.() -> Unit):
BlockDeviceVolume = ebs(volumeSize, EbsDeviceOptions(options))
public fun ebsFromSnapshot(snapshotId: String): BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.ebsFromSnapshot(snapshotId).let(BlockDeviceVolume::wrap)
public fun ebsFromSnapshot(snapshotId: String, options: EbsDeviceSnapshotOptions):
BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.ebsFromSnapshot(snapshotId,
options.let(EbsDeviceSnapshotOptions.Companion::unwrap)).let(BlockDeviceVolume::wrap)
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("d2c4097e9826e13baaeed791f5b14f0e259b1ce41e303a712c6116628f71dca9")
public fun ebsFromSnapshot(snapshotId: String,
options: EbsDeviceSnapshotOptions.Builder.() -> Unit): BlockDeviceVolume =
ebsFromSnapshot(snapshotId, EbsDeviceSnapshotOptions(options))
public fun ephemeral(volumeIndex: Number): BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.ephemeral(volumeIndex).let(BlockDeviceVolume::wrap)
public fun noDevice(): BlockDeviceVolume =
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume.noDevice().let(BlockDeviceVolume::wrap)
internal fun wrap(cdkObject: software.amazon.awscdk.services.autoscaling.BlockDeviceVolume):
BlockDeviceVolume = BlockDeviceVolume(cdkObject)
internal fun unwrap(wrapped: BlockDeviceVolume):
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume = wrapped.cdkObject as
software.amazon.awscdk.services.autoscaling.BlockDeviceVolume
}
}
| 4
|
Kotlin
|
0
| 4
|
a9befd2eccd63644f6662a4877d5b00ab9f85295
| 3,671
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
feature/streak/src/main/java/com/githukudenis/comlib/feature/streak/StreakViewModel.kt
|
DenisGithuku
| 707,847,935
| false
|
{"Kotlin": 416771, "Java": 95753, "Roff": 12367}
|
package com.githukudenis.comlib.feature.streak
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.githukudenis.comlib.core.common.DataResult
import com.githukudenis.comlib.core.common.StatefulViewModel
import com.githukudenis.comlib.core.domain.usecases.GetAllBooksUseCase
import com.githukudenis.comlib.core.domain.usecases.GetReadBooksUseCase
import com.githukudenis.comlib.core.domain.usecases.GetStreakUseCase
import com.githukudenis.comlib.core.domain.usecases.SaveStreakUseCase
import com.githukudenis.comlib.core.domain.usecases.UpdateStreakUseCase
import com.githukudenis.comlib.core.model.book.Book
import com.githukudenis.comlib.core.model.book.BookMilestone
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.plus
import kotlinx.datetime.todayIn
import javax.inject.Inject
data class StreakUiState(
val isLoading: Boolean = false,
val selectedBook: StreakBook? = null,
val milestoneId: Long? = null,
val saveSuccess: Boolean = false,
val availableBooks: List<Book> = emptyList(),
val startDate: LocalDate = Clock.System.todayIn(TimeZone.currentSystemDefault()),
val endDate: LocalDate = Clock.System.todayIn(TimeZone.currentSystemDefault())
.plus(7, DateTimeUnit.DAY),
val error: String? = null,
) {
val isValid: Boolean = selectedBook != null
}
data class StreakBook(
val id: String?, val title: String?, val pages: Int? = null
)
fun Book.asStreakBook(): StreakBook = StreakBook(id, title, pages)
@HiltViewModel
class StreakViewModel @Inject constructor(
private val getAllBooksUseCase: GetAllBooksUseCase,
private val getReadBooksUseCase: GetReadBooksUseCase,
private val saveStreakUseCase: SaveStreakUseCase,
private val getStreakUseCase: GetStreakUseCase,
private val updateStreakUseCase: UpdateStreakUseCase,
private val savedStateHandle: SavedStateHandle
) : StatefulViewModel<StreakUiState>(StreakUiState()) {
init {
savedStateHandle.get<String>("bookId").also {
getStreakDetails(it)
}
getAvailableBooks()
}
private fun getStreakDetails(bookId: String?) {
if (bookId == null) return
viewModelScope.launch {
val bookMilestone = getStreakUseCase().first()
bookMilestone?.let { bookMilestone ->
update {
copy(
milestoneId = bookMilestone.id,
selectedBook = StreakBook(
id = bookMilestone.bookId, title = bookMilestone.bookName, pages = bookMilestone.pages
),
startDate = bookMilestone.startDate?.toLocalDate()!!,
endDate = bookMilestone.endDate?.toLocalDate()!!
)
}
}
}
}
private fun getAvailableBooks() {
viewModelScope.launch {
val readBooks = getReadBooksUseCase().first()
getAllBooksUseCase().collectLatest { result ->
when (result) {
DataResult.Empty -> {
update { copy(isLoading = false, error = "No books available") }
}
is DataResult.Error -> update {
copy(
error = result.message, isLoading = false
)
}
is DataResult.Loading -> update {
copy(
isLoading = true
)
}
is DataResult.Success -> update {
copy(isLoading = false,
availableBooks = result.data.filterNot { it.id in readBooks })
}
}
}
}
}
fun onToggleBook(streakBook: StreakBook?) {
update { copy(selectedBook = streakBook) }
}
fun onSaveStreak() {
viewModelScope.launch {
val milestone = BookMilestone(
bookId = state.value.selectedBook?.id,
bookName = state.value.selectedBook?.title,
startDate = state.value.startDate.atStartOfDayIn(TimeZone.currentSystemDefault())
.toEpochMilliseconds(),
endDate = state.value.endDate.atStartOfDayIn(TimeZone.currentSystemDefault())
.toEpochMilliseconds(),
pages = state.value.selectedBook?.pages
)
if(savedStateHandle.get<String>("bookId") == null) {
saveStreakUseCase(milestone)
} else {
updateStreakUseCase(
milestone.copy(id = state.value.milestoneId)
)
}
update {
copy(saveSuccess = true)
}
}
}
fun onChangeStartDate(date: LocalDate) {
update { copy(startDate = date) }
}
fun onChangeEndDate(date: LocalDate) {
update { copy(endDate = date) }
}
}
| 3
|
Kotlin
|
1
| 0
|
0c0b0d364b329ca40b5d39bcacf8ca9e70b0874e
| 5,385
|
comlib-android-client
|
Apache License 2.0
|
one-client-react-native/android/src/main/java/com/eartho/one_rn/EarthoOneModuleModule.kt
|
eartho-group
| 501,142,276
| false
| null |
package com.eartho.one_rn
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReadableArray
import com.eartho.one.EarthoOne
import com.eartho.one.EarthoOneConfig
import com.eartho.one.request.DefaultClient
import com.google.gson.Gson
class EarthoOneModuleModule(val reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
private lateinit var config: EarthoOneConfig
private lateinit var earthoOne: EarthoOne
override fun getName(): String {
return "EarthoModule"
}
@ReactMethod
fun initEartho(clientId: String, clientSecret: String, enabledProviders: ReadableArray?, promise: Promise) {
config = EarthoOneConfig(
clientId = clientId,
clientSecret = clientSecret,
enabledProviders = enabledProviders?.toArrayList()?.map{ it as String }?.toTypedArray()
)
// config.networkingClient = DefaultClient(enableLogging = true)
val activity = getCurrentActivity();
earthoOne = EarthoOne(activity!!, config)
earthoOne.init()
promise.resolve("")
}
@ReactMethod
fun connectWithRedirect(accessId: String, promise: Promise) {
val gson = Gson()
try {
earthoOne.connectWithRedirect(
accessId = accessId,
onSuccess = { c ->
val d = gson.toJson(c)
promise.resolve(d)
}, onFailure = { f ->
promise.reject("AuthenticationException", f.message + f.cause?.message, f)
})
} catch (e: Exception) {
e.printStackTrace()
promise.reject("AuthenticationException", e.message, e)
}
}
@ReactMethod
fun getUser(a: String, promise: Promise) {
try {
val user = earthoOne.getUser() ?: return promise.resolve(null);
val gson = Gson()
val d = gson.toJson(user)
promise.resolve(d)
} catch (e: Exception) {
promise.reject("Exception", e.message, e)
}
}
@ReactMethod
fun getIdToken(a: String, promise: Promise) {
try {
earthoOne.getIdToken(onSuccess = { c ->
promise.resolve(c.idToken)
},
onFailure = { e ->
promise.reject("CredentialsException", e.message, e)
})
} catch (e: Exception) {
promise.reject("CredentialsException", e.message, e)
}
}
@ReactMethod
fun disconnect(a: String, promise: Promise) {
try {
val user = earthoOne.logout()
} catch (e: Exception) {
promise.reject("Exception", e.message, e)
}
}
}
| 12
| null |
1
| 18
|
9d9a3aa27efda318804ae5fb8e657d2ae93d8433
| 2,612
|
eartho-packages
|
MIT License
|
lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/IssueRegistry.kt
|
lgvalle
| 368,149,676
| false
| null |
package com.vanniktech.lintrules.android
import com.android.tools.lint.detector.api.CURRENT_API
internal const val PRIORITY = 10 // Does not matter anyways within Lint.
class IssueRegistry : com.android.tools.lint.client.api.IssueRegistry() {
override val api = CURRENT_API
override val issues get() = listOf(
ISSUE_RESOURCES_GET_DRAWABLE,
ISSUE_RESOURCES_GET_COLOR,
ISSUE_RESOURCES_GET_COLOR_STATE_LIST,
ISSUE_INVALID_IMPORT,
ISSUE_WRONG_VIEW_ID_FORMAT,
ISSUE_WRONG_MENU_ID_FORMAT,
ISSUE_RAW_DIMEN,
ISSUE_RAW_COLOR,
ISSUE_SUPERFLUOUS_MARGIN_DECLARATION,
ISSUE_SUPERFLUOUS_PADDING_DECLARATION,
ISSUE_SHOULD_USE_STATIC_IMPORT,
ISSUE_MATCHING_VIEW_ID,
ISSUE_MATCHING_MENU_ID,
ISSUE_JCENTER,
ISSUE_INVALID_SINGLE_LINE_COMMENT,
ISSUE_INVALID_STRING,
ISSUE_DEFAULT_LAYOUT_ATTRIBUTE,
ISSUE_TODO,
ISSUE_WRONG_CONSTRAINT_LAYOUT_USAGE,
ISSUE_MISSING_XML_HEADER,
ISSUE_WRONG_TEST_METHOD_NAME,
ISSUE_WRONG_LAYOUT_NAME,
ISSUE_WRONG_ANNOTATION_ORDER,
ISSUE_CONSTRAINT_LAYOUT_TOOLS_EDITOR_ATTRIBUTE_DETECTOR,
ISSUE_SUPERFLUOUS_NAME_SPACE,
ISSUE_XML_SPACING,
ISSUE_NAMING_PATTERN,
ISSUE_UNUSED_MERGE_ATTRIBUTES,
ISSUE_LAYOUT_FILE_NAME_MATCHES_CLASS,
ISSUE_UNSUPPORTED_LAYOUT_ATTRIBUTE,
ISSUE_ASSERTJ_IMPORT
)
}
| 0
| null |
0
| 1
|
e9a0931c558017200c060264aa4328d6fccc14d2
| 1,392
|
lint-rules
|
Apache License 2.0
|
parent-feature/src/main/java/com/cheise_proj/parent_feature/ParentNavigationActivity.kt
|
marshall219
| 249,870,132
| true
|
{"Kotlin": 788935}
|
package com.cheise_proj.parent_feature
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupActionBarWithNavController
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.cheise_proj.common_module.DELAY_HANDLER
import com.cheise_proj.common_module.PICSUM_URL
import com.cheise_proj.parent_feature.base.BaseActivity
import com.cheise_proj.parent_feature.utils.ConnectionLiveData
import com.cheise_proj.presentation.viewmodel.SharedViewModel
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.android.synthetic.main.content_parent_navigation.*
class ParentNavigationActivity : BaseActivity() {
companion object {
fun getIntent(context: Context): Intent =
Intent(context, ParentNavigationActivity::class.java)
}
private lateinit var navController: NavController
private lateinit var drawerLayout: DrawerLayout
private lateinit var navView: NavigationView
private lateinit var sharedViewModel: SharedViewModel
private val textBadgeViews = arrayListOf<TextView>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_parent_navigation)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
connectionLiveData = ConnectionLiveData(this)
val snack = Snackbar.make(root, "", Snackbar.LENGTH_INDEFINITE)
navView = findViewById(R.id.nav_view)
drawerLayout = findViewById(R.id.drawer_layout)
setupNavigation()
initNavBadge()
setProfileData(navView)
configureViewModel()
openNavigationMenu()
subscribeNetworkChange(snack)
firebaseMessageSubscription()
// dialogUseBackgroundChanger()
}
private fun subscribeNetworkChange(snack: Snackbar) {
connectionLiveData.observe(this, Observer {
if (!it) {
root.background = baseContext.getDrawable(R.drawable.no_internet)
snack.setText(getString(R.string.no_network_connection))
snack.show()
} else {
root.background = getDrawable(R.drawable.background)
snack.dismiss()
}
})
}
private fun configureViewModel() {
sharedViewModel = ViewModelProvider(this)[SharedViewModel::class.java]
sharedViewModel.getBadgeValue().observe(this, Observer {
setNavMenuBadge(it)
})
}
private fun setNavMenuBadge(badge: Pair<Int, Int?>?) {
val str = if (badge?.second != null && badge.second!! > 0) "${badge.second} +" else ""
when (badge?.first) {
R.id.messageFragment -> textBadgeViews[0].text = str
R.id.circularFragment2 -> textBadgeViews[1].text = str
R.id.assignmentFragment -> textBadgeViews[2].text = str
R.id.reportFragment2 -> textBadgeViews[3].text = str
R.id.timeTableFragment -> textBadgeViews[4].text = str
R.id.billFragment -> textBadgeViews[5].text = str
}
}
private fun initNavBadge() {
val menuNav = navView.menu
textBadgeViews.add(menuNav.findItem(R.id.messageFragment).actionView as TextView)
textBadgeViews.add(menuNav.findItem(R.id.circularFragment2).actionView as TextView)
textBadgeViews.add(menuNav.findItem(R.id.assignmentFragment).actionView as TextView)
textBadgeViews.add(menuNav.findItem(R.id.reportFragment2).actionView as TextView)
textBadgeViews.add(menuNav.findItem(R.id.timeTableFragment).actionView as TextView)
textBadgeViews.add(menuNav.findItem(R.id.billFragment).actionView as TextView)
textBadgeViews.forEach {
it.apply {
gravity = Gravity.CENTER_VERTICAL
typeface = Typeface.DEFAULT_BOLD
setTextColor(ContextCompat.getColor(baseContext, android.R.color.holo_red_dark))
}
}
}
private fun openNavigationMenu() {
val handler = Handler(Looper.getMainLooper())
handler.postDelayed(
{
drawerLayout.openDrawer(GravityCompat.START)
}, 2000
)
}
private fun dialogUseBackgroundChanger() {
if (prefs.getFirstTimeLogin()) {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setTitle(getString(R.string.background_changer_title))
dialogBuilder.setMessage(getString(R.string.background_changer_message))
dialogBuilder.setPositiveButton(getString(R.string.dialog_positive_response)) { dialog, _ ->
prefs.setBackgroundChanger(true)
dialog.dismiss()
}
dialogBuilder.setNegativeButton(getString(R.string.dialog_negative_response)) { dialog, _ ->
prefs.setBackgroundChanger(false)
dialog.dismiss()
}
prefs.setFirstTimeLogin(false)
dialogBuilder.setCancelable(false)
dialogBuilder.show()
}
}
private fun setBackgroundChanger() {
if (prefs.getBackgroundChanger()) {
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({
Glide.with(baseContext).load(PICSUM_URL)
.diskCacheStrategy(
DiskCacheStrategy.NONE
)
.into(object : CustomTarget<Drawable>() {
override fun onLoadCleared(placeholder: Drawable?) {
}
override fun onResourceReady(
resource: Drawable,
transition: Transition<in Drawable>?
) {
root.background = resource
}
})
}, DELAY_HANDLER + 500)
}
}
private fun setupNavigation() {
navController = findNavController(R.id.fragment_socket)
setupActionBarWithNavController(navController, drawerLayout)
navView.setNavigationItemSelectedListener { menuItem ->
menuItem.isChecked = true
drawerLayout.closeDrawers()
true
}
NavigationUI.setupWithNavController(navView, navController)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_logout -> navigation.logout(this,getParentTopic())
}
return super.onOptionsItemSelected(item)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController, drawerLayout)
}
private fun firebaseMessageSubscription() {
FirebaseMessaging.getInstance().subscribeToTopic(getParentTopic()).addOnCompleteListener {
if (!it.isSuccessful) {
println("Task Failed")
return@addOnCompleteListener
}
println("subscribe parent topic")
}
}
private fun getParentTopic(): String {
return if (BuildConfig.DEBUG) getString(R.string.fcm_topic_dev_parent) else getString(R.string.fcm_topic_parent)
}
}
| 0
| null |
0
| 0
|
0183ab6165a42be83691dd7281efc6d738ebe88c
| 8,438
|
Nagies-Edu-Center
|
Apache License 2.0
|
formula-android/src/main/java/com/instacart/formula/android/FeatureEvent.kt
|
instacart
| 171,923,573
| false
| null |
package com.instacart.formula.android
sealed class FeatureEvent {
data class Init(override val id: FragmentId, val feature: Feature): FeatureEvent()
data class Failure(override val id: FragmentId, val error: Throwable): FeatureEvent()
data class MissingBinding(override val id: FragmentId): FeatureEvent()
abstract val id: FragmentId
}
| 8
| null |
14
| 151
|
26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff
| 353
|
formula
|
BSD 3-Clause Clear License
|
app/src/main/java/com/obaralic/how2/model/database/UserDao.kt
|
obaralic
| 186,580,640
| false
| null |
/**
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.obaralic.how2.model.database
import androidx.room.*
import androidx.room.OnConflictStrategy.REPLACE
@Dao
interface UserDao {
@Insert(onConflict = REPLACE)
fun insert(user: UserEntity)
@Update
fun update(user: UserEntity)
@Delete
fun delete(user: UserEntity)
@Query("DELETE FROM users_table")
fun deleteAll()
@Query("SELECT * FROM users_table WHERE uid == :id")
fun findById(id: Long): UserEntity
@Query("SELECT COUNT(*) FROM users_table")
fun getCount(): Int
}
| 0
|
Kotlin
|
0
| 0
|
5ad642d2cb7b1486c044f9188cee0778d2c38e44
| 1,118
|
dagger-android-mvvm
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/annotations/AnnotationIdentifier.fir.kt
|
android
| 263,405,600
| true
| null |
// FILE: a.kt
annotation class annotation
// FILE: test/b.kt
package test
@test.annotation class annotation
// FILE: other/c.kt
package other
annotation class My
@test.annotation class Your
@My class Our
| 0
|
Kotlin
|
37
| 316
|
74126637a097f5e6b099a7b7a4263468ecfda144
| 212
|
kotlin
|
Apache License 2.0
|
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/settings/SeedView.kt
|
ACINQ
| 192,964,514
| false
| null |
/*
* Copyright 2021 ACINQ SAS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.acinq.phoenix.android.settings
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import fr.acinq.phoenix.android.R
import fr.acinq.phoenix.android.components.*
import fr.acinq.phoenix.android.navController
import fr.acinq.phoenix.android.security.EncryptedSeed
import fr.acinq.phoenix.android.security.KeyState
import fr.acinq.phoenix.android.security.SeedManager
import fr.acinq.phoenix.android.utils.annotatedStringResource
import fr.acinq.phoenix.android.utils.logger
import fr.acinq.phoenix.android.utils.mutedTextColor
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private sealed class SeedViewState() {
object Init : SeedViewState()
object ReadingSeed : SeedViewState()
data class ShowSeed(val words: List<String>) : SeedViewState()
data class Error(val message: String) : SeedViewState()
}
@Composable
fun SeedView() {
val log = logger("SeedView")
val nc = navController
val context = LocalContext.current
val scope = rememberCoroutineScope()
var state by remember { mutableStateOf<SeedViewState>(SeedViewState.Init) }
SettingScreen {
SettingHeader(onBackClick = { nc.popBackStack() }, title = stringResource(id = R.string.displayseed_title))
Card(internalPadding = PaddingValues(16.dp)) {
Text(text = annotatedStringResource(id = R.string.displayseed_instructions))
}
Spacer(modifier = Modifier.height(16.dp))
Card {
when (val s = state) {
is SeedViewState.Init -> {
SettingButton(text = R.string.displayseed_authenticate_button, icon = R.drawable.ic_key) {
state = SeedViewState.ReadingSeed
scope.launch {
val keyState = SeedManager.getSeedState(context)
when {
keyState is KeyState.Present && keyState.encryptedSeed is EncryptedSeed.V2.NoAuth -> {
val words = EncryptedSeed.toMnemonics(keyState.encryptedSeed.decrypt())
delay(300)
state = SeedViewState.ShowSeed(words)
}
keyState is KeyState.Error.Unreadable -> {
state = SeedViewState.Error(context.getString(R.string.displayseed_error_details, keyState.message ?: "n/a"))
}
else -> {
log.info { "unable to read seed in state=$keyState" }
// TODO: handle errors
}
}
}
}
}
is SeedViewState.ReadingSeed -> {
Row (modifier = Modifier.padding(16.dp).fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
IconWithText(icon = R.drawable.ic_key, text = stringResource(id = R.string.displayseed_loading))
}
}
is SeedViewState.ShowSeed -> {
SeedDialog(onDismiss = { state = SeedViewState.Init }, words = s.words)
}
}
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun SeedDialog(words: List<String>, onDismiss: () -> Unit) {
val log = logger("SeedDialog")
Dialog(
onDismiss = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Column(
modifier = Modifier.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.displayseed_dialog_header),
style = MaterialTheme.typography.body1.copy(textAlign = TextAlign.Center)
)
Spacer(modifier = Modifier.height(32.dp))
if (words.isEmpty()) {
Text("reading seed...")
} else {
val groupedWords: List<Pair<String, String>> = remember(words) {
words.mapIndexed { i, w ->
if (i + (words.size / 2) < words.size) {
words[i] to words[i + (words.size / 2)]
} else {
null
}
}.filterNotNull()
}
val typo = MaterialTheme.typography.body1
val indexColor = mutedTextColor()
val indexStyle = remember(typo) { typo.copy(fontSize = 12.sp, textAlign = TextAlign.End, color = indexColor) }
val wordStyle = remember(typo) { typo.copy(fontWeight = FontWeight.Bold) }
groupedWords.forEachIndexed { index, wordPair ->
Row(
modifier = Modifier
.wrapContentHeight()
.widthIn(max = 300.dp)
) {
Cell(text = "#${index + 1}", modifier = Modifier.width(24.dp), textStyle = indexStyle)
Spacer(modifier = Modifier.width(4.dp))
Cell(text = wordPair.first, modifier = Modifier.width(100.dp), textStyle = wordStyle)
Spacer(modifier = Modifier.width(8.dp))
Cell(text = "#${index + words.size / 2 + 1}", modifier = Modifier.width(24.dp), textStyle = indexStyle)
Spacer(modifier = Modifier.width(4.dp))
Cell(text = wordPair.second, modifier = Modifier.width(100.dp), textStyle = wordStyle)
}
Spacer(modifier = Modifier.height(4.dp))
}
}
Spacer(modifier = Modifier.height(32.dp))
Text(
text = stringResource(id = R.string.displayseed_derivation_path),
style = TextStyle(textAlign = TextAlign.Center, color = mutedTextColor())
)
}
}
}
@Composable
private fun RowScope.Cell(
text: String,
modifier: Modifier = Modifier,
textStyle: TextStyle = MaterialTheme.typography.body1
) {
Text(
text = text,
modifier = modifier.alignBy(FirstBaseline),
style = textStyle
)
}
| 68
| null |
75
| 399
|
b8a0562bc6e1a13491f494bae3187cae0ee63a1e
| 7,649
|
phoenix
|
Apache License 2.0
|
plugins/search-everywhere-ml/ranking/src/com/intellij/searchEverywhereMl/ranking/model/SearchEverywhereAllRankingModelLoader.kt
|
ingokegel
| 72,937,917
| false
| null |
package com.intellij.searchEverywhereMl.ranking.core.model
import com.intellij.internal.ml.DecisionFunction
import com.intellij.searchEverywhereMl.SearchEverywhereTabWithMlRanking
internal class SearchEverywhereAllRankingModelLoader : SearchEverywhereMLRankingModelLoader() {
private val expResourceDirectory = "all_features_exp"
private val expModelDirectory = "all_model_exp"
override val supportedTab = SearchEverywhereTabWithMlRanking.ALL
override fun getBundledModel(): DecisionFunction {
return getCatBoostModel(expResourceDirectory, expModelDirectory)
}
}
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 581
|
intellij-community
|
Apache License 2.0
|
08-cross_platform/wrapper/JNI/sdk/src/main/java/com/sdk/sdk/IAlgorithmInterface.kt
|
AlanLi7991
| 226,488,265
| false
| null |
package com.sdk.sdk
interface IAlgorithmInterface {
fun onCallback(number: Int, message: String)
}
| 2
|
CMake
|
3
| 19
|
88d1199cb5367272da49749626806e2aef24e09d
| 103
|
cmake-tutorial-sample
|
MIT License
|
feature-location/src/main/java/de/niklasbednarczyk/nbweather/feature/location/screens/overview/views/LocationOverviewHourlyView.kt
|
NiklasBednarczyk
| 529,683,941
| false
| null |
package de.niklasbednarczyk.nbweather.feature.location.screens.overview.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import de.niklasbednarczyk.nbweather.core.common.string.NBString
import de.niklasbednarczyk.nbweather.core.ui.grid.NBGridRowOneLine
import de.niklasbednarczyk.nbweather.core.ui.stickyheader.NBStickyHeaderListView
import de.niklasbednarczyk.nbweather.core.ui.theme.dimens.listItemPaddingValuesVerticalOneLine
import de.niklasbednarczyk.nbweather.core.ui.windowsize.getWidthSizeClass
import de.niklasbednarczyk.nbweather.feature.location.screens.overview.models.hourly.LocationOverviewHourlyModel
@Composable
fun LocationOverviewHourlyView(
hourlyMap: Map<NBString?, List<LocationOverviewHourlyModel>>,
navigateToHourly: (Long) -> Unit
) {
val widthSizeClass = getWidthSizeClass()
NBStickyHeaderListView(hourlyMap) { hourly ->
val items = when (widthSizeClass) {
WindowWidthSizeClass.Compact -> hourly.itemsCompact
WindowWidthSizeClass.Medium -> hourly.itemsMedium
WindowWidthSizeClass.Expanded -> hourly.itemsExpanded
else -> hourly.itemsCompact
}
NBGridRowOneLine(
modifier = Modifier
.clickable {
navigateToHourly(hourly.forecastTime)
}
.padding(listItemPaddingValuesVerticalOneLine),
items = items
)
}
}
| 22
|
Kotlin
|
0
| 0
|
b9894a6739d699799aa2ab49f3d9218a97cfb7bc
| 1,623
|
NBWeather
|
MIT License
|
android-arch-listview/src/main/kotlin/moe/feng/common/arch/list/BindingListViewAdapter.kt
|
fython
| 115,638,922
| false
| null |
package moe.feng.common.arch.list
import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
open class BindingListViewAdapter(private val variableId: Int)
: BaseAdapter(), IBindingAdapter {
private var _data: MutableList<Any> = mutableListOf()
final override var data: MutableList<Any>
get() = _data
set(value) { _data = value }
private val _binders: MutableList<Pair<Class<*>, BindingItemBinder<*, *>>> = mutableListOf()
final override val binders: MutableList<Pair<Class<*>, BindingItemBinder<*, *>>>
get() = _binders
private fun onCreateView(parent: ViewGroup, position: Int): View {
val binder = getBinderByDataPosition<Any>(position)
?: throw IllegalArgumentException("No binder for position=$position")
val binding = DataBindingUtil.inflate<ViewDataBinding>(
parent.layoutInflater, binder.layoutId, parent, false
).apply { root.tag = BindingHolder(this, binder::onViewHolderCreated) }
return binding.root
}
private fun onBindView(view: View, position: Int) {
val holder = view.tag as BindingHolder<Any, ViewDataBinding>
holder.setAdapterPosition(position)
holder.currentItem = data[position]
holder.binding.setVariable(variableId, data[position])
holder.binding.executePendingBindings()
getBinderByDataPosition<Any>(position)?.onBindViewHolder(holder, data[position], position)
}
final override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: onCreateView(parent, position)
this.onBindView(view, position)
return view
}
final override fun getItem(position: Int): Any = data[position]
final override fun getItemId(position: Int): Long = position.toLong()
final override fun getCount(): Int = data.size
final override fun getViewTypeCount(): Int = binders.size
final override fun getItemViewType(position: Int): Int = getBinderIndexByDataPosition(position)
class BindingHolder<M, out T: ViewDataBinding>(
override val binding: T,
initBlock: BindingListViewAdapter.BindingHolder<M, T>.() -> Unit
): IBindingViewHolder<M, T> {
init { initBlock() }
private var _adapterPosition = -1
override fun getAdapterPosition(): Int = _adapterPosition
internal fun setAdapterPosition(adapterPosition: Int) {
_adapterPosition = adapterPosition
}
private var _currentItem: M? = null
override var currentItem: M?
get() = _currentItem
set(value) { _currentItem = value }
override val context: Context
get() = binding.root.context
}
}
| 0
|
Kotlin
|
1
| 10
|
a7c78c1a5ceea35aab3637ec042eced5a05803e1
| 2,908
|
NyanAndroidArch
|
MIT License
|
common/src/main/java/info/dvkr/screenstream/common/module/StreamingModuleService.kt
|
dkrivoruchko
| 63,582,643
| false
|
{"Kotlin": 727102, "Java": 51723, "HTML": 22517, "JavaScript": 15440}
|
package info.dvkr.screenstream.common.module
import android.Manifest
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.IBinder
import androidx.core.app.ServiceCompat
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.common.isPermissionGranted
import info.dvkr.screenstream.common.notification.NotificationHelper
import org.koin.android.ext.android.inject
public abstract class StreamingModuleService : Service() {
protected abstract val notificationIdForeground: Int
protected abstract val notificationIdError: Int
protected val streamingModuleManager: StreamingModuleManager by inject(mode = LazyThreadSafetyMode.NONE)
protected val notificationHelper: NotificationHelper by inject(mode = LazyThreadSafetyMode.NONE)
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
XLog.d(getLog("onCreate"))
}
override fun onDestroy() {
stopForeground()
hideErrorNotification()
super.onDestroy()
}
@SuppressLint("InlinedApi")
protected fun startForeground(stopIntent: Intent) {
val notification = notificationHelper.createForegroundNotification(this, stopIntent)
val serviceType = when {
isPermissionGranted(Manifest.permission.RECORD_AUDIO) -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST
else -> ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
}
ServiceCompat.startForeground(this, notificationIdForeground, notification, serviceType)
}
public fun stopForeground() {
XLog.d(getLog("stopForeground"))
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
}
protected fun showErrorNotification(message: String, recoverIntent: Intent) {
hideErrorNotification()
if (notificationHelper.notificationPermissionGranted(this).not()) {
XLog.e(getLog("showErrorNotification", "No permission granted. Ignoring."))
return
}
if (notificationHelper.errorNotificationsEnabled().not()) {
XLog.e(getLog("showErrorNotification", "Notifications disabled. Ignoring."))
return
}
val notification = notificationHelper.getErrorNotification(this, message, recoverIntent)
notificationHelper.showNotification(notificationIdError, notification)
}
public fun hideErrorNotification() {
XLog.d(getLog("hideErrorNotification"))
notificationHelper.cancelNotification(notificationIdError)
}
}
| 21
|
Kotlin
|
311
| 1,509
|
10e6fae4e253628e0e022726d591bbce301317bb
| 2,694
|
ScreenStream
|
MIT License
|
app/src/main/java/com/example/bagstore/Model/Data/SubmitOrder.kt
|
pixel-Alireza
| 634,630,481
| false
| null |
package com.example.onlineshop.model.data
data class SubmitOrder(
val success: Boolean ,
val orderId: Int,
val paymentLink :String
)
| 0
| null |
0
| 4
|
08e55ac89f51448ec8a654de3b393b9fb8d79add
| 145
|
Bag-Store
|
MIT License
|
plugin-build/tailwind-kt/src/main/kotlin/kizzy/tailwind/templates/PostCssTemplate.kt
|
dead8309
| 661,807,290
| false
| null |
package kizzy.tailwind.templates
internal fun postCssConfigTemplate() = """
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}
""".trimIndent()
| 1
| null |
0
| 6
|
b33488d0ce40cf11760b379863f57a026536a0aa
| 199
|
tailwind-kt
|
MIT License
|
ktor/src/main/kotlin/dev/evo/prometheus/ktor/ktor.kt
|
anti-social
| 191,977,120
| false
| null |
package dev.evo.prometheus.ktor
import dev.evo.prometheus.GaugeLong
import dev.evo.prometheus.Histogram
import dev.evo.prometheus.LabelSet
import dev.evo.prometheus.PrometheusMetrics
import dev.evo.prometheus.hiccup.HiccupMetrics
import dev.evo.prometheus.jvm.DefaultJvmMetrics
import dev.evo.prometheus.writeSamples
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationCall
import io.ktor.server.application.ApplicationCallPipeline
import io.ktor.server.application.BaseApplicationPlugin
import io.ktor.server.application.call
import io.ktor.server.application.install
import io.ktor.server.request.httpMethod
import io.ktor.server.request.path
import io.ktor.server.routing.get
import io.ktor.server.routing.Route
import io.ktor.server.routing.routing
import io.ktor.server.response.respondTextWriter
import io.ktor.server.routing.PathSegmentConstantRouteSelector
import io.ktor.server.routing.PathSegmentOptionalParameterRouteSelector
import io.ktor.server.routing.PathSegmentParameterRouteSelector
import io.ktor.server.routing.PathSegmentTailcardRouteSelector
import io.ktor.server.routing.PathSegmentWildcardRouteSelector
import io.ktor.server.routing.Routing
import io.ktor.util.AttributeKey
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.system.measureNanoTime
import kotlin.time.TimeSource
import kotlinx.coroutines.CoroutineScope
// TODO: Possibly it is worth to wrap hiccups settings into a config class
fun Application.metricsModule(
startHiccups: Boolean = true,
hiccupsCoroutineScope: CoroutineScope? = null,
hiccupsCoroutineContext: CoroutineContext = EmptyCoroutineContext,
hiccupsTimeSource: TimeSource = TimeSource.Monotonic,
) {
val feature = MetricsFeature()
if (startHiccups) {
feature.metrics.hiccups.startTracking(
hiccupsCoroutineScope ?: this@metricsModule,
coroutineContext = hiccupsCoroutineContext,
timeSource = hiccupsTimeSource,
)
}
metricsModule(feature)
}
fun Application.metricsModule(metrics: PrometheusMetrics) {
metricsModule(MetricsFeature(metrics))
}
fun <TMetrics: HttpMetrics> Application.metricsModule(
metricsFeature: MetricsFeature<TMetrics>
) {
install(metricsFeature)
routing {
metrics(metricsFeature.metrics.metrics)
}
}
fun Route.metrics(metrics: PrometheusMetrics) {
get("/metrics") {
metrics.collect()
call.respondTextWriter {
writeSamples(metrics.dump(), this)
}
}
}
open class MetricsFeature<TMetrics: HttpMetrics>(val metrics: TMetrics):
BaseApplicationPlugin<Application, MetricsFeature.Configuration, Unit>
{
override val key = AttributeKey<Unit>("Response metrics collector")
private val routeKey = AttributeKey<Route>("Route info")
companion object {
operator fun invoke(): MetricsFeature<DefaultMetrics> {
return MetricsFeature(DefaultMetrics())
}
operator fun invoke(prometheusMetrics: PrometheusMetrics): MetricsFeature<DummyMetrics> {
return MetricsFeature(DummyMetrics(prometheusMetrics))
}
}
class Configuration {
var totalRequests: Histogram<HttpRequestLabels>? = null
var inFlightRequests: GaugeLong<HttpRequestLabels>? = null
var enablePathLabel = false
}
open fun defaultConfiguration(): Configuration {
return Configuration().apply {
totalRequests = metrics.totalRequests
inFlightRequests = metrics.inFlightRequests
}
}
override fun install(pipeline: Application, configure: Configuration.() -> Unit) {
val configuration = defaultConfiguration().apply(configure)
pipeline.environment.monitor.subscribe(Routing.RoutingCallStarted) { call ->
call.attributes.put(routeKey, call.route)
}
pipeline.intercept(ApplicationCallPipeline.Monitoring) {
val requestTimeMs = measureNanoTime {
configuration.inFlightRequests?.incAndDec({
fromCall(call, configuration.enablePathLabel)
}) {
proceed()
} ?: proceed()
}.toDouble() / 1_000_000.0
configuration.totalRequests?.observe(requestTimeMs) {
fromCall(call, configuration.enablePathLabel)
}
}
}
private fun HttpRequestLabels.fromCall(call: ApplicationCall, enablePathLabel: Boolean) {
method = call.request.httpMethod
statusCode = call.response.status()
route = call.attributes.getOrNull(routeKey)
if (enablePathLabel) {
path = call.request.path()
}
}
}
interface HttpMetrics {
val totalRequests: Histogram<HttpRequestLabels>?
get() = null
val inFlightRequests: GaugeLong<HttpRequestLabels>?
get() = null
val metrics: PrometheusMetrics
}
class DefaultMetrics : PrometheusMetrics(), HttpMetrics {
val jvm by submetrics(DefaultJvmMetrics())
val hiccups by submetrics(HiccupMetrics())
val http by submetrics(StandardHttpMetrics())
override val totalRequests: Histogram<HttpRequestLabels>?
get() = http.totalRequests
override val inFlightRequests: GaugeLong<HttpRequestLabels>?
get() = http.inFlightRequests
override val metrics: PrometheusMetrics
get() = this
}
class DummyMetrics(private val prometheusMetrics: PrometheusMetrics) : HttpMetrics {
override val metrics: PrometheusMetrics
get() = prometheusMetrics
}
class StandardHttpMetrics : PrometheusMetrics() {
private val prefix = "http"
val totalRequests by histogram(
"${prefix}_total_requests", logScale(0, 3)
) { HttpRequestLabels() }
val inFlightRequests by gaugeLong("${prefix}_in_flight_requests") {
HttpRequestLabels()
}
}
class HttpRequestLabels : LabelSet() {
var method: HttpMethod? by label { value }
var statusCode: HttpStatusCode? by label("response_code") { value.toString() }
var route: Route? by label {
toLabelString()
}
var path by label()
fun Route.toLabelString(): String {
val segment = when (selector) {
is PathSegmentConstantRouteSelector -> selector
is PathSegmentParameterRouteSelector -> selector
is PathSegmentOptionalParameterRouteSelector -> selector
is PathSegmentTailcardRouteSelector -> selector
is PathSegmentWildcardRouteSelector -> selector
else -> null
}
val parent = parent
return when {
segment == null -> parent?.toLabelString() ?: "/"
parent == null -> "/$segment"
else -> {
val parentSegment = parent.toLabelString()
when {
parentSegment.isEmpty() -> segment.toString()
parentSegment.endsWith('/') -> "$parentSegment$segment"
else -> "$parentSegment/$segment"
}
}
}
}
}
| 5
|
Kotlin
|
2
| 7
|
1ecbe7272270dec44266df08667946cf39d17b67
| 7,175
|
prometheus-kt
|
Apache License 2.0
|
korio/src/androidMain/kotlin/com/soywiz/korio/lang/EnvironmentJvm.kt
|
korlibs
| 77,343,418
| false
| null |
package korlibs.io.lang
internal actual object EnvironmentInternal {
// Uses querystring on JS/Browser, and proper env vars in the rest
actual operator fun get(key: String): String? = System.getenv(key)
actual fun getAll(): Map<String, String> = System.getenv()
}
| 444
| null |
33
| 349
|
e9e89804f5682db0a70e58b91f469b49698dd72b
| 268
|
korio
|
MIT License
|
src/main/kotlin/examples/shm/simpleHarmonicMotion.kt
|
CuriousNikhil
| 415,380,983
| false
| null |
package examples.shm
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.translate
import k5
import math.TWO_PI
import math.map
import kotlin.math.sin
fun simulateSineWave() = k5 {
val angles = mutableListOf<Float>()
val r = 6
val total = dimensInt.width / (r * 2)
repeat(total) {
angles.add(map(it.toFloat(), 0f, total.toFloat(), 0f, 2 * TWO_PI.toFloat()))
}
show { drawScope ->
drawScope.translate(500f, 500f) {
for (i in 0 until angles.size) {
val y = map(sin(angles[i]), -1f, 1f, -400f, 400f)
val x = map(i.toFloat(), 0f, angles.size.toFloat(), -400f, 400f)
this.drawCircle(Color.Yellow, r.toFloat(), Offset(x, y))
angles[i] += 0.02f
}
}
}
}
| 1
| null |
6
| 99
|
106deec4165a44c3590c6c9ea335b97d29e54cf5
| 870
|
k5-compose
|
Apache License 2.0
|
src/main/kotlin/com/odim/simulator/tree/templates/redfish/embedded/SensorThresholdsTemplate.kt
|
ODIM-Project
| 355,910,204
| false
| null |
// Copyright (c) Intel Corporation
//
// 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.odim.simulator.tree.templates.redfish.embedded
import com.odim.simulator.tree.EmbeddedObjectTemplate
import com.odim.simulator.tree.RedfishVersion.V1_0_0
import com.odim.simulator.tree.ResourceTemplate
import com.odim.simulator.tree.structure.EmbeddedObjectType.SENSOR_THRESHOLD
import com.odim.simulator.tree.structure.EmbeddedObjectType.SENSOR_THRESHOLDS
import com.odim.simulator.tree.structure.Resource.Companion.embeddedObject
/**
* This is generated class. Please don't edit it's contents.
*/
@EmbeddedObjectTemplate(SENSOR_THRESHOLDS)
open class SensorThresholdsTemplate : ResourceTemplate() {
init {
version(V1_0_0, embeddedObject(
"UpperCaution" to embeddedObject(SENSOR_THRESHOLD),
"UpperCritical" to embeddedObject(SENSOR_THRESHOLD),
"UpperFatal" to embeddedObject(SENSOR_THRESHOLD),
"LowerCaution" to embeddedObject(SENSOR_THRESHOLD),
"LowerCritical" to embeddedObject(SENSOR_THRESHOLD),
"LowerFatal" to embeddedObject(SENSOR_THRESHOLD)
))
}
}
| 1
|
Kotlin
|
0
| 7
|
7e8a3030ca83c040678f8edf76def588b2b01cca
| 1,685
|
BMCSimulator
|
Apache License 2.0
|
loader/src/test/java/com/rarible/core/loader/LoadStressIt.kt
|
rarible
| 357,923,214
| false
| null |
package com.rarible.core.loader
import com.rarible.core.loader.test.testLoaderType
import com.rarible.core.loader.test.testReceivedNotifications
import com.rarible.core.test.wait.Wait
import io.mockk.coEvery
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import java.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@Disabled
class LoadStressIt : AbstractIntegrationTest() {
@Autowired
lateinit var loadService: LoadService
@ExperimentalTime
@Test
fun `stress test loading`() = runBlocking<Unit> {
println(clock.instant())
coEvery { loader.load(any()) } coAnswers {
val key = firstArg<String>()
val id = key.substringBefore(":").toLong()
val delay = key.substringAfter(":").toLong()
delay(delay)
println("Finished task $id after $delay")
}
val numberOfTasks = 1000
val loadTasks = (0 until numberOfTasks).map { key ->
val delay = key * 2
testLoaderType to "$delay:$delay"
}
val totalDelay = (0 until numberOfTasks).sumOf { it * 2 }
println("Total tasks delay: $totalDelay")
println("Number of workers: ${loadProperties.workers}")
println("Number of task topic partitions: ${loadProperties.loadTasksTopicPartitions}")
loadTasks.forEach { loadService.scheduleLoad(it.first, it.second) }
val totalTime = measureTime {
Wait.waitAssert(timeout = Duration.ofMinutes(1)) {
assertThat(testReceivedNotifications.filter { it.status is LoadTaskStatus.Scheduled }).hasSize(numberOfTasks)
assertThat(testReceivedNotifications.filter { it.status is LoadTaskStatus.Loaded }).hasSize(numberOfTasks)
}
}
println("Total execution time: $totalTime")
val speedupFactor = totalDelay.toDouble() / totalTime.inWholeMilliseconds.toDouble()
println("Speedup factor for ${loadProperties.workers} workers " + String.format("%.2f", speedupFactor))
}
}
| 0
|
Kotlin
|
3
| 9
|
2b2c746150f0fe83bcc0789401345810353e5b1c
| 2,259
|
service-core
|
MIT License
|
affogato-structure/src/main/java/com/parsuomash/affogato/structure/validation/Validation.kt
|
ghasemdev
| 510,960,043
| false
| null |
package com.parsuomash.affogato.structure.validation
/**
* ## Validation
* Check is value valid.
* @since 1.4.0
*/
fun interface Validation {
fun isValid(): Boolean
}
| 0
|
Kotlin
|
1
| 9
|
f1944a97416221855060a954b539fbd87b74033b
| 174
|
affogato
|
MIT License
|
client/app/src/main/java/com/rh/heji/data/db/Image.kt
|
RUANHAOANDROID
| 324,589,079
| false
| null |
package com.rh.heji.data.db
import androidx.room.*
import com.blankj.utilcode.util.GsonUtils
import com.rh.heji.data.db.mongo.ObjectId
import java.util.*
/**
* @date: 2020/11/19
* @author: 锅得铁
* primaryKeys image_id
* ForeignKey bill_id -> image.bill_id
*/
@Entity(
tableName = Image.TAB_NAME,
primaryKeys = [Image.COLUMN_ID],
foreignKeys = [ForeignKey(
entity = Bill::class,
parentColumns = [Bill.COLUMN_ID],
childColumns = [Image.COLUMN_BILL_ID],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.NO_ACTION
)], indices = [Index(value = [Image.COLUMN_ID, Image.COLUMN_BILL_ID], unique = true)]
)
data class Image(
@ColumnInfo(name = COLUMN_ID)
var id: String = ObjectId().toHexString(),
@ColumnInfo(name = Bill.COLUMN_ID, index = true)
var billID: String
) {
var md5: String? = null
var ext: String? = null
@ColumnInfo(name = COLUMN_PATH)
var localPath: String? = null
@ColumnInfo(name = COLUMN_ONLINE_PATH)
var onlinePath: String? = null
@ColumnInfo(name = COLUMN_STATUS, defaultValue = "0")
var syncStatus = 0
override fun hashCode(): Int {
return Objects.hash(id, billID, localPath, onlinePath)
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val image = o as Image
return id === image.id && billID == image.billID &&
localPath == image.localPath &&
onlinePath == image.onlinePath
}
companion object {
const val COLUMN_ID = "image_id"
const val COLUMN_BILL_ID = Bill.COLUMN_ID
const val TAB_NAME = "image"
const val COLUMN_PATH = "local_path"
const val COLUMN_ONLINE_PATH = "online_path"
const val COLUMN_STATUS = "sync_status"
}
override fun toString(): String {
return GsonUtils.toJson(this)
}
}
| 0
| null |
7
| 7
|
38d7d743b34ac09e08682f00e0442dd6d1e16b49
| 1,962
|
heji
|
Apache License 2.0
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/DoDisturbAltSharp.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 2961484, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/DoDisturbAltSharp")
package mui.icons.material
@JsName("default")
external val DoDisturbAltSharp: SvgIconComponent
| 0
|
Kotlin
|
5
| 35
|
d12f6b1ad1b215ad7d3d9f27e24d48ada9b7fe2d
| 198
|
mui-kotlin
|
Apache License 2.0
|
app/src/main/java/org/fossasia/susi/ai/skills/skilllisting/adapters/recycleradapters/SkillListAdapter.kt
|
sachgits
| 143,452,275
| true
|
{"Kotlin": 325028, "Java": 212866, "Shell": 2946}
|
package org.fossasia.susi.ai.skills.skilllisting.adapters.recycleradapters
import android.content.Context
import android.support.annotation.NonNull
import android.support.v4.graphics.drawable.RoundedBitmapDrawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import com.squareup.picasso.Transformation
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.helper.CircleTransform
import org.fossasia.susi.ai.rest.responses.susi.SkillData
import org.fossasia.susi.ai.skills.SkillFragmentCallback
import org.fossasia.susi.ai.skills.skilllisting.adapters.viewholders.SkillViewHolder
/**
*
* Created by chiragw15 on 15/8/17.
*/
class SkillListAdapter(val context: Context, private val skillDetails: List<SkillData>?, val skillCallback: SkillFragmentCallback) : RecyclerView.Adapter<SkillViewHolder>(),
SkillViewHolder.ClickListener {
private val imageLink = "https://raw.githubusercontent.com/fossasia/susi_skill_data/master/models/general/"
private val clickListener: SkillViewHolder.ClickListener = this
@NonNull
override fun onBindViewHolder(holder: SkillViewHolder, position: Int) {
if (skillDetails != null) {
val skillData = skillDetails.toTypedArray()[position]
if (skillData.skillName == null || skillData.skillName.isEmpty()) {
holder.skillPreviewTitle?.text = context.getString(R.string.no_skill_name)
} else {
holder.skillPreviewTitle?.text = skillData.skillName
}
if (skillData.examples == null || skillData.examples.isEmpty())
holder.skillPreviewExample?.text = StringBuilder("\"").append("\"")
else
holder.skillPreviewExample?.text = StringBuilder("\"").append(skillData.examples[0]).append("\"")
if (skillData.image == null || skillData.image.isEmpty()) {
holder.previewImageView?.setImageResource(R.drawable.ic_susi)
} else {
Picasso.with(context.applicationContext).load(StringBuilder(imageLink)
.append(skillDetails[position].group.replace(" ", "%20")).append("/en/").append(skillData.image).toString())
.fit().centerCrop()
.error(R.drawable.ic_susi)
.transform(CircleTransform())
.into(holder.previewImageView)
}
if (skillData.skillRating != null) {
if (skillData.skillRating?.stars != null) {
holder.skillRatingBar.rating = skillData.skillRating?.stars?.averageStar as Float
holder.totalRatings.text = skillData.skillRating?.stars?.totalStar.toString()
}
}
}
}
override fun getItemCount(): Int {
return (skillDetails as List<SkillData>).size
}
override fun onItemClicked(position: Int) {
var skillTag: String? = ""
if ((skillDetails as List<SkillData>)[position].skillTag != null) {
skillTag = skillDetails.toTypedArray()[position].skillTag
} else {
skillTag = ""
}
val skillData = skillDetails[position]
val skillGroup = skillDetails[position].group.replace(" ", "%20")
showSkillDetailFragment(skillData, skillGroup, skillTag)
}
private fun showSkillDetailFragment(skillData: SkillData, skillGroup: String, skillTag: String) {
skillCallback.loadDetailFragment(skillData, skillGroup, skillTag)
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SkillViewHolder {
val itemView = LayoutInflater.from(parent?.context)
.inflate(R.layout.item_skill, parent, false)
return SkillViewHolder(itemView, clickListener)
}
}
| 0
|
Kotlin
|
0
| 0
|
aa09e6d5bf40cc10dc011c16051ced83fb772273
| 3,902
|
susi_android
|
Apache License 2.0
|
src/test/kotlin/no/ssb/barn/xsd/UndersokelseKonklusjonTypeTest.kt
|
statisticsnorway
| 360,498,313
| false
| null |
package no.ssb.barn.xsd
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.data.forAll
import io.kotest.data.row
import io.kotest.matchers.shouldBe
import no.ssb.barn.TestUtils.CLARIFICATION_MAX_LEN
import no.ssb.barn.TestUtils.EMPTY_DATE_ERROR
import no.ssb.barn.TestUtils.INVALID_CLARIFICATION_ERROR
import no.ssb.barn.TestUtils.INVALID_DATE_ERROR
import no.ssb.barn.TestUtils.buildBarnevernXml
import no.ssb.barn.toStreamSource
import no.ssb.barn.util.ValidationUtils.getSchemaValidator
import org.xml.sax.SAXException
class UndersokelseKonklusjonTypeTest : BehaviorSpec({
Given("misc UndersokelseKonklusjon XML") {
/** make sure it's possible to make a valid test XML */
When("valid XML, expect no exceptions") {
shouldNotThrowAny {
getSchemaValidator().validate(
buildUndersokelseXml(
"<Konklusjon SluttDato=\"2022-11-14\" Kode=\"1\" " +
"Presisering=\"~Presisering~\" />"
).toStreamSource()
)
}
}
forAll(
/** SluttDato */
row(
"missing SluttDato",
"<Konklusjon Kode=\"1\" />",
"cvc-complex-type.4: Attribute 'SluttDato' must appear on element 'Konklusjon'."
),
row(
"empty SluttDato",
"<Konklusjon SluttDato=\"\" Kode=\"1\" />",
EMPTY_DATE_ERROR
),
row(
"invalid SluttDato",
"<Konklusjon SluttDato=\"2022\" Kode=\"1\" />",
INVALID_DATE_ERROR
),
/** Kode */
row(
"missing Kode",
"<Konklusjon SluttDato=\"2022-11-14\" />",
"cvc-complex-type.4: Attribute 'Kode' must appear on element 'Konklusjon'."
),
row(
"empty Kode",
"<Konklusjon SluttDato=\"2022-11-14\" Kode=\"\" />",
"cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to " +
"minLength '1' for type '#AnonType_KodeKonklusjonUndersokelseType'."
),
row(
"invalid Kode",
"<Konklusjon SluttDato=\"2022-11-14\" Kode=\"42\" />",
"cvc-maxLength-valid: Value '42' with length = '2' is not facet-valid with respect to " +
"maxLength '1' for type '#AnonType_KodeKonklusjonUndersokelseType'."
),
/** Presisering */
row(
"empty Presisering",
"<Konklusjon SluttDato=\"2022-11-14\" Kode=\"1\" Presisering=\"\" />",
"cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to " +
"minLength '1' for type '#AnonType_Presisering'."
),
row(
"too long Presisering",
"<Konklusjon SluttDato=\"2022-11-14\" Kode=\"1\" Presisering=\"${"a".repeat(CLARIFICATION_MAX_LEN + 1)}\" />",
INVALID_CLARIFICATION_ERROR
)
) { description, partialXml, expectedError ->
When(description) {
val thrown = shouldThrow<SAXException> {
getSchemaValidator().validate(buildUndersokelseXml(partialXml).toStreamSource())
}
Then("thrown should be as expected") {
thrown.message shouldBe expectedError
}
}
}
}
}) {
companion object {
private fun buildUndersokelseXml(undersokelseKonklusjonXml: String): String = buildBarnevernXml(
"<Undersokelse Id=\"6ee9bf92-7a4e-46ef-a2dd-b5a3a0a9ee2e\" StartDato=\"2022-11-14\">" +
undersokelseKonklusjonXml +
"</Undersokelse>"
)
}
}
| 2
| null |
1
| 6
|
850d8aea3c7c2458f162394ca986933a07fd1644
| 4,063
|
barn-barnevern-xsd
|
MIT License
|
app/src/main/java/com/example/david/diyrules/activities/AutoMateActivity.kt
|
DavidRoebl
| 217,783,211
| false
| null |
package com.example.david.diyrules.activities
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v7.app.AppCompatActivity
import com.example.david.diyrules.mediator.PermissionMediator
/**
* base activity for handling permissions
*/
abstract class AutoMateActivity: AppCompatActivity() {
override fun onResume() {
super.onResume()
PermissionMediator.currentActivity = this
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
PermissionMediator.permissionResult(requestCode, permissions, grantResults)
}
}
| 0
|
Kotlin
|
0
| 0
|
f363f6a9a53b7c38f6b7717c7f9fb7b6dc8566fd
| 649
|
DIYRules
|
MIT License
|
features/home/home-impl/src/commonMain/kotlin/io/spherelabs/homeimpl/domain/DefaultGetPasswordByCategoryUseCase.kt
|
getspherelabs
| 687,455,894
| false
|
{"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048}
|
package io.spherelabs.homeimpl.domain
import io.spherelabs.homeapi.domain.usecase.GetPasswordsByCategoryUseCase
import io.spherelabs.homeapi.models.HomePassword
import io.spherelabs.homeapi.repository.HomeRepository
import kotlinx.coroutines.flow.Flow
class DefaultGetPasswordByCategoryUseCase(private val homeRepository: HomeRepository) :
GetPasswordsByCategoryUseCase {
override fun execute(categoryId: String): Flow<List<HomePassword>> {
if (categoryId.isEmpty()) throw Exception("Invalid a category id.")
return homeRepository.getPasswordsByCategory(categoryId)
}
}
| 18
|
Kotlin
|
27
| 236
|
902a0505c5eaf0f3848a5e06afaec98c1ed35584
| 600
|
anypass-kmp
|
Apache License 2.0
|
samples/notes-app/src/main/java/com/nhaarman/acorn/notesapp/presentation/edititem/EditItemScene.kt
|
nhaarman
| 137,459,947
| false
| null |
/*
* Copyright 2018 Niek Haarman
*
* 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.nhaarman.acorn.notesapp.presentation.edititem
import com.nhaarman.acorn.notesapp.mainThread
import com.nhaarman.acorn.notesapp.note.NoteItemsRepository
import com.nhaarman.acorn.orNull
import com.nhaarman.acorn.presentation.RxScene
import com.nhaarman.acorn.presentation.SavableScene
import com.nhaarman.acorn.presentation.SceneKey.Companion.defaultKey
import com.nhaarman.acorn.state.SceneState
import com.nhaarman.acorn.state.get
import io.reactivex.rxkotlin.plusAssign
class EditItemScene(
private val itemId: Long,
private val noteItemsRepository: NoteItemsRepository,
private val listener: Events,
savedState: SceneState? = null,
) : RxScene<EditItemContainer>(savedState),
SavableScene {
private val originalItem by lazy {
noteItemsRepository.find(itemId)
.observeOn(mainThread)
.replay(1).autoConnect(this)
}
private val saveClicks = view.whenAvailable { it.saveClicks }
private val deleteClicks = view.whenAvailable { it.deleteClicks }
override fun onStart() {
super.onStart()
disposables += originalItem
.combineWithLatestView()
.firstElement()
.subscribe { (item, view) ->
view?.initialText = item.orNull()?.text
}
disposables += saveClicks
.flatMapSingle { text -> noteItemsRepository.update(itemId, text) }
.observeOn(mainThread)
.subscribe { _ -> listener.saved() }
disposables += deleteClicks
.firstElement()
.subscribe {
noteItemsRepository.delete(itemId)
listener.deleted()
}
}
override fun saveInstanceState(): SceneState {
return super.saveInstanceState()
.also { it["item_id"] = itemId }
}
override fun toString(): String {
return "EditItemScene(itemId=$itemId)@${Integer.toHexString(hashCode())}"
}
interface Events {
fun saved()
fun deleted()
}
companion object {
val key = defaultKey<EditItemScene>()
fun create(
noteItemsRepository: NoteItemsRepository,
listener: Events,
state: SceneState,
): EditItemScene {
return EditItemScene(
state["item_id"]!!,
noteItemsRepository,
listener,
state,
)
}
}
}
| 17
|
Kotlin
|
7
| 182
|
bb4cd33a54103bb1a1cf4c0eecabfcc7b9c352d2
| 3,083
|
acorn
|
Apache License 2.0
|
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/brands/CreativeCommonsSampling.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.fontawesomeicons.brands
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.fontawesomeicons.BrandsGroup
public val BrandsGroup.CreativeCommonsSampling: ImageVector
get() {
if (_creativeCommonsSampling != null) {
return _creativeCommonsSampling!!
}
_creativeCommonsSampling = Builder(name = "CreativeCommonsSampling", defaultWidth =
496.0.dp, defaultHeight = 512.0.dp, viewportWidth = 496.0f, viewportHeight =
512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(247.6f, 8.0f)
curveTo(389.4f, 8.0f, 496.0f, 118.1f, 496.0f, 256.0f)
curveToRelative(0.0f, 147.1f, -118.5f, 248.0f, -248.4f, 248.0f)
curveTo(113.6f, 504.0f, 0.0f, 394.5f, 0.0f, 256.0f)
curveTo(0.0f, 123.1f, 104.7f, 8.0f, 247.6f, 8.0f)
close()
moveTo(248.4f, 52.7f)
curveTo(130.2f, 52.7f, 44.7f, 150.6f, 44.7f, 256.0f)
curveToRelative(0.0f, 109.8f, 91.2f, 202.8f, 203.7f, 202.8f)
curveToRelative(103.2f, 0.0f, 202.8f, -81.1f, 202.8f, -202.8f)
curveToRelative(0.1f, -113.8f, -90.2f, -203.3f, -202.8f, -203.3f)
close()
moveTo(252.0f, 105.9f)
curveToRelative(2.8f, -0.3f, 11.5f, 1.0f, 11.5f, 11.5f)
lineToRelative(6.6f, 107.2f)
lineToRelative(4.9f, -59.3f)
curveToRelative(0.0f, -6.0f, 4.7f, -10.6f, 10.6f, -10.6f)
curveToRelative(5.9f, 0.0f, 10.6f, 4.7f, 10.6f, 10.6f)
curveToRelative(0.0f, 2.5f, -0.5f, -5.7f, 5.7f, 81.5f)
lineToRelative(5.8f, -64.2f)
curveToRelative(0.3f, -2.9f, 2.9f, -9.3f, 10.2f, -9.3f)
curveToRelative(3.8f, 0.0f, 9.9f, 2.3f, 10.6f, 8.9f)
lineToRelative(11.5f, 96.5f)
lineToRelative(5.3f, -12.8f)
curveToRelative(1.8f, -4.4f, 5.2f, -6.6f, 10.2f, -6.6f)
horizontalLineToRelative(58.0f)
verticalLineToRelative(21.3f)
horizontalLineToRelative(-50.9f)
lineToRelative(-18.2f, 44.3f)
curveToRelative(-3.9f, 9.9f, -19.5f, 9.1f, -20.8f, -3.1f)
lineToRelative(-4.0f, -31.9f)
lineToRelative(-7.5f, 92.6f)
curveToRelative(-0.3f, 3.0f, -3.0f, 9.3f, -10.2f, 9.3f)
curveToRelative(-3.0f, 0.0f, -9.8f, -2.1f, -10.6f, -9.3f)
curveToRelative(0.0f, -1.9f, 0.6f, 5.8f, -6.2f, -77.9f)
lineToRelative(-5.3f, 72.2f)
curveToRelative(-1.1f, 4.8f, -4.8f, 9.3f, -10.6f, 9.3f)
curveToRelative(-2.9f, 0.0f, -9.8f, -2.0f, -10.6f, -9.3f)
curveToRelative(0.0f, -1.9f, 0.5f, 6.7f, -5.8f, -87.7f)
lineToRelative(-5.8f, 94.8f)
curveToRelative(0.0f, 6.3f, -3.6f, 12.4f, -10.6f, 12.4f)
curveToRelative(-5.2f, 0.0f, -10.6f, -4.1f, -10.6f, -12.0f)
lineToRelative(-5.8f, -87.7f)
curveToRelative(-5.8f, 92.5f, -5.3f, 84.0f, -5.3f, 85.9f)
curveToRelative(-1.1f, 4.8f, -4.8f, 9.3f, -10.6f, 9.3f)
curveToRelative(-3.0f, 0.0f, -9.8f, -2.1f, -10.6f, -9.3f)
curveToRelative(0.0f, -0.7f, -0.4f, -1.1f, -0.4f, -2.6f)
lineToRelative(-6.2f, -88.6f)
lineTo(182.0f, 348.0f)
curveToRelative(-0.7f, 6.5f, -6.7f, 9.3f, -10.6f, 9.3f)
curveToRelative(-5.8f, 0.0f, -9.6f, -4.1f, -10.6f, -8.9f)
lineTo(149.7f, 272.0f)
curveToRelative(-2.0f, 4.0f, -3.5f, 8.4f, -11.1f, 8.4f)
lineTo(87.2f, 280.4f)
verticalLineToRelative(-21.3f)
lineTo(132.0f, 259.1f)
lineToRelative(13.7f, -27.9f)
curveToRelative(4.4f, -9.9f, 18.2f, -7.2f, 19.9f, 2.7f)
lineToRelative(3.1f, 20.4f)
lineToRelative(8.4f, -97.9f)
curveToRelative(0.0f, -6.0f, 4.8f, -10.6f, 10.6f, -10.6f)
curveToRelative(0.5f, 0.0f, 10.6f, -0.2f, 10.6f, 12.4f)
lineToRelative(4.9f, 69.1f)
lineToRelative(6.6f, -92.6f)
curveToRelative(0.0f, -10.1f, 9.5f, -10.6f, 10.2f, -10.6f)
curveToRelative(0.6f, 0.0f, 10.6f, 0.7f, 10.6f, 10.6f)
lineToRelative(5.3f, 80.6f)
lineToRelative(6.2f, -97.9f)
curveToRelative(0.1f, -1.1f, -0.6f, -10.3f, 9.9f, -11.5f)
close()
}
}
.build()
return _creativeCommonsSampling!!
}
private var _creativeCommonsSampling: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 5,408
|
compose-icons
|
MIT License
|
app/src/main/kotlin/batect/execution/RunOptions.kt
|
uBuFun
| 190,537,998
| true
|
{"Gradle": 18, "INI": 2, "Markdown": 21, "Shell": 22, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "YAML": 36, "Kotlin": 370, "Dockerfile": 22, "HTML": 5, "Groovy": 4, "Python": 2, "Java": 1, "JSON": 2, "JavaScript": 8}
|
/*
Copyright 2017-2019 Charles Korn.
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 batect.execution
import batect.cli.CommandLineOptions
data class RunOptions(
val taskName: String,
val additionalTaskCommandArguments: Iterable<String>,
val levelOfParallelism: Int,
val behaviourAfterFailure: BehaviourAfterFailure,
val propagateProxyEnvironmentVariables: Boolean
) {
constructor(options: CommandLineOptions) : this(
options.taskName!!,
options.additionalTaskCommandArguments,
options.levelOfParallelism,
if (options.disableCleanupAfterFailure) {
BehaviourAfterFailure.DontCleanup
} else {
BehaviourAfterFailure.Cleanup
},
!options.dontPropagateProxyEnvironmentVariables
)
}
| 1
|
Kotlin
|
1
| 1
|
b02013e2b0ab3e9ba3298f160c69971543bda985
| 1,305
|
batect
|
Apache License 2.0
|
backend/data/src/main/kotlin/io/tolgee/security/OrganizationHolder.kt
|
tolgee
| 303,766,501
| false
|
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
|
package io.tolgee.security
import io.tolgee.dtos.cacheable.OrganizationDto
import io.tolgee.model.Organization
import io.tolgee.service.organization.OrganizationService
open class OrganizationHolder(
private val organizationService: OrganizationService,
) {
open val organizationEntity: Organization by lazy {
organizationService.get(organization.id)
}
private var _organization: OrganizationDto? = null
open var organization: OrganizationDto
set(value) {
_organization = value
}
get() {
return _organization ?: throw OrganizationNotSelectedException()
}
val organizationOrNull: OrganizationDto?
get() = _organization
}
| 170
|
TypeScript
|
188
| 1,837
|
6e01eec3a19c151a6e0aca49e187e2d0deef3082
| 672
|
tolgee-platform
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppscontactsapi/resource/sync/PrisonerContactSyncController.kt
|
ministryofjustice
| 835,306,273
| false
|
{"Kotlin": 563533, "Shell": 2365, "Dockerfile": 1483}
|
package uk.gov.justice.digital.hmpps.hmppscontactsapi.resource
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.media.Content
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.validation.Valid
import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.hmppscontactsapi.model.request.sync.CreatePrisonerContactRequest
import uk.gov.justice.digital.hmpps.hmppscontactsapi.model.request.sync.UpdatePrisonerContactRequest
import uk.gov.justice.digital.hmpps.hmppscontactsapi.model.response.sync.PrisonerContact
import uk.gov.justice.digital.hmpps.hmppscontactsapi.service.SyncPrisonerContactService
import uk.gov.justice.digital.hmpps.hmppscontactsapi.swagger.AuthApiResponses
import uk.gov.justice.hmpps.kotlin.common.ErrorResponse
@Tag(name = "Sync endpoints")
@RestController
@RequestMapping(value = ["/sync"], produces = [MediaType.APPLICATION_JSON_VALUE])
@AuthApiResponses
class PrisonerContactSyncController(
val syncService: SyncPrisonerContactService,
) {
@GetMapping(path = ["/prisoner-contact/{prisonerContactId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Operation(
summary = "Returns the data for a prisoner contact by prisonerContactId",
description = """
Requires role: ROLE_CONTACTS_MIGRATION.
Used to get the details for one prisoner contact.
""",
)
@ApiResponses(
value = [
ApiResponse(
responseCode = "200",
description = "Found the prisoner contact",
content = [
Content(
mediaType = "application/json",
schema = Schema(implementation = PrisonerContact::class),
),
],
),
ApiResponse(
responseCode = "404",
description = "No prisoner contact reference with that id could be found",
),
],
)
@PreAuthorize("hasAnyRole('CONTACTS_MIGRATION')")
fun getPrisonerContactById(
@Parameter(description = "The internal ID for a prisoner contact.", required = true)
@PathVariable prisonerContactId: Long,
) = syncService.getPrisonerContactById(prisonerContactId)
@DeleteMapping(path = ["/prisoner-contact/{prisonerContactId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@Operation(
summary = "Deletes one prisoner contact by internal ID",
description = """
Requires role: ROLE_CONTACTS_MIGRATION.
Used to delete a prisoner contact.
""",
)
@ApiResponses(
value = [
ApiResponse(
responseCode = "204",
description = "Successfully deleted prisoner contact",
),
ApiResponse(
responseCode = "404",
description = "No prisoner contact reference with that id could be found",
),
],
)
@PreAuthorize("hasAnyRole('CONTACTS_MIGRATION')")
fun deletePrisonerContactById(
@Parameter(description = "The internal ID for the prisoner contact.", required = true)
@PathVariable prisonerContactId: Long,
) = syncService.deletePrisonerContact(prisonerContactId)
@PostMapping(path = ["/prisoner-contact"], produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@Operation(
summary = "Creates a new prisoner contact",
description = """
Requires role: ROLE_CONTACTS_MIGRATION.
Used to create a prisoner contact.
""",
)
@ApiResponses(
value = [
ApiResponse(
responseCode = "201",
description = "Successfully created prisoner contact",
content = [
Content(
mediaType = "application/json",
schema = Schema(implementation = PrisonerContact::class),
),
],
),
ApiResponse(
responseCode = "400",
description = "The request has invalid or missing fields",
content = [Content(schema = Schema(implementation = ErrorResponse::class))],
),
],
)
@PreAuthorize("hasAnyRole('CONTACTS_MIGRATION')")
fun createPrisonerContact(
@Valid @RequestBody createPrisonerContactRequest: CreatePrisonerContactRequest,
) = syncService.createPrisonerContact(createPrisonerContactRequest)
@PutMapping(path = ["/prisoner-contact/{prisonerContactId}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@Operation(
summary = "Updates a prisoner contact with new or extra detail",
description = """
Requires role: ROLE_CONTACTS_MIGRATION.
Used to update a prisoner contact.
""",
)
@ApiResponses(
value = [
ApiResponse(
responseCode = "200",
description = "Successfully updated prisoner contact",
content = [
Content(
mediaType = "application/json",
schema = Schema(implementation = PrisonerContact::class),
),
],
),
ApiResponse(
responseCode = "404",
description = "PrisonerContact not found",
),
ApiResponse(
responseCode = "400",
description = "Invalid input data",
),
],
)
@PreAuthorize("hasAnyRole('CONTACTS_MIGRATION')")
fun updatePrisonerContact(
@Parameter(description = "The internal ID for the prisoner contact.", required = true)
@PathVariable prisonerContactId: Long,
@Valid @RequestBody updatePrisonerContactRequest: UpdatePrisonerContactRequest,
) = syncService.updatePrisonerContact(prisonerContactId, updatePrisonerContactRequest)
}
| 7
|
Kotlin
|
0
| 0
|
975fa02a8ef74e3c5434838939ce4407237aa124
| 6,187
|
hmpps-contacts-api
|
MIT License
|
app/src/main/java/ru/hh/compose/navigations/DemoApplication.kt
|
hhru
| 558,759,425
| false
| null |
package ru.hh.compose.navigations
import android.app.Application
import ru.hh.compose.navigations.di.DemoDi
import timber.log.Timber
import toothpick.Toothpick
import toothpick.configuration.Configuration
internal class DemoApplication : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(PrettyLoggingTree(getString(R.string.app_name)))
initTp()
}
private fun initTp() {
val tpConfig = Configuration.forDevelopment().preventMultipleRootScopes()
Toothpick.setConfiguration(tpConfig)
DemoDi.initAppScope()
}
}
| 0
|
Kotlin
|
0
| 7
|
40f0a2af17438971a92bd6c7178959a18af284e1
| 600
|
jetpack-compose-navigation-research
|
MIT License
|
src/test/kotlin/org/jetbrains/kotlinx/dataframe/api/rename.kt
|
Kotlin
| 259,256,617
| false
| null |
package org.jetbrains.kotlinx.dataframe.api
import io.kotest.assertions.asClue
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.matchers.shouldBe
import org.jetbrains.kotlinx.dataframe.impl.columns.asAnyFrameColumn
import org.junit.Test
class RenameTests {
companion object {
val nestedDf = dataFrameOf("test_name")(dataFrameOf("another_name")(1))
val nestedColumnGroup = dataFrameOf("test_name")(
dataFrameOf("another_name")(1).first()
)
val deeplyNestedDf = kotlin.run {
val df = dataFrameOf("another_name")(1)
val rowWithDf = dataFrameOf("group_name")(df).first()
dataFrameOf("test_name")(rowWithDf)
}
val deeplyNestedFrameColumn = kotlin.run {
val df = dataFrameOf("col_0")(1)
val df1 = dataFrameOf("col_1")(df)
dataFrameOf("col_2")(df1)
}
}
@Test
fun `nested df`() {
nestedDf.renameToCamelCase() shouldBe dataFrameOf("testName")(dataFrameOf("anotherName")(1))
}
@Test
fun `nested row`() {
val df = nestedColumnGroup.renameToCamelCase()
df.columnNames() shouldBe listOf("testName")
df.getColumnGroup("testName").columnNames() shouldBe listOf("anotherName")
}
@Test
fun `deeply nested df`() {
val df = deeplyNestedDf.renameToCamelCase()
df.schema().asClue {
df.columnNames() shouldBe listOf("testName")
df.getColumnGroup("testName").columnNames() shouldBe listOf("groupName")
df["testName"]["groupName"].asAnyFrameColumn()[0].columnNames() shouldBe listOf("anotherName")
}
}
@Test
fun `deeply nested frame column`() {
val df = deeplyNestedFrameColumn.renameToCamelCase()
df.schema().asClue {
shouldNotThrowAny {
df["col2"].asAnyFrameColumn().firstOrNull()!!["col1"].asAnyFrameColumn().firstOrNull()!!["col0"]
}
}
}
}
| 91
|
Kotlin
|
4
| 94
|
41a099b4d9b563d0518e1550e764211f43e34702
| 2,003
|
dataframe
|
Apache License 2.0
|
core/src/commonMain/kotlin/io/github/kitakkun/kondition/core/internal/KonditionInternalApi.kt
|
kitakkun
| 869,640,130
| false
|
{"Kotlin": 198429}
|
@file:Suppress("UNUSED")
package io.github.kitakkun.kondition.core.internal
@RequiresOptIn(
message = "This is a util function for Kondition compiler. Don't use it directly from source code.",
level = RequiresOptIn.Level.ERROR,
)
internal annotation class KonditionInternalApi
| 4
|
Kotlin
|
0
| 9
|
09f5c9a290aa57035e92820a4c486d9cc915f932
| 287
|
Kondition
|
Apache License 2.0
|
test/src/me/anno/tests/utils/WindowsShortcutTest.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.tests
import me.anno.io.files.FileReference.Companion.getReference
import me.anno.io.utils.WindowsShortcut
fun main() {
@Suppress("SpellCheckingInspection")
val names = arrayOf( /* "src/test/fixtures/Local file.lnk",
"src/test/fixtures/Local folder.lnk",
"src/test/fixtures/Remote folder.lnk",
"src/test/fixtures/Remote folder (mapped to X-drive).lnk",
"src/test/fixtures/Hazarsolve Eduction Tubes II.pdf - Shortcut.lnk",
"src/test/fixtures/HSBD-10AS Instructions.pdf - Shortcut.lnk",
"src/test/fixtures/HSBD-50E Instructions.pdf - Shortcut.lnk",
"src/test/fixtures/test.pdf - Shortcut.lnk",*/
"C:/Users/Antonio/Desktop/Eclipse.lnk"
)
for (name in names) {
val file = getReference(name)
val link = WindowsShortcut(file)
System.out.printf("-------%s------ \n", name)
System.out.printf("getRealFilename: %s \n", link.absolutePath)
System.out.printf("getDescription: %s \n", link.description)
System.out.printf("getRelativePath: %s \n", link.relativePath)
System.out.printf("getWorkingDirectory: %s \n", link.workingDirectory)
System.out.printf("getCommandLineArguments: %s \n", link.commandLineArguments)
System.out.printf("isLocal: %b \n", link.isLocal)
System.out.printf("isDirectory: %b \n", link.isDirectory)
}
}
| 0
| null |
1
| 9
|
566e183d43bff96ee3006fecf0142e6d20828857
| 1,453
|
RemsEngine
|
Apache License 2.0
|
composeApp/src/iosMain/kotlin/MainViewController.kt
|
rbrauwers
| 715,620,789
| false
|
{"Kotlin": 102653, "Swift": 781}
|
import androidx.compose.runtime.remember
import androidx.compose.ui.window.ComposeUIViewController
import com.arkivanov.decompose.DefaultComponentContext
import com.arkivanov.essenty.lifecycle.LifecycleRegistry
import components.AppRootComponent
fun MainViewController() = ComposeUIViewController {
val rootComponent = remember {
AppRootComponent(DefaultComponentContext(LifecycleRegistry()))
}
App(rootComponent)
}
| 0
|
Kotlin
|
0
| 0
|
e3c5677dec0b51a6b48587b5ebf97c19240918bf
| 438
|
news-app-multiplatform
|
Apache License 2.0
|
src/commonMain/kotlin/io/smallibs/pilin/standard/either/Functor.kt
|
d-plaindoux
| 354,225,640
| false
| null |
package io.smallibs.pilin.standard.either
import io.smallibs.pilin.abstractions.Functor
import io.smallibs.pilin.core.Standard.Infix.then
import io.smallibs.pilin.standard.either.Either.Companion.left
import io.smallibs.pilin.standard.either.Either.Companion.right
import io.smallibs.pilin.standard.either.Either.EitherK
import io.smallibs.pilin.standard.either.Either.EitherK.Companion.fold
import io.smallibs.pilin.type.App
import io.smallibs.pilin.type.Fun
object Functor {
private class FunctorImpl<L> : Functor.API<EitherK<L>> {
override suspend fun <A, B> map(f: Fun<A, B>): Fun<App<EitherK<L>, A>, App<EitherK<L>, B>> =
{ ma -> ma.fold(::left, f then ::right) }
}
fun <L> functor(): Functor.API<EitherK<L>> = FunctorImpl()
}
| 3
|
Kotlin
|
1
| 9
|
4a96f11e7360610d04b03d5a7aa52b8df83e4f4a
| 766
|
pilin
|
MIT License
|
sqlbrite-kotlin/src/main/java/com/squareup/sqlbrite3/extensions.kt
|
square
| 31,001,422
| false
| null |
/*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE") // Extensions provided for intentional convenience.
package com.squareup.sqlbrite3
import android.database.Cursor
import android.support.annotation.RequiresApi
import com.squareup.sqlbrite3.BriteDatabase.Transaction
import com.squareup.sqlbrite3.SqlBrite.Query
import io.reactivex.Observable
import java.util.Optional
typealias Mapper<T> = (Cursor) -> T
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper`.
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows do not emit
* an item.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
inline fun <T> Observable<Query>.mapToOne(noinline mapper: Mapper<T>): Observable<T>
= lift(Query.mapToOne(mapper))
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper`
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows emit
* `default`.
*
* This operator emits `defaultValue` if null is returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
* @param default Value returned if result set is empty
*/
inline fun <T> Observable<Query>.mapToOneOrDefault(default: T, noinline mapper: Mapper<T>): Observable<T>
= lift(Query.mapToOneOrDefault(mapper, default))
/**
* Transforms an observable of single-row [Query] to an observable of `T` using `mapper.
*
* It is an error for a query to pass through this operator with more than 1 row in its result set.
* Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows emit
* `default`.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
@RequiresApi(24)
inline fun <T> Observable<Query>.mapToOptional(noinline mapper: Mapper<T>): Observable<Optional<T>>
= lift(Query.mapToOptional(mapper))
/**
* Transforms an observable of [Query] to `List<T>` using `mapper` for each row.
*
* Be careful using this operator as it will always consume the entire cursor and create objects
* for each row, every time this observable emits a new query. On tables whose queries update
* frequently or very large result sets this can result in the creation of many objects.
*
* This operator ignores null cursors returned from [Query.run].
*
* @param mapper Maps the current [Cursor] row to `T`. May not return null.
*/
inline fun <T> Observable<Query>.mapToList(noinline mapper: Mapper<T>): Observable<List<T>>
= lift(Query.mapToList(mapper))
/**
* Run the database interactions in `body` inside of a transaction.
*
* @param exclusive Uses [BriteDatabase.newTransaction] if true, otherwise
* [BriteDatabase.newNonExclusiveTransaction].
*/
inline fun <T> BriteDatabase.inTransaction(
exclusive: Boolean = true,
body: BriteDatabase.(Transaction) -> T
): T {
val transaction = if (exclusive) newTransaction() else newNonExclusiveTransaction()
try {
val result = body(transaction)
transaction.markSuccessful()
return result
} finally {
transaction.end()
}
}
| 5
|
Java
|
441
| 4,650
|
d4cf6ef967452f19a508e14b7c46f64964f8052e
| 4,059
|
sqlbrite
|
Apache License 2.0
|
src/test/kotlin/com/vauthenticator/server/account/mailverification/MailVerificationControllerTest.kt
|
VAuthenticator
| 191,632,792
| false
| null |
package com.vauthenticator.server.account.mailverification
import com.vauthenticator.server.i18n.I18nMessageInjector
import com.vauthenticator.server.i18n.I18nScope
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.just
import io.mockk.runs
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup
@ExtendWith(MockKExtension::class)
internal class MailVerificationControllerTest {
lateinit var mokMvc: MockMvc
@MockK
lateinit var mailVerifyMailChallengeSent: VerifyMailChallengeSent
@MockK
lateinit var i18nMessageInjector: I18nMessageInjector
@BeforeEach
internal fun setUp() {
mokMvc = standaloneSetup(MailVerificationController(i18nMessageInjector, mailVerifyMailChallengeSent)).build()
}
@Test
internal fun `when the challenge is verified`() {
every { mailVerifyMailChallengeSent.verifyMail("A_TICKET") } just runs
every { i18nMessageInjector.setMessagedFor(I18nScope.SUCCESSFUL_MAIL_VERIFY_PAGE, any()) } just runs
mokMvc.perform(MockMvcRequestBuilders.get("/mail-verify/A_TICKET"))
.andExpect(MockMvcResultMatchers.status().isOk)
}
}
| 40
| null |
1
| 17
|
d9de0195848db4a47617837e948c6ded94778ead
| 1,549
|
vauthenticator
|
Apache License 2.0
|
src/main/kotlin/z3roco01/pragmatica/datagen/provider/PragmaticaModelProvider.kt
|
z3roco01
| 838,691,497
| false
|
{"Kotlin": 24737}
|
package z3roco01.pragmatica.datagen.provider
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput
import net.fabricmc.fabric.api.datagen.v1.provider.FabricModelProvider
import net.minecraft.data.client.*
import net.minecraft.item.Item
import net.minecraft.util.Identifier
import z3roco01.pragmatica.Pragmatica
import z3roco01.pragmatica.item.PragmaticaItems
class PragmaticaModelProvider(dataOutput: FabricDataOutput): FabricModelProvider(dataOutput) {
override fun generateBlockStateModels(blockStateModelGenerator: BlockStateModelGenerator) {
}
override fun generateItemModels(itemModelGenerator: ItemModelGenerator) {
itemModelGenerator.register(PragmaticaItems.PINK_GOLD_INGOT, Models.GENERATED)
itemModelGenerator.register(PragmaticaItems.PINK_GOLD_DUST, Models.GENERATED)
itemModelGenerator.register(PragmaticaItems.PINK_GOLD_NUGGET, Models.GENERATED)
}
}
| 0
|
Kotlin
|
0
| 0
|
7e608084d5b0db84e1d385693cad3d322ccf33fd
| 911
|
pragmatica
|
The Unlicense
|
sykepenger-mediators/src/main/kotlin/no/nav/helse/spleis/PersonMediator.kt
|
navikt
| 193,907,367
| false
| null |
package no.nav.helse.spleis
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.convertValue
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.prometheus.client.Summary
import java.time.LocalDate
import java.util.UUID
import no.nav.helse.Fødselsnummer
import no.nav.helse.hendelser.Hendelseskontekst
import no.nav.helse.hendelser.Periode
import no.nav.helse.hendelser.Periode.Companion.grupperSammenhengendePerioder
import no.nav.helse.hendelser.Påminnelse
import no.nav.helse.person.Person
import no.nav.helse.person.PersonHendelse
import no.nav.helse.person.PersonObserver
import no.nav.helse.person.TilstandType
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.asLocalDate
import no.nav.helse.rapids_rivers.asOptionalLocalDate
import no.nav.helse.serde.serialize
import no.nav.helse.spleis.db.HendelseRepository
import no.nav.helse.spleis.db.LagrePersonDao
import no.nav.helse.spleis.meldinger.model.HendelseMessage
import org.slf4j.LoggerFactory
internal class PersonMediator(
private val person: Person,
private val message: HendelseMessage,
private val hendelse: PersonHendelse,
private val hendelseRepository: HendelseRepository
) : PersonObserver {
private val meldinger = mutableListOf<Pakke>()
private val replays = mutableListOf<String>()
private var vedtak = false
private companion object {
private val sikkerLogg = LoggerFactory.getLogger("tjenestekall")
private val logg = LoggerFactory.getLogger(PersonMediator::class.java)
private val objectMapper = jacksonObjectMapper()
.registerModule(JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
private val jsonSizeSummary = Summary.build("json_size", "size of entire json")
.quantile(.05, .01)
.quantile(.01, .001)
.register()
private val jsonSubsizeSummary = Summary.build("json_path_size", "sizes of various paths in json(number of characters)")
.labelNames("path")
.quantile(.05, .01)
.quantile(.01, .001)
.register()
}
init {
person.addObserver(this)
}
fun finalize(rapidsConnection: RapidsConnection, context: MessageContext, lagrePersonDao: LagrePersonDao) {
val serialisertPerson = person.serialize()
try {
jsonSizeSummary.observe(serialisertPerson.json.length.toDouble())
serialisertPerson.metrikker().forEach { metrikk ->
jsonSubsizeSummary.labels(metrikk.path.joinToString(".")).observe(metrikk.størrelse().toDouble())
}
} catch (e: Exception) {
sikkerLogg.error("Kunne ikke lage metrikker for person ${hendelse.fødselsnummer()}", e)
}
lagrePersonDao.lagrePerson(message, serialisertPerson, hendelse, vedtak)
sendUtgåendeMeldinger(context)
sendReplays(rapidsConnection)
}
private fun sendUtgåendeMeldinger(context: MessageContext) {
if (meldinger.isEmpty()) return
message.logOutgoingMessages(sikkerLogg, meldinger.size)
meldinger.forEach { pakke -> pakke.publish(context) }
}
private fun sendReplays(rapidsConnection: RapidsConnection) {
if (replays.isEmpty()) return
message.logReplays(sikkerLogg, replays.size)
replays.forEach { melding ->
rapidsConnection.queueReplayMessage(hendelse.fødselsnummer(), melding)
}
}
private fun queueMessage(fødselsnummer: String, eventName: String, message: String) {
meldinger.add(Pakke(fødselsnummer, eventName, message))
}
override fun inntektsmeldingReplay(fødselsnummer: Fødselsnummer, vedtaksperiodeId: UUID) {
hendelseRepository.finnInntektsmeldinger(fødselsnummer).forEach { inntektsmelding ->
createReplayMessage(inntektsmelding, mapOf(
"@event_name" to "inntektsmelding_replay",
"vedtaksperiodeId" to vedtaksperiodeId
))
}
}
private fun createReplayMessage(message: JsonNode, extraFields: Map<String, Any>) {
message as ObjectNode
message.put("@replay", true)
extraFields.forEach { (key, value), -> message.replace(key, objectMapper.convertValue<JsonNode>(value)) }
replays.add(message.toString())
}
override fun vedtaksperiodePåminnet(hendelseskontekst: Hendelseskontekst, påminnelse: Påminnelse) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtaksperiode_påminnet", påminnelse.toOutgoingMessage()))
}
override fun vedtaksperiodeIkkePåminnet(hendelseskontekst: Hendelseskontekst, nåværendeTilstand: TilstandType) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtaksperiode_ikke_påminnet", mapOf(
"tilstand" to nåværendeTilstand
)))
}
override fun annullering(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtbetalingAnnullertEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("utbetaling_annullert", mutableMapOf(
"utbetalingId" to event.utbetalingId,
"korrelasjonsId" to event.korrelasjonsId,
"fom" to event.fom,
"tom" to event.tom,
"annullertAvSaksbehandler" to event.annullertAvSaksbehandler,
"tidspunkt" to event.annullertAvSaksbehandler,
"saksbehandlerEpost" to event.saksbehandlerEpost,
"epost" to event.saksbehandlerEpost,
"saksbehandlerIdent" to event.saksbehandlerIdent,
"ident" to event.saksbehandlerIdent,
"utbetalingslinjer" to event.utbetalingslinjer.map { mapOf(
"fom" to it.fom,
"tom" to it.tom,
"grad" to it.grad,
"beløp" to it.beløp
)}
).apply {
event.arbeidsgiverFagsystemId?.also {
this["fagsystemId"] = it
this["arbeidsgiverFagsystemId"] = it
}
event.personFagsystemId?.also {
this["personFagsystemId"] = it
}
}))
}
override fun utbetalingEndret(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtbetalingEndretEvent) {
queueMessage(hendelseskontekst , JsonMessage.newMessage("utbetaling_endret", mapOf(
"utbetalingId" to event.utbetalingId,
"type" to event.type,
"forrigeStatus" to event.forrigeStatus,
"gjeldendeStatus" to event.gjeldendeStatus,
"arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag,
"personOppdrag" to event.personOppdrag
)))
}
override fun utbetalingUtbetalt(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtbetalingUtbetaltEvent) {
queueMessage(hendelseskontekst, utbetalingAvsluttet("utbetaling_utbetalt", event))
}
override fun utbetalingUtenUtbetaling(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtbetalingUtbetaltEvent) {
queueMessage(hendelseskontekst, utbetalingAvsluttet("utbetaling_uten_utbetaling", event))
}
private fun utbetalingAvsluttet(eventName: String, event: PersonObserver.UtbetalingUtbetaltEvent) =
JsonMessage.newMessage(eventName, mapOf(
"utbetalingId" to event.utbetalingId,
"korrelasjonsId" to event.korrelasjonsId,
"type" to event.type,
"fom" to event.fom,
"tom" to event.tom,
"maksdato" to event.maksdato,
"forbrukteSykedager" to event.forbrukteSykedager,
"gjenståendeSykedager" to event.gjenståendeSykedager,
"stønadsdager" to event.stønadsdager,
"ident" to event.ident,
"epost" to event.epost,
"tidspunkt" to event.tidspunkt,
"automatiskBehandling" to event.automatiskBehandling,
"arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag,
"personOppdrag" to event.personOppdrag,
"utbetalingsdager" to event.utbetalingsdager,
"vedtaksperiodeIder" to event.vedtaksperiodeIder
))
override fun feriepengerUtbetalt(hendelseskontekst: Hendelseskontekst, event: PersonObserver.FeriepengerUtbetaltEvent) =
queueMessage(hendelseskontekst, JsonMessage.newMessage("feriepenger_utbetalt", mapOf(
"arbeidsgiverOppdrag" to event.arbeidsgiverOppdrag,
"personOppdrag" to event.personOppdrag,
)))
override fun vedtaksperiodeEndret(hendelseskontekst: Hendelseskontekst, event: PersonObserver.VedtaksperiodeEndretEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtaksperiode_endret", mapOf(
"gjeldendeTilstand" to event.gjeldendeTilstand,
"forrigeTilstand" to event.forrigeTilstand,
"aktivitetslogg" to event.aktivitetslogg.toMap(),
"harVedtaksperiodeWarnings" to event.harVedtaksperiodeWarnings,
"hendelser" to event.hendelser,
"makstid" to event.makstid,
"fom" to event.fom,
"tom" to event.tom
)))
}
override fun opprettOppgaveForSpeilsaksbehandlere(hendelseskontekst: Hendelseskontekst, event: PersonObserver.OpprettOppgaveForSpeilsaksbehandlereEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("opprett_oppgave_for_speilsaksbehandlere", mapOf(
"hendelser" to event.hendelser,
)))
}
override fun opprettOppgave(hendelseskontekst: Hendelseskontekst, event: PersonObserver.OpprettOppgaveEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("opprett_oppgave", mapOf(
"hendelser" to event.hendelser,
)))
}
override fun utsettOppgave(hendelseskontekst: Hendelseskontekst, event: PersonObserver.UtsettOppgaveEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("utsett_oppgave", mapOf(
"hendelse" to event.hendelse
)))
}
override fun vedtaksperiodeForkastet(hendelseskontekst: Hendelseskontekst, event: PersonObserver.VedtaksperiodeForkastetEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtaksperiode_forkastet", mapOf(
"tilstand" to event.gjeldendeTilstand,
"hendelser" to event.hendelser,
"fom" to event.fom,
"tom" to event.tom
)))
}
override fun vedtakFattet(
hendelseskontekst: Hendelseskontekst,
event: PersonObserver.VedtakFattetEvent
) {
vedtak = true
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtak_fattet", mutableMapOf(
"fom" to event.periode.start,
"tom" to event.periode.endInclusive,
"hendelser" to event.hendelseIder,
"skjæringstidspunkt" to event.skjæringstidspunkt,
"sykepengegrunnlag" to event.sykepengegrunnlag,
"grunnlagForSykepengegrunnlag" to event.beregningsgrunnlag,
"grunnlagForSykepengegrunnlagPerArbeidsgiver" to event.omregnetÅrsinntektPerArbeidsgiver,
"begrensning" to event.sykepengegrunnlagsbegrensning,
"inntekt" to event.inntekt,
"vedtakFattetTidspunkt" to event.vedtakFattetTidspunkt
).apply {
event.utbetalingId?.let { this["utbetalingId"] = it }
}))
}
override fun revurderingAvvist(hendelseskontekst: Hendelseskontekst, event: PersonObserver.RevurderingAvvistEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("revurdering_avvist", event.toJsonMap()))
}
override fun avstemt(hendelseskontekst: Hendelseskontekst, result: Map<String, Any>) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("person_avstemt", result))
}
override fun vedtaksperiodeIkkeFunnet(hendelseskontekst: Hendelseskontekst, vedtaksperiodeEvent: PersonObserver.VedtaksperiodeIkkeFunnetEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("vedtaksperiode_ikke_funnet", mapOf(
"vedtaksperiodeId" to vedtaksperiodeEvent.vedtaksperiodeId
)))
}
override fun manglerInntektsmelding(hendelseskontekst: Hendelseskontekst, orgnr: String, event: PersonObserver.ManglendeInntektsmeldingEvent) {
if (skalIkkeMasePåArbeidsgiver(hendelse.fødselsnummer(), orgnr, event.fom, event.tom)) {
hendelse.info("Hindrer publisering av trenger_inntektsmelding - har allerede fått inntektsmelding, men perioden er mistolket som gap")
return
}
queueMessage(hendelseskontekst , JsonMessage.newMessage("trenger_inntektsmelding", mapOf(
"fom" to event.fom,
"tom" to event.tom,
"søknadIder" to event.søknadIder
)))
}
override fun trengerIkkeInntektsmelding(hendelseskontekst: Hendelseskontekst, event: PersonObserver.TrengerIkkeInntektsmeldingEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("trenger_ikke_inntektsmelding", mapOf(
"fom" to event.fom,
"tom" to event.tom,
"søknadIder" to event.søknadIder
)))
}
override fun hendelseIkkeHåndtert(hendelseskontekst: Hendelseskontekst, event: PersonObserver.HendelseIkkeHåndtertEvent) {
queueMessage(hendelseskontekst, JsonMessage.newMessage("hendelse_ikke_håndtert", mapOf(
"hendelseId" to event.hendelseId,
"årsaker" to event.årsaker
)))
}
private fun leggPåStandardfelter(hendelseskontekst: Hendelseskontekst, outgoingMessage: JsonMessage) = outgoingMessage.apply {
hendelseskontekst.appendTo(this::set)
}
private fun queueMessage(hendelseskontekst: Hendelseskontekst, outgoingMessage: JsonMessage) {
loggHvisTomHendelseliste(outgoingMessage)
queueMessage(hendelse.fødselsnummer(), outgoingMessage.also { it.interestedIn("@event_name") }["@event_name"].asText(), leggPåStandardfelter(hendelseskontekst, outgoingMessage).toJson())
}
private fun loggHvisTomHendelseliste(outgoingMessage: JsonMessage) {
objectMapper.readTree(outgoingMessage.toJson()).let {
if (it.path("hendelser").isArray && it["hendelser"].isEmpty) {
logg.warn("Det blir sendt ut et event med tom hendelseliste - ooouups")
}
}
}
private fun skalIkkeMasePåArbeidsgiver(fnr: String, orgnr: String, fom: LocalDate, tom: LocalDate): Boolean {
val gjeldendePeriode = hendelseRepository.finnSøknader(Fødselsnummer.tilFødselsnummer(fnr))
.flatMap { søknad -> Periode(søknad["fom"].asLocalDate(), søknad["tom"].asLocalDate()) }
.grupperSammenhengendePerioder()
.firstOrNull { it.contains(fom) || it.contains(tom) }
return hendelseRepository
.finnInntektsmeldinger(Fødselsnummer.tilFødselsnummer(fnr))
.filterNot { it["foersteFravaersdag"] == null }
.filter { it["virksomhetsnummer"].asText() == orgnr }
.map { inntektsmelding ->
inntektsmelding["foersteFravaersdag"].asOptionalLocalDate() to
if (inntektsmelding["arbeidsgiverperioder"].isEmpty) Periode(LocalDate.MIN, LocalDate.MIN)
else Periode(
inntektsmelding["arbeidsgiverperioder"].minOf { it["fom"].asLocalDate() },
inntektsmelding["arbeidsgiverperioder"].maxOf { it["tom"].asLocalDate() }
)
}
.any { (førsteFraværsdag, sammenslåttArbeidsgiverperiode) -> gjeldendePeriode?.fårInntektFra(førsteFraværsdag, sammenslåttArbeidsgiverperiode) ?: false }
}
private fun Periode.fårInntektFra(førsteFraværsdag: LocalDate?, arbeidsgiverperiode: Periode): Boolean {
if (førsteFraværsdag.erEtterPeriode(arbeidsgiverperiode)) return førsteFraværsdag in this
return this.overlapperMed(arbeidsgiverperiode)
}
private fun LocalDate?.erEtterPeriode (periode: Periode) = this?.let { periode.endInclusive < this } ?: false
private data class Pakke (
private val fødselsnummer: String,
private val eventName: String,
private val blob: String,
) {
fun publish(context: MessageContext) {
context.publish(fødselsnummer, blob.also { sikkerLogg.info("sender $eventName: $it") })
}
}
}
| 0
|
Kotlin
|
3
| 4
|
470b02c1f41847ea2afcf2c4fd78ae66229b03d5
| 16,663
|
helse-spleis
|
MIT License
|
thirdparty/ktfx-controlsfx-layouts/src/main/kotlin/ktfx/controlsfx/layouts/_SegmentedBar.kt
|
hanggrian
| 102,934,147
| false
| null |
@file:JvmMultifileClass
@file:JvmName("ControlsfxLayoutsKt")
@file:OptIn(ExperimentalContracts::class)
@file:Suppress("ktlint")
package ktfx.controlsfx.layouts
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.InvocationKind.EXACTLY_ONCE
import kotlin.contracts.contract
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
import ktfx.layouts.KtfxLayoutDslMarker
import ktfx.layouts.NodeContainer
import org.controlsfx.control.SegmentedBar
/**
* Add a [SegmentedBar] to this container.
*
* @return the control added.
*/
public fun <T : SegmentedBar.Segment> NodeContainer.segmentedBar(): SegmentedBar<T> = segmentedBar()
{ }
/**
* Create a [SegmentedBar] with configuration block.
*
* @param configuration the configuration block.
* @return the control created.
*/
public inline fun <T : SegmentedBar.Segment> segmentedBar(configuration: (@KtfxLayoutDslMarker
SegmentedBar<T>).() -> Unit): SegmentedBar<T> {
contract { callsInPlace(configuration, EXACTLY_ONCE) }
val child = SegmentedBar<T>()
child.configuration()
return child
}
/**
* Add a [SegmentedBar] with configuration block to this container.
*
* @param configuration the configuration block.
* @return the control added.
*/
public inline fun <T : SegmentedBar.Segment>
NodeContainer.segmentedBar(configuration: (@KtfxLayoutDslMarker
SegmentedBar<T>).() -> Unit): SegmentedBar<T> {
contract { callsInPlace(configuration, EXACTLY_ONCE) }
val child = SegmentedBar<T>()
child.configuration()
return addChild(child)
}
/**
* Create a styled [SegmentedBar].
*
* @param styleClass the CSS style class.
* @param id the CSS id.
* @return the styled control created.
*/
public fun <T : SegmentedBar.Segment> styledSegmentedBar(vararg styleClass: String, id: String? =
null): SegmentedBar<T> = styledSegmentedBar(styleClass = *styleClass, id = id) { }
/**
* Add a styled [SegmentedBar] to this container.
*
* @param styleClass the CSS style class.
* @param id the CSS id.
* @return the styled control added.
*/
public fun <T : SegmentedBar.Segment> NodeContainer.styledSegmentedBar(vararg styleClass: String,
id: String? = null): SegmentedBar<T> = styledSegmentedBar(styleClass = *styleClass, id = id)
{ }
/**
* Create a styled [SegmentedBar] with configuration block.
*
* @param styleClass the CSS style class.
* @param id the CSS id.
* @param configuration the configuration block.
* @return the styled control created.
*/
public inline fun <T : SegmentedBar.Segment> styledSegmentedBar(
vararg styleClass: String,
id: String? = null,
configuration: (@KtfxLayoutDslMarker SegmentedBar<T>).() -> Unit,
): SegmentedBar<T> {
contract { callsInPlace(configuration, EXACTLY_ONCE) }
val child = SegmentedBar<T>()
child.styleClass += styleClass
child.id = id
child.configuration()
return child
}
/**
* Add a styled [SegmentedBar] with configuration block to this container.
*
* @param styleClass the CSS style class.
* @param id the CSS id.
* @param configuration the configuration block.
* @return the styled control added.
*/
public inline fun <T : SegmentedBar.Segment> NodeContainer.styledSegmentedBar(
vararg styleClass: String,
id: String? = null,
configuration: (@KtfxLayoutDslMarker SegmentedBar<T>).() -> Unit,
): SegmentedBar<T> {
contract { callsInPlace(configuration, EXACTLY_ONCE) }
val child = SegmentedBar<T>()
child.styleClass += styleClass
child.id = id
child.configuration()
return addChild(child)
}
| 1
| null |
2
| 19
|
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
| 3,701
|
ktfx
|
Apache License 2.0
|
api/src/main/kotlin/org/jetbrains/kotlinx/dl/api/core/activation/Activations.kt
|
JetBrains
| 249,948,572
| false
| null |
/*
* Copyright 2020-2022 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.kotlinx.dl.api.core.activation
import org.tensorflow.Operand
import org.tensorflow.op.Ops
import org.tensorflow.op.core.Stack
/**
* Neural network hyperparameter, activation function of a node defines the output of that node given an input or set of inputs.
*/
public enum class Activations {
/**
* Linear unit. Returns unmodified input.
*
* NOTE: Doing nothing useful. Returns to ancient times of linear perceptron.
*
* Calls [LinearActivation] under the hood.
*/
Linear,
/**
* Sigmoid activation function.
*
* Transforms input 'x' according formula:
* ```
* sigmoid(x) = 1 / (1 + exp(-x))
* ```
*
* For small values (<-5), `sigmoid` returns a value close to zero, and for large values (>5)
* the result of the function gets close to 1.
*
* NOTE: Sigmoid is equivalent to a 2-element Softmax, where the second element is
* assumed to be zero. The sigmoid function always returns a value between 0 and 1.
*
* Calls [SigmoidActivation] under the hood.
*
*/
Sigmoid,
/**
* Hyperbolic tangent activation function.
*
* Transforms input 'x' according formula:
* ```
* tanh(x) = sinh(x)/cosh(x) = ((exp(x) - exp(-x))/(exp(x) + exp(-x)))
* ```
*
* Calls [TanhActivation] under the hood.
*/
Tanh,
/**
* Rectified linear unit (ReLU).
*
* With default values, this returns the standard ReLU activation:
* `max(x, 0)`, the element-wise maximum of 0 and the input tensor.
*
* Calls [ReluActivation] under the hood.
*/
Relu,
/**
* Computes Rectified Linear 6:
* ```
* min(max(features, 0), 6)
* ```
* Calls [Relu6Activation] under the hood.
*
* @see <a href="http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf">
* Convolutional Deep Belief Networks on CIFAR-10. <NAME></a>
*/
Relu6,
/**
* Exponential Linear Unit.
*
* The exponential linear unit (ELU) with `alpha > 0` is:
* `x` if `x > 0` and `alpha * (exp(x) - 1)` if `x < 0`
*
* For this implementation alpha is equal to 1.0.
*
* The ELU hyperparameter `alpha` controls the value to which an
* ELU saturates for negative net inputs. ELUs diminish the
* vanishing gradient effect.
*
* ELUs have negative values which pushes the mean of the activations closer to zero.
*
* Mean activations that are closer to zero enable faster learning as they
* bring the gradient closer to the natural gradient.
*
* ELUs saturate to a negative value when the argument gets smaller.
* Saturation means a small derivative which decreases the variation
* and the information that is propagated to the next layer.
*
* Calls [EluActivation] under the hood.
*
* @see <a href="https://arxiv.org/abs/1511.07289">Fast and Accurate Deep Network Learning by Exponential Linear Units
* (ELUs) (Clevert et al., 2016)</a>
*/
Elu,
/**
* Scaled Exponential Linear Unit (SELU).
*
* The Scaled Exponential Linear Unit (SELU) activation function is defined as:
* ```
* if x > 0: return scale * x
* if x < 0: return scale * alpha * (exp(x) - 1)
* ```
* where `alpha` and `scale` are pre-defined constants (`alpha=1.67326324` and `scale=1.05070098`).
*
* Basically, the SELU activation function multiplies `scale` (> 1) with the
* output of the `tf.keras.activations.elu` function to ensure a slope larger
* than one for positive inputs.
*
* NOTE: The values of `alpha` and `scale` are
* chosen so that the mean and variance of the inputs are preserved
* between two consecutive layers as long as the weights are initialized
* correctly (see [org.jetbrains.kotlinx.dl.api.core.initializer.LeCunNormal] initializer)
* and the number of input units is "large enough"
* (see reference paper for more information).
*
* Calls [SeluActivation] under the hood.
*
* @see <a href="https://arxiv.org/abs/1706.02515">Klambauer et al., 2017</a>
*/
Selu,
/**
* Softmax converts a real vector to a vector of categorical probabilities.
* The elements of the output vector are in range (0, 1) and sum to 1.
*
* Softmax is often used as the activation for the last
* layer of a classification network because the result could be interpreted as
* a probability distribution.
*
* Calls [SoftmaxActivation] under the hood.
*/
Softmax,
/**
* Log softmax activation function.
*
* For each batch `i` and class `j` we have
* ```
* logsoftmax = logits - log(reduce_sum(exp(logits), axis))
* ```
*/
LogSoftmax,
/**
* Exponential activation function.
*
* Transforms input 'x' according formula:
* ```
* exp(x)
* ```
*
* Calls [ExponentialActivation] under the hood.
*/
Exponential,
/**
* Softplus activation function.
*
* Transforms input 'x' according formula:
* ```
* softplus(x) = log(exp(x) + 1)
* ```
*
* Calls [SoftPlusActivation] under the hood.
*/
SoftPlus,
/***
* Softsign activation function.
*
* Transforms input 'x' according formula:
* ```
* softsign(x) = x / (abs(x) + 1)
* ```
*
* Calls [SoftSignActivation] under the hood.
*/
SoftSign,
/**
* Hard sigmoid activation function.
*
* Transforms input 'x' according formula:
* ```
* if x < -2.5: return 0
* if x > 2.5: return 1
* if -2.5 <= x <= 2.5: return 0.2 * x + 0.5
* ```
* A faster approximation of the sigmoid activation.
*
* Calls [HardSigmoidActivation] under the hood.
*/
HardSigmoid,
/**
* Softshrink activation function.
*
* Transforms input 'x' according formula:
* ```
* if x > lambda: return x − lambda
* if x < -lambda: return x + lambda
* otherwise return 0
* ```
* A faster approximation of the sigmoid activation.
*
* Calls [SoftShrinkActivation] under the hood.
*/
SoftShrink,
/**
* Swish activation function.
*
* Transforms input 'x' according formula:
* ```
* swish(x) = x * sigmoid(x)
* ```
*
* It is a smooth, non-monotonic function that consistently matches
* or outperforms ReLU on deep networks, it is unbounded above and
* bounded below.
*
* Calls [SwishActivation] under the hood.
*
* @see <a href="https://arxiv.org/abs/1710.05941">Ramachandran et al., 2017</a>
*/
Swish,
/**
* Mish activation function.
*
* Transforms input 'x' according formula:
* ```
* mish(x) = x * tanh(softplus(x))
* ```
*
* It is a smooth, non-monotonic function that consistently matches
* or outperforms ReLU and Swish on deep networks, it is unbounded above and
* bounded below. It also smoothens the loss landscape of the network.
*
* Calls [MishActivation] under the hood.
*
* @see <a href="https://arxiv.org/abs/1908.08681">Misra, 2019</a>
*/
Mish,
/**
* HardShrink Function
*
* Computes hard shrink function:
*
* hardshrink(x) = x if x < lower
* x if x > upper
* 0 otherwise
*
* Calls [HardShrinkActivation] under the hood.
*/
HardShrink,
/**
* Gelu Function
*
* Computes the Gaussian Error Linear Unit (GELU):
*
* gelu(x) = x * P(X <= x) where P(X) ~ N(0, 1)
*
* Calls [GeluActivation] under the hood.
*/
Gelu,
/**
* Non-Parametric Linearly Scaled Hyperbolic Tangent (LiSHT) Activation Function.
*
* ```
* LiSHT(x) = x * tanh(x)
* ```
*/
LiSHT,
/**
* Snake Activation Function.
*
* Transforms input 'x' according formula:
* ```
* snake(x) = x + (1 - cos(2 * frequency * x)) / (2 * frequency)
* ```
* @see [Neural Networks Fail to Learn Periodic Functions and How to Fix It](https://arxiv.org/abs/2006.08195).
*/
Snake,
/**
* TanhShrink Activation Function.
*
* This is a hyperbolic tangent (TanH) shrink activation type that implements the element wise function:
* ```
* TanhShrink(x) = x − tanh(x)
* ```
* Calls [TanhActivation] under the hood.
*/
TanhShrink,
/**
* Sparsemax activation function is similar to softmax but able to output sparse probabilities.
*
* for batch `i` and class `j`
*
* sparsemax(x)`[i,j]` = max(0, logits`[i,j]` - `τ`(logits`[i,:]`))
*
* @see <a href="https://arxiv.org/abs/1602.02068">From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification</a>
*/
Sparsemax;
public companion object {
/**
* Converts [activationType] to the appropriate [Activation] subclass.
*/
public fun convert(activationType: Activations): Activation {
return when (activationType) {
Sigmoid -> SigmoidActivation()
Linear -> LinearActivation()
Tanh -> TanhActivation()
TanhShrink -> TanhShrinkActivation()
Relu -> ReluActivation()
Relu6 -> Relu6Activation()
Elu -> EluActivation()
Selu -> SeluActivation()
Softmax -> SoftmaxActivation()
LogSoftmax -> LogSoftmaxActivation()
Exponential -> ExponentialActivation()
SoftPlus -> SoftPlusActivation()
SoftSign -> SoftSignActivation()
HardSigmoid -> HardSigmoidActivation()
Swish -> SwishActivation()
Mish -> MishActivation()
HardShrink -> HardShrinkActivation()
SoftShrink -> SoftShrinkActivation()
LiSHT -> LishtActivation()
Snake -> SnakeActivation()
Gelu -> GeluActivation()
Sparsemax -> SparsemaxActivation()
}
}
}
}
/**
* @see [Activations.Linear]
*/
public class LinearActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
return features
}
}
/**
* @see [Activations.Sigmoid]
*/
public class SigmoidActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.math.sigmoid(features)
}
/**
* @see [Activations.Relu]
*/
public class ReluActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.relu(features)
}
/**
* @see [Activations.Relu6]
*/
public class Relu6Activation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.relu6(features)
}
/**
* @see [Activations.Tanh]
*/
public class TanhActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.math.tanh(features)
}
/**
* @see [Activations.TanhShrink]
*/
public class TanhShrinkActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> =
tf.math.sub(features, tf.math.tanh(features))
}
/**
* @see [Activations.Elu]
*/
public class EluActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.elu(features)
}
/**
* @see [Activations.Selu]
*/
public class SeluActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.selu(features)
}
/**
* Internal class, wrapping TensorFlow operand
* ```
* tf.nn.softmax
* ```
*
* For each batch `i` and class `j` we have
*
* ```
* softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))
* ```
*
* @see [Activations.Softmax] for explanation.
*/
public class SoftmaxActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.softmax(features)
}
/**
* @see [Activations.LogSoftmax]
*/
public class LogSoftmaxActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.logSoftmax(features)
}
/**
* @see [Activations.Exponential]
*/
public class ExponentialActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.math.exp(features)
}
/**
* @see [Activations.SoftPlus]
*/
public class SoftPlusActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> =
tf.math.log(tf.math.add(tf.math.exp(features), tf.constant(1.0f)))
}
/**
* @see [Activations.SoftSign]
*/
public class SoftSignActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> = tf.nn.softsign(features)
}
/**
* @see [Activations.HardSigmoid]
*/
public class HardSigmoidActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
val point2: Operand<Float> = tf.constant(0.2f)
val point5: Operand<Float> = tf.constant(0.5f)
return tf.math.add(tf.math.mul(features, point2), point5)
}
}
/**
* @see [Activations.Swish]
*/
public class SwishActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> =
tf.math.mul(features, tf.math.sigmoid(features))
}
/**
* @see [Activations.Mish]
*/
public class MishActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> =
tf.math.mul(features, tf.math.tanh(tf.math.softplus(features)))
}
/**
* ```
* hardshrink(x) = x if x < lower
* x if x > upper
* 0 otherwise
* ```
*
* @property [lower] lower bound for setting values to zeros
* @property [upper] upper bound for setting values to zeros
*
* @see [Activations.HardShrink]
*/
public class HardShrinkActivation(public val lower: Float = -0.5f, public val upper: Float = 0.5f) : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
require(lower < upper) {
"The value of lower should not be higher than upper"
}
val maskLower = tf.math.less(features, tf.constant(lower))
val maskUpper = tf.math.greater(features, tf.constant(upper))
return tf.where3(tf.math.logicalOr(maskLower, maskUpper), features, tf.zerosLike(features))
}
}
/**
* @property [lower] lower bound for setting values to zeros
* @property [upper] upper bound for setting values to zeros
* @see [Activations.SoftShrink]
*/
public class SoftShrinkActivation(public val lower: Float = -0.5f, public val upper: Float = 0.5f) : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
require((lower < upper) && (lower < 0) && (upper > 0)) {
"The boundary values have to be non zero and the lower bound has to be lower as the upper"
}
val zeros = tf.math.mul(features, tf.constant(0f))
val valuesBelowLower = tf.where3(
tf.math.less(features, tf.constant(lower)),
tf.math.sub(
features, tf.constant(lower)
),
zeros
)
val valuesAboveUpper = tf.where3(
tf.math.less(tf.constant(upper), features),
tf.math.sub(
features, tf.constant(upper)
),
zeros
)
return tf.math.add(valuesBelowLower, valuesAboveUpper)
}
}
/**
* @see [Activations.LiSHT]
*/
public class LishtActivation : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> =
tf.math.mul(features, tf.math.tanh(features))
}
/**
* @property [frequency] A scalar, frequency of the periodic part.
* @see [Activations.Snake]
*/
public class SnakeActivation(private val frequency: Float = 1.0f) : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
val doubleFreqConstant = tf.constant(2 * frequency)
return tf.math.add(
features,
tf.math.div(
tf.math.sub(tf.constant(1.0f), tf.math.cos(tf.math.mul(doubleFreqConstant, features))),
doubleFreqConstant
)
)
}
}
/**
* @property [approximate] The boolean flag to toggle approximation.
*
* @see [Activations.Gelu]
*/
public class GeluActivation(public val approximate: Boolean = false) : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
if (approximate) {
val coefficient = tf.constant(0.044715f)
return tf.math.mul(
tf.constant(0.5f), tf.math.mul(
features, tf.math.add(
tf.constant(1.0f), tf.math.tanh(
tf.math.mul(
tf.constant(0.7978845608028654f), // This value is equal to sqrt(2/pi) to avoid a constant division
tf.math.add(features, tf.math.mul(coefficient, tf.math.pow(features, tf.constant(3f))))
)
)
)
)
)
} else {
return tf.math.mul(
tf.constant(0.5f),
tf.math.mul(
features,
tf.math.add(
tf.constant(1f),
tf.math.erf(tf.math.div(features, tf.constant(1.4142135623730951f)))
)
)
)
}
}
}
/**
* @property [axis] axis along which the sparsemax operation is applied.
* @see [Activations.Sparsemax]
*/
public class SparsemaxActivation(private val axis: Int = -1) : Activation {
override fun apply(tf: Ops, features: Operand<Float>): Operand<Float> {
// Keep references to shape because we perform sparsemax on 2D.
// If required, we need to reshape features to 2D and back.
val shape = features.asOutput().shape()
val rank = shape.numDimensions()
val isLastAxis = (axis == -1) || (axis == rank - 1)
if (isLastAxis) {
val output = compute2DSparsemax(tf, features)
return tf.ensureShape(output, shape)
}
// compute2DSparsemax only calculates sparsemax operation along it's last axis.
// If different axis is required for sparsemax, we first swap axes, then calculate compute2DSparsemax then
// swap axes back.
val axisNorm = axis % rank //ensure axis is within rank
val logits = swapAxis(tf, features, axisNorm, rank - 1)
val output = compute2DSparsemax(tf, logits)
return tf.ensureShape(swapAxis(tf, output, axisNorm, rank - 1), shape)
}
private fun swapAxis(tf: Ops, features: Operand<Float>, axis: Int, lastIndex: Int): Operand<Float> {
/**
* swaps features Operand's lastIndex with axis
*/
val range = (tf.range(tf.constant(0), tf.constant(lastIndex + 1), tf.constant(1)))
return tf.linalg.transpose(
features,
tf.tensorScatterUpdate(
range,
tf.constant(arrayOf(intArrayOf(axis), intArrayOf(lastIndex))),
tf.constant(intArrayOf(lastIndex, axis))
)
)
}
private fun compute2DSparsemax(tf: Ops, features: Operand<Float>): Operand<Float> {
val shape = features.asOutput().tensor().shape()
val dims = shape[shape.lastIndex]
val dimsOp = tf.constant(dims.toInt())
val obs = shape.reduce { acc, l -> acc * l } / dims
val one = tf.constant(1f)
val z = tf.reshape(features, tf.constant(longArrayOf(obs, dims)))
val zSorted = tf.nn.topK(z, dimsOp)
val zCumSum = tf.math.cumsum(zSorted.values(), tf.constant(-1))
val k = tf.range(one, tf.math.add(tf.dtypes.cast(dimsOp, Float::class.javaObjectType), one), one)
// check where (k * z_sorted + 1 > cumsum(z)
val zCheck = tf.math.greater(tf.math.add(one, tf.math.mul(k, zSorted.values())), zCumSum)
// casting boolean values to Int makes true = 1, false = 0,
// then summing each row is same as finding last value that is one in such vector [1,1,..1,0,0,..,0]
val kz = tf.reduceSum(tf.dtypes.cast(zCheck, Int::class.javaObjectType), tf.constant(-1))
// If there are inf values or all values are -inf, the k_z will be zero,
// this is mathematically invalid and will also cause the gather_nd to fail.
// Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then
// fixed later (see p_safe) by returning p = nan. This results in the same
// behavior as softmax.
// (This comment is taken from original python implementation)
val kzSafe = tf.math.maximum(kz, tf.constant(1))
val indices = tf.stack(
listOf(
tf.range(tf.constant(0), tf.constant(obs.toInt()), tf.constant(1)),
tf.math.sub(tf.reshape(kzSafe, tf.constant(intArrayOf(-1))), tf.constant(1))
), Stack.axis(1)
)
val tauSum = tf.gatherNd(zCumSum, indices)
val tauZ = tf.math.div(tf.math.sub(tauSum, one), tf.dtypes.cast(kz, Float::class.javaObjectType))
val p = tf.math.maximum(tf.constant(0f), tf.math.sub(z, tf.expandDims(tauZ, tf.constant(-1))))
// getting a reference to last index. Similar to slicing the last index of a python array [:, -1]
val zCumsumLastIndex = tf.stack(
listOf(
tf.range(tf.constant(0), tf.constant(obs.toInt()), tf.constant(1)),
tf.fill(tf.constant(longArrayOf(obs)), tf.math.sub(dimsOp, tf.constant(1)))
), Stack.axis(1)
)
val pSafe = tf.where3(
tf.math.logicalOr(
tf.math.equal(kz, tf.constant(0)),
tf.math.isNan(
tf.gatherNd(zCumSum, zCumsumLastIndex)
)
),
tf.fill(tf.constant(longArrayOf(obs, dims)), tf.constant(Float.NaN)),
p
)
return tf.reshape(pSafe, tf.constant(shape))
}
}
| 81
| null |
79
| 806
|
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
| 22,734
|
KotlinDL
|
Apache License 2.0
|
app/src/main/java/com/nafanya/mp3world/features/artists/di/ArtistsComponentProvider.kt
|
AlexSoWhite
| 445,900,000
| false
| null |
package com.nafanya.mp3world.features.artists.di
interface ArtistsComponentProvider {
val artistsComponent: ArtistsComponent
}
| 0
|
Kotlin
|
0
| 0
|
480fa9c16460890d393ece7c8aa2466c031d8f78
| 133
|
mp3world
|
MIT License
|
app/src/main/java/com/suyash/creditmanager/presentation/emis/EMIsScreen.kt
|
suyash01
| 732,788,266
| false
|
{"Kotlin": 282293}
|
package com.suyash.creditmanager.presentation.emis
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.suyash.creditmanager.domain.util.order.EMIOrder
import com.suyash.creditmanager.presentation.emis.component.EMIItem
import com.suyash.creditmanager.presentation.commons.Screen
import com.suyash.creditmanager.presentation.commons.components.CustomActionBottomSheet
import com.suyash.creditmanager.presentation.commons.components.CustomConfirmationDialog
import com.suyash.creditmanager.presentation.commons.components.CustomSortingBottomSheet
import com.suyash.creditmanager.presentation.commons.model.ItemAction
@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
fun EMIsScreen(
navController: NavController,
viewModel: EMIsViewModel = hiltViewModel()
) {
val haptics = LocalHapticFeedback.current
var isItemBottomSheetOpen by rememberSaveable {
mutableStateOf(false)
}
var isSortBottomSheetOpen by rememberSaveable {
mutableStateOf(false)
}
var openDeleteConfirmationDialog by rememberSaveable {
mutableStateOf(false)
}
var fabHeight by remember {
mutableIntStateOf(0)
}
val fabHeightInDp = with(LocalDensity.current) { fabHeight.toDp() }
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "EMIs") },
actions = {
IconButton(onClick = { isSortBottomSheetOpen = true }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.Sort,
contentDescription = "Sort EMIs"
)
}
}
)
},
floatingActionButton = {
FloatingActionButton(
modifier = Modifier.onGloballyPositioned { fabHeight = it.size.height },
onClick = { navController.navigate(Screen.AddEditEMIScreen.route) }
) {
Icon(Icons.Filled.Add, "Add EMI")
}
}
) {
paddingValues ->
LazyColumn(
modifier = Modifier
.padding(paddingValues),
contentPadding = PaddingValues(
bottom = fabHeightInDp + 16.dp
)
) {
items(viewModel.state.value.emis) { emi ->
EMIItem(
emi = emi,
countryCode = viewModel.state.value.countryCode,
dateFormat = viewModel.state.value.dateFormat,
modifier = Modifier
.fillMaxWidth()
.combinedClickable(
onClick = {
navController.navigate(
Screen.EMIDetailScreen.route + "?emiId=" + emi.id
)
},
onLongClick = {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
viewModel.onEvent(EMIsEvent.SelectEMI(emi))
isItemBottomSheetOpen = true
}
)
)
}
}
if(openDeleteConfirmationDialog) {
CustomConfirmationDialog(
title = "Delete EMI?",
description = "Do you want to delete ${viewModel.state.value.selectedEMI?.name}",
onDismissRequest = { openDeleteConfirmationDialog = false },
onConfirmButton = {
openDeleteConfirmationDialog = false
viewModel.onEvent(EMIsEvent.DeleteEMI(viewModel.state.value.selectedEMI))
},
onDismissButton = { openDeleteConfirmationDialog = false }
)
}
if(isItemBottomSheetOpen) {
CustomActionBottomSheet(
onDismissRequest = { isItemBottomSheetOpen = false },
actions = listOf(
ItemAction(
icon = Icons.Filled.Edit,
iconName = "Edit EMI",
title = "Edit",
onClick = {
navController.navigate(
Screen.AddEditEMIScreen.route +
"?emiId=${viewModel.state.value.selectedEMI?.id}"
)
}
),
ItemAction(
icon = Icons.Filled.Delete,
iconName = "Delete EMI",
title = "Delete",
onClick = {
openDeleteConfirmationDialog = true
}
)
)
)
}
if (isSortBottomSheetOpen) {
CustomSortingBottomSheet(
onDismissRequest = { isSortBottomSheetOpen = false },
orderList = EMIOrder.getOrderList(),
currentOrder = viewModel.state.value.emiOrder,
sort = { viewModel.onEvent(EMIsEvent.Order(it)) }
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ea4bcd5c53d1b66c54ba144d0772378c5b4f566e
| 6,906
|
credit-manager
|
Apache License 2.0
|
app/src/main/java/org/stepic/droid/adaptive/ui/fragments/AdaptiveProgressFragment.kt
|
Ujjawal-Anand
| 142,415,269
| true
|
{"Java": 1818802, "Kotlin": 1403557, "CSS": 3790, "Shell": 618, "Prolog": 98}
|
package org.stepic.droid.adaptive.ui.fragments
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.stepic.droid.R
import org.stepic.droid.adaptive.ui.adapters.AdaptiveWeeksAdapter
import org.stepic.droid.base.App
import org.stepic.droid.base.FragmentBase
import org.stepic.droid.core.presenters.AdaptiveProgressPresenter
import org.stepic.droid.core.presenters.contracts.AdaptiveProgressView
import org.stepic.droid.util.AppConstants
import javax.inject.Inject
class AdaptiveProgressFragment : FragmentBase(), AdaptiveProgressView {
companion object {
fun newInstance(courseId: Long) = AdaptiveProgressFragment().apply {
arguments = Bundle(1).apply { putLong(AppConstants.KEY_COURSE_LONG_ID, courseId) }
}
}
private var courseId = 0L
@Inject
lateinit var adaptiveProgressPresenter: AdaptiveProgressPresenter
private lateinit var recycler: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
courseId = arguments.getLong(AppConstants.KEY_COURSE_LONG_ID, 0)
super.onCreate(savedInstanceState)
}
override fun injectComponent() {
App.componentManager()
.adaptiveCourseComponent(courseId)
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
recycler = RecyclerView(context)
recycler.layoutManager = LinearLayoutManager(context)
val divider = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.list_divider_h))
recycler.addItemDecoration(divider)
return recycler
}
override fun onWeeksAdapter(adapter: AdaptiveWeeksAdapter) {
recycler.adapter = adapter
}
override fun onStart() {
super.onStart()
adaptiveProgressPresenter.attachView(this)
}
override fun onStop() {
adaptiveProgressPresenter.detachView(this)
super.onStop()
}
override fun onReleaseComponent() {
App.componentManager()
.releaseAdaptiveCourseComponent(courseId)
}
override fun onDestroy() {
adaptiveProgressPresenter.destroy()
super.onDestroy()
}
}
| 0
|
Java
|
0
| 1
|
256a90051eefe8db83f7053914004905bbb1f8d0
| 2,567
|
stepik-android
|
Apache License 2.0
|
app/src/main/java/com/nordkaz/ds24test/ui/SearchRepositoriesViewModel.kt
|
ekbandroid
| 144,299,832
| false
| null |
package com.nordkaz.ds24test.ui
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations
import android.arch.lifecycle.ViewModel
import com.nordkaz.ds24test.data.QuoteRepository
import com.nordkaz.ds24test.model.Detail
import com.nordkaz.ds24test.model.DetailResult
import com.nordkaz.ds24test.model.Quote
import com.nordkaz.ds24test.model.QuoteSearchResult
class SearchRepositoriesViewModel(val repository: QuoteRepository) : ViewModel() {
companion object {
private const val VISIBLE_THRESHOLD = 5
}
private val queryLiveData = MutableLiveData<String>()
private val detailQueryLiveData = MutableLiveData<Int>()
private val mQuoteResult: LiveData<QuoteSearchResult> = Transformations.map(queryLiveData, {
repository.searchQuotes()
})
private val mDetailResult: LiveData<DetailResult> = Transformations.map(detailQueryLiveData, {
repository.searchDetail(it)
})
val quotes: LiveData<List<Quote>> = Transformations.switchMap(mQuoteResult,
{ it -> it.data })
val networkErrors: LiveData<String> = Transformations.switchMap(mQuoteResult,
{ it -> it.networkErrors })
val details: LiveData<Detail> = Transformations.switchMap(mDetailResult,
{ it -> it.data })
val networkErrorsDetails: LiveData<String> = Transformations.switchMap(mDetailResult,
{ it -> it.networkErrors })
fun searchQuotes() {
queryLiveData.postValue("")
}
fun searchDetails(id: Int) {
detailQueryLiveData.postValue(id)
}
private var itemCount = repository.NETWORK_PAGE_SIZE
fun listScrolled(visibleItemCount: Int, lastVisibleItemPosition: Int, totalItemCount: Int) {
if (itemCount > (totalItemCount))
itemCount = totalItemCount
if (visibleItemCount + lastVisibleItemPosition + VISIBLE_THRESHOLD >= totalItemCount) {
val immutableQuery = lastQueryValue()
if ((immutableQuery != null)&&(!repository.quotesOver)) {
repository.requestMore(itemCount + 1)
itemCount += repository.NETWORK_PAGE_SIZE
}
}
}
fun lastQueryValue(): String? = queryLiveData.value
}
| 0
|
Kotlin
|
0
| 0
|
efef3a436d82b628db79a2071f9eaa4300d9a536
| 2,270
|
DS24Test
|
Apache License 2.0
|
src/main/kotlin/com/example/hsm/sign/impl/KeyFileSignature.kt
|
fclemonschool
| 218,457,180
| false
|
{"Java": 128939, "Kotlin": 23165}
|
package com.example.hsm.sign.impl
import com.example.hsm.sign.Signature
import com.example.hsm.sign.Signature.Companion.appCertificateAlias
import com.example.hsm.sign.Signature.Companion.certificationChain
import com.example.hsm.sign.Signature.Companion.keyStore
import com.example.hsm.sign.Signature.Companion.keyStorePassword
import org.bouncycastle.cert.jcajce.JcaCertStore
import org.bouncycastle.cms.CMSException
import org.bouncycastle.cms.CMSSignedDataGenerator
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder
import org.bouncycastle.operator.OperatorCreationException
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder
import java.io.IOException
import java.io.InputStream
import java.security.GeneralSecurityException
import java.security.KeyStore
import java.security.PrivateKey
import java.security.cert.X509Certificate
import java.util.*
/**
* @author jmc90
* @since 2019-11-01
*/
class KeyFileSignature(
private var keyStoreInput: KeyStore,
private var keyStorePasswordInput: CharArray,
private var appCertificateAliasInput: String
) : Signature {
override fun sign(content: InputStream): ByteArray {
try {
keyStore = keyStoreInput
keyStorePassword = keyStorePasswordInput
appCertificateAlias = appCertificateAliasInput
certificationChain = Optional.ofNullable(keyStore.getCertificateChain(appCertificateAlias))
.orElseThrow {
IOException("Cannot find Certificate Chain")
}
val certificate = certificationChain[0]
if (certificate is X509Certificate) {
certificate.checkValidity()
}
val generator = CMSSignedDataGenerator()
val certification = certificationChain[0] as X509Certificate
val sha1Signer = JcaContentSignerBuilder("SHA256WithRSA")
.build(keyStore.getKey(appCertificateAlias, keyStorePassword) as PrivateKey?)
generator.addSignerInfoGenerator(
JcaSignerInfoGeneratorBuilder(JcaDigestCalculatorProviderBuilder().build())
.build(sha1Signer, certification)
)
generator.addCertificates(JcaCertStore(listOf(*certificationChain)))
val message = CMSProcessableInputStream(content)
val signedData = generator.generate(message, false)
return signedData.encoded
} catch (e: GeneralSecurityException) {
throw IOException(e)
} catch (e: CMSException) {
throw IOException(e)
} catch (e: OperatorCreationException) {
throw IOException(e)
}
}
}
| 1
|
Java
|
1
| 2
|
906a258480452b45eb6d2c0b4e0db8a379579187
| 2,814
|
gcp-hsm-example
|
MIT License
|
idea/testData/codeInsight/overrideImplement/functionFromTraitInJava/foo/KotlinTrait.kt
|
chashnikov
| 14,658,474
| false
| null |
package foo
trait KotlinTrait {
fun bar(price : String?)
}
// KT-1043 'Implement Methods' throws a ClassCastException
| 0
| null |
0
| 1
|
88a261234860ff0014e3c2dd8e64072c685d442d
| 123
|
kotlin
|
Apache License 2.0
|
core-model/src/main/java/com/ddd/carssok/core/model/OnBoardingItem.kt
|
DDD-Community
| 566,191,080
| false
| null |
package com.ddd.carssok.core.model
// server 개발 이전 임시 더미 데이터용
data class CarBrand(
val id: Long = -1,
val name: String,
val isChecked: Boolean = false
)
| 7
|
Kotlin
|
0
| 0
|
03e80f26a4c4f7e2cbb2992e05e4800253441ea0
| 165
|
28.8-Android
|
Apache License 2.0
|
src/main/kotlin/com/google/actions/api/smarthome/SmartHomeRequest.kt
|
actions-on-google
| 165,905,654
| false
| null |
/*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.actions.api.smarthome
import org.json.JSONObject
/**
* A representation of the JSON payload received during a smart home request.
*
* @see <a href="https://developers.google.com/actions/smarthome/develop/process-intents">Public documentation</a>
*/
open class SmartHomeRequest {
lateinit var requestId: String
lateinit var inputs: Array<RequestInputs>
open class RequestInputs {
lateinit var intent: String
}
companion object {
fun create(inputJson: String): SmartHomeRequest {
val json = JSONObject(inputJson)
val requestId = json.getString("requestId")
val inputs = json.getJSONArray("inputs")
val request = inputs.getJSONObject(0)
val intent = request.getString("intent")
when (intent) {
SYNC_INTENT -> {
val syncRequest = SyncRequest()
syncRequest.requestId = requestId
syncRequest.inputs = arrayOf(SyncRequest.Inputs())
syncRequest.inputs[0].intent = intent
return syncRequest
}
QUERY_INTENT -> {
val queryRequest = QueryRequest()
queryRequest.requestId = requestId
queryRequest.inputs = arrayOf(QueryRequest.Inputs())
queryRequest.inputs[0].intent = intent
(queryRequest.inputs[0] as QueryRequest.Inputs).payload = QueryRequest.Inputs.Payload()
val devicesList = ArrayList<QueryRequest.Inputs.Payload.Device>()
val devicesJsonArray = json.getJSONArray("inputs")
.getJSONObject(0)
.getJSONObject("payload")
.getJSONArray("devices")
for (i in 0 until devicesJsonArray.length()) {
val deviceJson = devicesJsonArray.getJSONObject(i)
val deviceObject = QueryRequest.Inputs.Payload.Device()
deviceObject.id = deviceJson.getString("id")
if (deviceJson.has("customData")) {
deviceObject.customData = deviceJson.getJSONObject("customData").toMap()
}
devicesList.add(deviceObject)
}
val array = arrayOfNulls<QueryRequest.Inputs.Payload.Device>(devicesList.size)
(queryRequest.inputs[0] as QueryRequest.Inputs).payload.devices = devicesList.toArray(array)
return queryRequest
}
EXEC_INTENT -> {
val executeRequest = ExecuteRequest()
executeRequest.requestId = requestId
executeRequest.inputs = arrayOf(ExecuteRequest.Inputs())
executeRequest.inputs[0].intent = intent
(executeRequest.inputs[0] as ExecuteRequest.Inputs).payload = ExecuteRequest.Inputs.Payload()
val commandsList = ArrayList<ExecuteRequest.Inputs.Payload.Commands>()
val commandsJsonArray = json.getJSONArray("inputs")
.getJSONObject(0)
.getJSONObject("payload")
.getJSONArray("commands")
for (i in 0 until commandsJsonArray.length()) {
val devicesList = ArrayList<ExecuteRequest.Inputs.Payload.Commands.Devices>()
val devicesJsonArray = commandsJsonArray.getJSONObject(i).getJSONArray("devices")
for (j in 0 until devicesJsonArray.length()) {
val deviceJson = devicesJsonArray.getJSONObject(j)
val deviceObject = ExecuteRequest.Inputs.Payload.Commands.Devices()
deviceObject.id = deviceJson.getString("id")
if (deviceJson.has("customData")) {
deviceObject.customData = deviceJson.getJSONObject("customData").toMap()
}
devicesList.add(deviceObject)
}
val executionsList = ArrayList<ExecuteRequest.Inputs.Payload.Commands.Execution>()
val executionsJsonArray = commandsJsonArray.getJSONObject(i).getJSONArray("execution")
for (j in 0 until executionsJsonArray.length()) {
val executionJson = executionsJsonArray.getJSONObject(j)
val executionObject = ExecuteRequest.Inputs.Payload.Commands.Execution()
executionObject.command = executionJson.getString("command")
if (executionJson.has("params")) {
executionObject.params = executionJson.getJSONObject("params").toMap()
}
executionObject.challenge =
executionJson.optJSONObject("challenge")?.toMap()
executionsList.add(executionObject)
}
val command = ExecuteRequest.Inputs.Payload.Commands()
val devicesArray = arrayOfNulls<ExecuteRequest.Inputs.Payload.Commands.Devices>(devicesList.size)
command.devices = devicesList.toArray(devicesArray)
val executionArray = arrayOfNulls<ExecuteRequest.Inputs.Payload.Commands.Execution>(executionsList.size)
command.execution = executionsList.toArray(executionArray)
commandsList.add(command)
}
val commandsArray = arrayOfNulls<ExecuteRequest.Inputs.Payload.Commands>(commandsList.size)
(executeRequest.inputs[0] as ExecuteRequest.Inputs).payload.commands = commandsList.toArray(commandsArray)
return executeRequest
}
DISCON_INTENT -> {
val disconnectRequest = DisconnectRequest()
disconnectRequest.requestId = requestId
disconnectRequest.inputs = arrayOf(DisconnectRequest.Inputs())
disconnectRequest.inputs[0].intent = intent
return disconnectRequest
}
else -> throw IllegalArgumentException("Unable to process request")
}
}
private const val SYNC_INTENT: String = "action.devices.SYNC"
private const val QUERY_INTENT: String = "action.devices.QUERY"
private const val EXEC_INTENT: String = "action.devices.EXECUTE"
private const val DISCON_INTENT: String = "action.devices.DISCONNECT"
}
}
/**
* A representation of the JSON payload received during an action.devices.SYNC request.
*
* @see <a href="https://developers.google.com/actions/smarthome/develop/process-intents#request_format">Public documentation</a>
*/
class SyncRequest : SmartHomeRequest() {
class Inputs : RequestInputs()
}
/**
* A representation of the JSON payload received during an action.devices.QUERY request.
*
* @see <a href="https://developers.google.com/actions/smarthome/develop/process-intents#request_format_2">Public documentation</a>
*/
class QueryRequest : SmartHomeRequest() {
class Inputs : RequestInputs() {
lateinit var payload: Payload
class Payload {
lateinit var devices: Array<Device>
class Device {
lateinit var id: String
var customData: Map<String, kotlin.Any>? = null
}
}
}
}
/**
* A representation of the JSON payload received during an action.devices.EXECUTE request.
*
* @see <a href="https://developers.google.com/actions/smarthome/develop/process-intents#request_format_3">Public documentation</a>
*/
class ExecuteRequest : SmartHomeRequest() {
class Inputs : RequestInputs() {
lateinit var payload: Payload
class Payload {
lateinit var commands: Array<Commands>
class Commands {
lateinit var devices: Array<Devices>
lateinit var execution: Array<Execution>
class Devices {
lateinit var id: String
var customData: Map<String, kotlin.Any>? = null
}
class Execution {
lateinit var command: String
var params: Map<String, kotlin.Any>? = null
var challenge: Map<String, kotlin.Any>? = null
}
}
}
}
}
/**
* A representation of the JSON payload received during an action.devices.DISCONNECT request.
*
* @see <a href="https://developers.google.com/actions/smarthome/develop/process-intents#request_format_4">Public documentation</a>
*/
class DisconnectRequest : SmartHomeRequest() {
class Inputs : RequestInputs()
}
| 27
|
Kotlin
|
40
| 286
|
3d9f62beb8a8ff98844528badcea9ebaaed559cc
| 9,739
|
actions-on-google-java
|
Apache License 2.0
|
app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/LinearVerticalActivity.kt
|
TakWolf
| 92,882,038
| false
| null |
package com.takwolf.android.demo.hfrecyclerview.ui.activity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.takwolf.android.demo.hfrecyclerview.R
import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityRecyclerViewBinding
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.LinearVerticalAdapter
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener
import com.takwolf.android.demo.hfrecyclerview.vm.SingleListViewModel
import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView
class LinearVerticalActivity : AppCompatActivity() {
private val viewModel: SingleListViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityRecyclerViewBinding.inflate(layoutInflater)
binding.toolbar.setTitle(R.string.linear_vertical)
binding.toolbar.setNavigationOnClickListener {
finish()
}
binding.recyclerView.layoutManager = LinearLayoutManager(this)
viewModel.extraHolder.setupVertical(layoutInflater, binding.recyclerView, binding.hfDashboard)
val adapter = LinearVerticalAdapter(layoutInflater).apply {
onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder)
onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder)
}
binding.recyclerView.adapter = adapter
viewModel.photosHolder.setupView(this, adapter)
setContentView(binding.root)
}
}
| 0
| null |
6
| 40
|
df08fe97aa14985c6e8998e9acf6e75c0ce89817
| 1,740
|
Android-HeaderAndFooterRecyclerView
|
Apache License 2.0
|
app/src/main/java/com/alveteg/simon/minutelauncher/theme/Theme.kt
|
simonalveteg
| 519,161,865
| false
|
{"Kotlin": 109907}
|
package com.example.android.minutelauncher.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MinuteLauncherTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
// Remember a SystemUiController
val systemUiController = rememberSystemUiController()
val useDarkIcons = !darkTheme
SideEffect {
// Update all of the system bar colors to be transparent, and use
// dark icons if we're in light theme
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
// setStatusBarColor() and setNavigationBarColor() also exist
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| 9
|
Kotlin
|
1
| 6
|
210285044f7a10fbb848ed8cb489e8f992bc2631
| 2,385
|
Minute-Launcher
|
MIT License
|
library/core/src/main/java/com/michaelflisar/kotpreferences/core/settings/AnyLongSetting.kt
|
MFlisar
| 705,564,357
| false
|
{"Kotlin": 61309}
|
package com.michaelflisar.kotpreferences.core.settings
import com.michaelflisar.kotpreferences.core.SettingsConverter
import com.michaelflisar.kotpreferences.core.SettingsModel
import com.michaelflisar.kotpreferences.core.interfaces.Storage
import com.michaelflisar.kotpreferences.core.interfaces.StorageSetting
import kotlinx.coroutines.flow.map
import kotlin.reflect.KProperty
abstract class BaseAnyLongSetting<T : Any?>(
private val model: SettingsModel,
override val defaultValue: T,
override val customKey: String?,
val converter: SettingsConverter<T, Long>,
override val cache: Boolean
) : AbstractSetting<T>() {
private var name: String? = null
override val key: String by lazy { customKey ?: name!! }
override val storage: Storage
get() = model.storage
override fun createFlow() =
model.storage.getLong(key, converter.to(defaultValue)).map { converter.from(it) }
override suspend fun persistValue(value: T) {
model.storage.setLong(key, converter.to(value))
}
private fun init(name: String) {
if (this.name == null) {
this.name = name
model.internalProperties[key] = this
}
}
/* Delegate */
override fun getValue(
thisRef: SettingsModel,
property: KProperty<*>
): StorageSetting<T> {
init(property.name)
return this
}
}
class AnyLongSetting<T : Any>(
model: SettingsModel,
defaultValue: T,
customKey: String?,
converter: SettingsConverter<T, Long>,
cache: Boolean
) : BaseAnyLongSetting<T>(model, defaultValue, customKey, converter, cache)
class NullableAnyLongSetting<T : Any?>(
model: SettingsModel,
defaultValue: T,
customKey: String?,
converter: SettingsConverter<T, Long>,
cache: Boolean
) : BaseAnyLongSetting<T>(model, defaultValue, customKey, converter, cache)
| 0
|
Kotlin
|
0
| 2
|
20897414d61c163fc7019a0bd7e9f4a9950ffdaa
| 1,889
|
KotPreferences
|
Apache License 2.0
|
app/src/test/java/org/listenbrainz/android/SearchViewModelTest.kt
|
metabrainz
| 550,726,972
| false
| null |
package org.listenbrainz.android
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.listenbrainz.android.model.ResponseError
import org.listenbrainz.android.model.User
import org.listenbrainz.android.repository.social.SocialRepository
import org.listenbrainz.android.util.Resource
import org.listenbrainz.android.viewmodel.SearchViewModel
import org.listenbrainz.sharedtest.testdata.SocialRepositoryTestData.ErrorUtil.alreadyFollowingError
import org.listenbrainz.sharedtest.testdata.SocialRepositoryTestData.ErrorUtil.cannotFollowSelfError
import org.listenbrainz.sharedtest.testdata.SocialRepositoryTestData.testFollowUnfollowSuccessResponse
import org.listenbrainz.sharedtest.testdata.SocialRepositoryTestData.testSearchResult
import org.listenbrainz.sharedtest.utils.EntityTestUtils.testFamiliarUser
import org.listenbrainz.sharedtest.utils.EntityTestUtils.testSomeOtherUser
import org.listenbrainz.sharedtest.utils.EntityTestUtils.testUsername
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.wheneverBlocking
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(MockitoJUnitRunner::class)
class SearchViewModelTest : BaseUnitTest() {
private lateinit var viewModel : SearchViewModel
@Mock
private lateinit var mockSocialRepository: SocialRepository
@Before
fun setup(){
// Search response mock
wheneverBlocking {
mockSocialRepository.searchUser(testUsername)
}.thenReturn(Resource.success(testSearchResult))
// Unfollow some other user mock
wheneverBlocking {
mockSocialRepository.unfollowUser(testSomeOtherUser)
}.thenReturn(Resource.success(testFollowUnfollowSuccessResponse))
// User tries to follow some unknown user.
wheneverBlocking {
mockSocialRepository.followUser(testSomeOtherUser)
}.thenReturn(Resource.success(testFollowUnfollowSuccessResponse))
// User tries to follow an already followed user.
wheneverBlocking {
mockSocialRepository.followUser(testFamiliarUser)
}.doReturn(Resource.failure(error = ResponseError.BAD_REQUEST.apply { actualResponse = alreadyFollowingError }))
viewModel = SearchViewModel(mockSocialRepository, testDispatcher(), testDispatcher())
}
@Test
fun `test if query is updated`() = test {
makeQueryAndAssert()
}
@Test
fun `test if query is cleared`() = test {
makeQueryAndAssert()
advanceUntilIdle()
clearQueryAndAssert()
}
@Test
fun `test if follow or unfollow request is executed correctly`() = test {
makeQueryAndAssert()
.toggleFollowStatus(testSomeOtherUser, this)
.assertFollowStatusChanged(testSomeOtherUser, expected = true)
.toggleFollowStatus(testSomeOtherUser,this)
.assertFollowStatusChanged(testSomeOtherUser, expected = false)
}
@Test
fun `test error flow is updated`() = test {
// User tries to follow self.
wheneverBlocking {
mockSocialRepository.followUser(testUsername)
}.doReturn(Resource.failure(error = ResponseError.BAD_REQUEST.apply { actualResponse = cannotFollowSelfError }))
makeQueryAndAssert()
.toggleFollowStatus(testUsername, this)
// Expected is false here because testUsername is user itself.
.assertFollowStatusChanged(testUsername, expected = false)
.assertErrorFlowChanged()
}
@Test
fun `test if state remains unchanged on already following error and error flow is updated`() = test {
makeQueryAndAssert()
.toggleFollowStatus(testFamiliarUser, this)
// Expected is true here even though initial state is false because testFamiliarUser is already being followed
// and our UI states should remain true to actual data.
.assertFollowStatusChanged(testFamiliarUser, expected = true)
.assertErrorFlowChanged()
}
private fun makeQueryAndAssert() : SearchViewModelTest {
viewModel.updateQueryFlow(testUsername)
assertEquals(viewModel.uiState.value.query, testUsername)
return this
}
private fun clearQueryAndAssert() : SearchViewModelTest {
viewModel.clearUi()
assertEquals(viewModel.uiState.value.query, "")
return this
}
private suspend fun toggleFollowStatus(user: String, testScope: TestScope) : SearchViewModelTest {
testScope.advanceUntilIdle()
viewModel.toggleFollowStatus(User(user), getIndex(user))
return this
}
private fun assertFollowStatusChanged(user: String, expected: Boolean) : SearchViewModelTest {
val index = getIndex(user)
assertEquals(user, viewModel.uiState.value.result.userList[index].username)
assertEquals(expected, viewModel.uiState.value.result.isFollowedList[index])
return this
}
private fun assertErrorFlowChanged() : SearchViewModelTest {
assertEquals(viewModel.uiState.value.error, ResponseError.BAD_REQUEST)
return this
}
private fun getIndex(user: String): Int {
return when(user){
testUsername -> 0
testFamiliarUser -> 1
testSomeOtherUser -> 2
else -> throw IndexOutOfBoundsException()
}
}
}
| 25
| null |
31
| 99
|
573ab0ec6c5b87ea963f013174159ddfcd123976
| 5,728
|
listenbrainz-android
|
Apache License 2.0
|
brd-android/app/src/main/java/com/breadwallet/ui/provekey/PaperKeyProveController.kt
|
rockwalletcode
| 551,321,635
| false
|
{"Kotlin": 2861608, "Java": 486902, "HTML": 12258}
|
/**
* BreadWallet
*
* Created by Pablo Budelli <pablo.budelli@breadwallet.com> on 10/10/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.provekey
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import com.breadwallet.R
import com.breadwallet.databinding.ControllerPaperKeyProveBinding
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.flowbind.textChanges
import com.breadwallet.ui.navigation.OnCompleteAction
import com.breadwallet.ui.provekey.PaperKeyProve.E
import com.breadwallet.ui.provekey.PaperKeyProve.F
import com.breadwallet.ui.provekey.PaperKeyProve.M
import com.breadwallet.util.normalize
import com.rockwallet.common.utils.RockWalletToastUtil
import com.rockwallet.common.utils.showErrorState
import drewcarlson.mobius.flow.FlowTransformer
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
private const val EXTRA_PHRASE = "phrase"
private const val EXTRA_ON_COMPLETE = "on-complete"
class PaperKeyProveController(args: Bundle) :
BaseMobiusController<M, E, F>(args) {
constructor(phrase: List<String>, onComplete: OnCompleteAction) : this(
bundleOf(
EXTRA_PHRASE to phrase,
EXTRA_ON_COMPLETE to onComplete.name
)
)
private val phrase: List<String> = arg(EXTRA_PHRASE)
private val onComplete = OnCompleteAction.valueOf(arg(EXTRA_ON_COMPLETE))
override val defaultModel = M.createDefault(phrase, onComplete)
override val update = PaperKeyProveUpdate
override val flowEffectHandler: FlowTransformer<F, E>
get() = createPaperKeyProveHandler()
private val binding by viewBinding(ControllerPaperKeyProveBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return with(binding) {
merge(
btnFaq.clicks().map { E.OnFaqClicked },
btnBack.clicks().map { E.OnBackClicked },
btnGotIt.clicks().map { E.OnGotItClicked },
etWord1.textChanges().map { E.OnFirstWordChanged(it.normalize().trim()) },
etWord2.textChanges().map { E.OnSecondWordChanged(it.normalize().trim()) }
)
}
}
override fun onDetach(view: View) {
super.onDetach(view)
Utils.hideKeyboard(activity)
}
override fun M.render() {
with(binding) {
ifChanged (M::gotItButtonEnabled) {
btnGotIt.isEnabled = it
}
ifChanged(M::firstWordState) {
tilWord1.showErrorState(
errorState = it == M.WordState.INVALID,
errorIcon = R.drawable.ic_input_field_error
)
}
ifChanged(M::secondWordSate) {
tilWord2.showErrorState(
errorState = it == M.WordState.INVALID,
errorIcon = R.drawable.ic_input_field_error
)
}
ifChanged(M::firstWordIndex) {
tilWord1.hint =
activity!!.getString(R.string.ConfirmPaperPhrase_word, firstWordIndex + 1)
}
ifChanged(M::secondWordIndex) {
tilWord2.hint =
activity!!.getString(R.string.ConfirmPaperPhrase_word, secondWordIndex + 1)
}
}
}
override fun handleViewEffect(effect: ViewEffect) {
when (effect) {
is F.ShowError ->
RockWalletToastUtil.showError(
parentView = binding.root,
message = activity!!.getString(R.string.RecoveryKeyFlow_confirmRecoveryInputError)
)
}
}
}
| 9
|
Kotlin
|
2
| 0
|
24b84f3d91a08c2d9f1233aa35db175e6102bd54
| 4,934
|
wallet-android
|
MIT License
|
app/src/main/java/com/app/quotify/feature_quote/presentation/quotes/components/quote_ui/QuoteItem.kt
|
shivam-gupta007
| 510,800,553
| false
|
{"Kotlin": 55709}
|
package com.app.quotify.feature_quote.presentation.quotes.components.quote_ui
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.app.quotify.R
import com.app.quotify.feature_quote.domain.model.Quote
import com.app.quotify.feature_quote.presentation.navigation.BottomBarScreen
import com.app.quotify.ui.theme.Shapes
import com.app.quotify.ui.theme.iconColor
import com.app.quotify.ui.theme.purple
@ExperimentalMaterial3Api
@Composable
fun QuoteItem(
modifier: Modifier = Modifier,
quote: Quote,
@DrawableRes drawable: Int = R.drawable.placeholder,
onClick: () -> Unit
) {
val offset = Offset(0.0f, 0.0f)
Card(
modifier = modifier
.clickable {
onClick()
},
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant
),
shape = Shapes.medium
) {
Box(
contentAlignment = Alignment.Center
) {
AsyncImage(
modifier = Modifier
.fillMaxWidth()
.height(500.dp)
.background(Color.Black)
.alpha(0.6f),
contentScale = ContentScale.Crop,
model = ImageRequest.Builder(LocalContext.current)
.data(quote.quoteImgUrl)
.placeholder(drawable)
.allowHardware(false)
//.error(R.drawable.error)
.build(),
contentDescription = stringResource(R.string.description),
)
Column(
modifier = Modifier
.padding(
top = 70.dp,
end = 30.dp,
start = 30.dp,
bottom = 25.dp
),
verticalArrangement = Arrangement.Center,
) {
Text(
text = quote.quoteContent.uppercase(),
style = MaterialTheme.typography.headlineSmall.copy(
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.SansSerif,
shadow = Shadow(
color = Color.Black,
offset = offset,
blurRadius = 10f
)
),
color = Color.White
)
Spacer(
modifier = Modifier
.height(80.dp)
.fillMaxWidth()
)
Text(
text = quote.quoteAuthor,
style = MaterialTheme.typography.bodyLarge.copy(
fontFamily = FontFamily.SansSerif,
shadow = Shadow(
color = Color.Black,
offset = offset,
blurRadius = 25f
)
),
color = Color.White
)
}
}
}
}
@Composable
fun ButtonsGroup(
modifier: Modifier = Modifier,
screen: BottomBarScreen,
onClick: (ImageVector) -> Unit
) {
val iconsList = arrayListOf(
if (screen.route == BottomBarScreen.Home.route)
Icons.Outlined.FavoriteBorder
else
Icons.Filled.Favorite,
Icons.Outlined.Share,
Icons.Filled.ContentCopy
)
Row(
modifier = modifier
.fillMaxWidth()
.padding(top = 16.dp, bottom = 30.dp),
horizontalArrangement = Arrangement.SpaceAround,
){
iconsList.forEach{ icon ->
Icon(
modifier = Modifier
.clickable {
onClick(icon)
}
.clip(RoundedCornerShape(10.dp))
.background(iconColor)
.padding(10.dp),
imageVector = icon,
tint = purple,
contentDescription = null
)
}
}
}
@ExperimentalMaterial3Api
@Preview(showBackground = true)
@Composable
fun QuoteItemPreview() {
QuoteItem(
quote = Quote(
quoteId = "",
quoteContent = "You don't get what you want. You only get what you are",
quoteAuthor = "<NAME>",
quoteImgUrl = ""
),
onClick = {}
)
}
| 0
|
Kotlin
|
0
| 3
|
94664898142eae219b1d3784c8b3b94d947cd0b1
| 5,801
|
Quotify
|
MIT License
|
app/src/main/java/com/app/quotify/feature_quote/presentation/quotes/components/quote_ui/QuoteItem.kt
|
shivam-gupta007
| 510,800,553
| false
|
{"Kotlin": 55709}
|
package com.app.quotify.feature_quote.presentation.quotes.components.quote_ui
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.app.quotify.R
import com.app.quotify.feature_quote.domain.model.Quote
import com.app.quotify.feature_quote.presentation.navigation.BottomBarScreen
import com.app.quotify.ui.theme.Shapes
import com.app.quotify.ui.theme.iconColor
import com.app.quotify.ui.theme.purple
@ExperimentalMaterial3Api
@Composable
fun QuoteItem(
modifier: Modifier = Modifier,
quote: Quote,
@DrawableRes drawable: Int = R.drawable.placeholder,
onClick: () -> Unit
) {
val offset = Offset(0.0f, 0.0f)
Card(
modifier = modifier
.clickable {
onClick()
},
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant
),
shape = Shapes.medium
) {
Box(
contentAlignment = Alignment.Center
) {
AsyncImage(
modifier = Modifier
.fillMaxWidth()
.height(500.dp)
.background(Color.Black)
.alpha(0.6f),
contentScale = ContentScale.Crop,
model = ImageRequest.Builder(LocalContext.current)
.data(quote.quoteImgUrl)
.placeholder(drawable)
.allowHardware(false)
//.error(R.drawable.error)
.build(),
contentDescription = stringResource(R.string.description),
)
Column(
modifier = Modifier
.padding(
top = 70.dp,
end = 30.dp,
start = 30.dp,
bottom = 25.dp
),
verticalArrangement = Arrangement.Center,
) {
Text(
text = quote.quoteContent.uppercase(),
style = MaterialTheme.typography.headlineSmall.copy(
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.SansSerif,
shadow = Shadow(
color = Color.Black,
offset = offset,
blurRadius = 10f
)
),
color = Color.White
)
Spacer(
modifier = Modifier
.height(80.dp)
.fillMaxWidth()
)
Text(
text = quote.quoteAuthor,
style = MaterialTheme.typography.bodyLarge.copy(
fontFamily = FontFamily.SansSerif,
shadow = Shadow(
color = Color.Black,
offset = offset,
blurRadius = 25f
)
),
color = Color.White
)
}
}
}
}
@Composable
fun ButtonsGroup(
modifier: Modifier = Modifier,
screen: BottomBarScreen,
onClick: (ImageVector) -> Unit
) {
val iconsList = arrayListOf(
if (screen.route == BottomBarScreen.Home.route)
Icons.Outlined.FavoriteBorder
else
Icons.Filled.Favorite,
Icons.Outlined.Share,
Icons.Filled.ContentCopy
)
Row(
modifier = modifier
.fillMaxWidth()
.padding(top = 16.dp, bottom = 30.dp),
horizontalArrangement = Arrangement.SpaceAround,
){
iconsList.forEach{ icon ->
Icon(
modifier = Modifier
.clickable {
onClick(icon)
}
.clip(RoundedCornerShape(10.dp))
.background(iconColor)
.padding(10.dp),
imageVector = icon,
tint = purple,
contentDescription = null
)
}
}
}
@ExperimentalMaterial3Api
@Preview(showBackground = true)
@Composable
fun QuoteItemPreview() {
QuoteItem(
quote = Quote(
quoteId = "",
quoteContent = "You don't get what you want. You only get what you are",
quoteAuthor = "<NAME>",
quoteImgUrl = ""
),
onClick = {}
)
}
| 0
|
Kotlin
|
0
| 3
|
94664898142eae219b1d3784c8b3b94d947cd0b1
| 5,801
|
Quotify
|
MIT License
|
reto08/Reto8/app/src/main/java/co/edu/unal/reto8/contact/ContactDao.kt
|
anromerom
| 290,949,827
| false
| null |
package co.edu.unal.reto8.contact
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface ContactDao {
// CREATE
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertContact(contact : Contact)
// READ
@Query("SELECT * FROM contact_table ORDER BY name ASC")
fun getAllContactsAlphabetic(): LiveData<List<Contact>>
@Query("SELECT * FROM contact_table WHERE type = :type ORDER BY name ASC ")
fun getAllContactsOfType(type : String): LiveData<List<Contact>>
// UPDATE
@Update
suspend fun updateContact(contact: Contact)
@Delete
suspend fun deleteContact(contact: Contact)
@Query("DELETE FROM contact_table")
suspend fun deleteAll()
}
| 1
| null |
1
| 1
|
c560c2eb1d5bbdc9868504299759f0d08220d403
| 732
|
DADM_2020
|
MIT License
|
reto08/Reto8/app/src/main/java/co/edu/unal/reto8/contact/ContactDao.kt
|
anromerom
| 290,949,827
| false
| null |
package co.edu.unal.reto8.contact
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface ContactDao {
// CREATE
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertContact(contact : Contact)
// READ
@Query("SELECT * FROM contact_table ORDER BY name ASC")
fun getAllContactsAlphabetic(): LiveData<List<Contact>>
@Query("SELECT * FROM contact_table WHERE type = :type ORDER BY name ASC ")
fun getAllContactsOfType(type : String): LiveData<List<Contact>>
// UPDATE
@Update
suspend fun updateContact(contact: Contact)
@Delete
suspend fun deleteContact(contact: Contact)
@Query("DELETE FROM contact_table")
suspend fun deleteAll()
}
| 1
| null |
1
| 1
|
c560c2eb1d5bbdc9868504299759f0d08220d403
| 732
|
DADM_2020
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/NorthEast.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/NorthEast")
package mui.icons.material
@JsName("default")
external val NorthEast: SvgIconComponent
| 12
| null |
5
| 983
|
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
| 182
|
kotlin-wrappers
|
Apache License 2.0
|
Mobile/SimplexLudum/composeApp/src/commonMain/kotlin/palbp/laboratory/simplex/domain/GameListsRepository.kt
|
palbp
| 463,200,783
| false
| null |
package palbp.laboratory.simplex.domain
/**
* Type used to represent functions responsible for obtaining game lists.
*/
typealias GetGameLists = suspend () -> List<GameListSummary>
/**
* Type used to represent functions responsible for obtaining the latest games.
*/
typealias GetLatestGames = suspend () -> List<Game>
/**
* Type used to represent functions responsible for obtaining a game list with the
* given filtering query.
*/
typealias GetGameListWithQuery = suspend (String) -> List<Game>
| 1
| null |
0
| 5
|
9067753258a6a71bcd79cd59401edd58df66db71
| 507
|
laboratory
|
MIT License
|
BusSatriaAppDriver/app/src/main/java/com/bussatriaappdriver/component/PageIndicator.kt
|
RanggaNf
| 834,310,436
| false
|
{"Kotlin": 404583}
|
package com.bussatriaapp.component
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.bussatriaapp.ui.theme.onSurface
import com.bussatriaapp.ui.theme.surface
@Composable
fun PageIndicator(
numberOfPages: Int,
selectedPage: Int = 0,
isDarkTheme: Boolean = false,
defaultColor: Color = Color.Gray,
defaultRadius: Dp = 8.dp,
selectedLength: Dp = 25.dp,
space: Dp = 4.dp,
modifier: Modifier = Modifier
) {
val isDarkTheme = isSystemInDarkTheme()
val selectedColor = if (isDarkTheme) surface else onSurface
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(space),
modifier = modifier
) {
repeat(numberOfPages) {
Indicator(
isSelected = it == selectedPage,
selectedColor = selectedColor,
defaultColor = defaultColor,
defaultRadius = defaultRadius,
selectedLength = selectedLength,
)
}
}
}
@Preview
@Composable
fun PageIndicatorPreview() {
val numberOfPages = 5 // Change as needed
val selectedPage = 2 // Change as needed
val isDarkTheme = false // Change to true to see the dark theme effect
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
PageIndicator(
numberOfPages = numberOfPages,
selectedPage = selectedPage,
isDarkTheme = isDarkTheme
)
}
}
@Composable
fun Indicator(
isSelected: Boolean,
selectedColor: Color,
defaultColor: Color,
defaultRadius: Dp,
selectedLength: Dp,
modifier: Modifier = Modifier.height(defaultRadius)
) {
val width by animateDpAsState(
targetValue = if (isSelected) selectedLength else defaultRadius,
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)
)
Box(
modifier = modifier
.width(width)
.clip(CircleShape)
.background(color = if (isSelected) selectedColor else defaultColor)
)
}
| 0
|
Kotlin
|
0
| 1
|
7046f6b382f7d0797c8ffeeebcacc2592671b0f5
| 3,228
|
Bus-Satria-App
|
MIT License
|
favourite/src/main/java/com/dicoding/dummyfilmapp/favourite/ui/fragment/TvShowFavouriteFragment.kt
|
r3dz0n3-plysafe
| 391,220,918
| false
| null |
package com.dicoding.dummyfilmapp.favourite.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.dicoding.dummyfilmapp.core.ui.TvShowListAdapter
import com.dicoding.dummyfilmapp.core.ui.utils.ViewBindingHolder
import com.dicoding.dummyfilmapp.core.ui.utils.ViewBindingHolderImpl
import com.dicoding.dummyfilmapp.favourite.databinding.FragmentTvShowFavouriteBinding
import com.dicoding.dummyfilmapp.favourite.ui.FavouriteViewModel
import com.dicoding.dummyfilmapp.ui.DetailFilmActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
class TvShowFavouriteFragment : Fragment(),
ViewBindingHolder<FragmentTvShowFavouriteBinding> by ViewBindingHolderImpl() {
private lateinit var tvShowFavListAdapter: TvShowListAdapter
private val favouriteViewModel: FavouriteViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = initBinding(FragmentTvShowFavouriteBinding.inflate(layoutInflater), this) {
if (activity != null) {
showLoading()
tvShowFavListAdapter = TvShowListAdapter()
tvShowFavListAdapter.onItemClick = { movie ->
Intent(context, DetailFilmActivity::class.java).also {
it.putExtra(DetailFilmActivity.EXTRAS_DATA, movie)
it.putExtra(DetailFilmActivity.EXTRAS_SELECTED, "TV_SHOW")
startActivity(it)
}
}
favouriteViewModel.tvShowFav.observe(viewLifecycleOwner, {
showLoading(false)
tvShowFavListAdapter.setData(it)
tvEmpty.visibility =
if (it.isNotEmpty()) View.GONE else View.VISIBLE
})
setRecyclerView()
}
}
private fun setRecyclerView() = requireBinding {
with(rvTvFav) {
layoutManager = GridLayoutManager(context, 2)
setHasFixedSize(true)
adapter = tvShowFavListAdapter
}
}
private fun showLoading(state: Boolean = true) = requireBinding {
apply {
if (state) pbLoading.visibility =
View.VISIBLE else pbLoading.visibility = View.GONE
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e60dc3657296f4e1e8d705d1543f110dc644e27f
| 2,471
|
Sub2-Expert-DummyFilmApp
|
The Unlicense
|
app/src/main/java/vtsen/hashnode/dev/androidnews/data/utils/ArticleRepoUtils.kt
|
vinchamp77
| 455,775,581
| false
|
{"Kotlin": 172657}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vtsen.hashnode.dev.androidnews.data.utils
import vtsen.hashnode.dev.androidnews.data.repository.ArticleRepo
import java.util.Date
object ArticleRepoUtils {
fun makeFakeArticles(): List<ArticleRepo> {
val articles: MutableList<ArticleRepo> = mutableListOf()
repeat(10) {
articles.add(createArticle())
}
return articles
}
fun createArticle(): ArticleRepo {
return ArticleRepo(
id = "how-to-implement-hilt-in-android-app",
title = "How to Implement Hilt in Android App?",
link = "https://vtsen.hashnode.dev/how-to-implement-hilt-in-android-app",
pubDate = Date().time,
image = "https://cdn.hashnode.com/res/hashnode/image/upload/v1643788167289/tf0hGfYSO.jpeg",
feedTitle = "Android Kotlin Weekly",
author = "<NAME>",
)
}
}
| 18
|
Kotlin
|
11
| 62
|
992c997733a3495bfa09977c6f6329e77b415e5d
| 1,477
|
AndroidNews
|
Apache License 2.0
|
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/pay_button/PayButton.kt
|
mercadopago
| 49,529,486
| false
| null |
package com.mercadopago.android.px.internal.features.pay_button
import com.mercadopago.android.px.internal.callbacks.PaymentServiceHandler
import com.mercadopago.android.px.internal.features.explode.ExplodingFragment
import com.mercadopago.android.px.model.IPaymentDescriptor
import com.mercadopago.android.px.model.PaymentRecovery
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.model.internal.PaymentConfiguration
import com.mercadopago.android.px.tracking.internal.model.ConfirmData
interface PayButton {
interface View : ExplodingFragment.ExplodingAnimationListener {
fun handlePaymentRecovery(paymentRecovery: PaymentRecovery)
fun isExploding(): Boolean
fun stimulate()
fun enable()
fun disable()
}
interface ViewModel : PaymentServiceHandler {
fun attach(handler: Handler)
fun detach()
fun preparePayment()
fun handleBiometricsResult(isSuccess: Boolean)
fun startPayment()
fun hasFinishPaymentAnimation()
fun recoverPayment()
fun recoverPayment(recovery: PaymentRecovery)
}
interface Handler {
fun prePayment(callback: OnReadyForPaymentCallback)
@JvmDefault fun enqueueOnExploding(callback: OnEnqueueResolvedCallback) { callback.success() }
fun onPaymentFinished(payment: IPaymentDescriptor)
fun onPaymentError(error: MercadoPagoError)
}
interface OnReadyForPaymentCallback {
fun call(paymentConfiguration: PaymentConfiguration, confirmTrackerData: ConfirmData?)
}
interface OnEnqueueResolvedCallback {
fun success()
fun failure()
}
}
| 44
| null |
77
| 98
|
b715075dd4cf865f30f6448f3c00d6e9033a1c21
| 1,701
|
px-android
|
MIT License
|
app/src/main/java/ru/divar/socprotection/ui/calculator/ChildrenCountPickerFragment.kt
|
BrightOS
| 410,199,584
| false
| null |
package ru.divar.socprotection.ui.calculator
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.transition.MaterialSharedAxis
import kotlinx.android.synthetic.main.fragment_children_count.*
import ru.divar.socprotection.App
import ru.divar.socprotection.R
import ru.divar.socprotection.data.PreferenceRepository
import ru.divar.socprotection.epoxy.age.ChildrenController
class ChildrenCountPickerFragment : Fragment(R.layout.fragment_children_count) {
private lateinit var preferenceRepository: PreferenceRepository
private lateinit var childrenController: ChildrenController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
preferenceRepository = (activity?.application as App).preferenceRepository
exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true)
reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)
returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val counts = arrayListOf<Int>()
if (!this::childrenController.isInitialized)
childrenController = ChildrenController(preferenceRepository)
children_recycler?.layoutManager =
LinearLayoutManager(
context
)
for (i in -1..100) {
counts.add(i)
}
childrenController.items = counts
children_recycler?.apply {
adapter = childrenController.adapter
setHasFixedSize(false)
scrollToPosition(2)
}
go.setOnClickListener { goNext() }
arrow_next.setOnClickListener { goNext() }
arrow_back.setOnClickListener { findNavController().popBackStack() }
}
private fun goNext() {
findNavController().navigate(
ChildrenCountPickerFragmentDirections.actionChildrenCountPickerFragmentToEngagedPickerFragment()
)
}
}
| 0
|
Kotlin
|
0
| 1
|
0e361407322777e3f317e49256afb5b20fdb8f84
| 2,308
|
SocialProtectionDivar
|
Apache License 2.0
|
app/src/main/java/com/breezefieldsalesversacorp/features/location/shopRevisitStatus/ShopRevisitStatusApi.kt
|
DebashisINT
| 855,745,768
| false
|
{"Kotlin": 15888573, "Java": 1028548}
|
package com.breezefieldsalesversacorp.features.location.shopRevisitStatus
import com.breezefieldsalesversacorp.app.NetworkConstant
import com.breezefieldsalesversacorp.base.BaseResponse
import com.breezefieldsalesversacorp.features.location.model.ShopDurationRequest
import com.breezefieldsalesversacorp.features.location.model.ShopRevisitStatusRequest
import com.breezefieldsalesversacorp.features.location.shopdurationapi.ShopDurationApi
import io.reactivex.Observable
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
interface ShopRevisitStatusApi {
@POST("Shopsubmission/OrderNotTakenReason")
fun submShopRevisitStatus(@Body shopRevisitStatus: ShopRevisitStatusRequest?): Observable<BaseResponse>
companion object Factory {
fun create(): ShopRevisitStatusApi {
val retrofit = Retrofit.Builder()
.client(NetworkConstant.setTimeOutNoRetry())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(NetworkConstant.BASE_URL)
.build()
return retrofit.create(ShopRevisitStatusApi::class.java)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ce77cb38df5798e0751dd5163378f778c856d95c
| 1,366
|
VERSACORP
|
Apache License 2.0
|
src/main/kotlin/com/fintecsystems/xs2a/java/models/risk/MatchType.kt
|
FinTecSystems
| 399,112,589
| false
|
{"Kotlin": 248672}
|
package com.fintecsystems.xs2a.java.models.risk
import com.squareup.moshi.Json
@Suppress("unused")
enum class MatchType(var value: String) {
@Json(name = "NONE")
NONE("NONE"),
@Json(name = "LAST_NAME")
LAST_NAME("LAST_NAME"),
@Json(name = "PERSON")
PERSON("PERSON"),
@Json(name = "COMPANY")
COMPANY("COMPANY");
override fun toString() = value
}
| 0
|
Kotlin
|
3
| 3
|
d34d9359857f362840f07a1c0c70789537dc90aa
| 386
|
xs2a-java
|
MIT License
|
src/main/kotlin/com/antwerkz/bottlerocket/configuration/types/DiagnosticLog.kt
|
evanchooly
| 36,263,772
| false
| null |
package com.antwerkz.bottlerocket.configuration.types
enum class DiagnosticLog(val level: Int) {
NONE(0),
WRITE(1),
READ(2),
READ_AND_WRITE(3),
WRITE_AND_SOME_READ(7);
override fun toString(): String {
return level.toString()
}
}
| 5
|
Kotlin
|
1
| 2
|
c83adbbfecbac4327defa6da4ecb30fde0d60884
| 268
|
bottlerocket
|
Apache License 2.0
|
src/main/kotlin/de/marcphilipp/gradle/nexus/NexusRepositoryContainer.kt
|
marcphilipp
| 156,114,106
| false
|
{"Gradle Kotlin DSL": 6, "Shell": 2, "Text": 2, "Ignore List": 2, "Batchfile": 2, "YAML": 1, "Markdown": 2, "Java": 2, "INI": 2, "Kotlin": 11}
|
/*
* Copyright 2019 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 de.marcphilipp.gradle.nexus
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
interface NexusRepositoryContainer : NamedDomainObjectContainer<NexusRepository> {
fun sonatype(): NexusRepository
fun sonatype(closure: Closure<*>): NexusRepository
fun sonatype(action: Action<in NexusRepository>): NexusRepository
}
| 0
|
Kotlin
|
9
| 39
|
fc6dbaf3f10df2fbab322e2706b7a5c2d81e573c
| 1,006
|
nexus-publish-plugin
|
Apache License 2.0
|
modules/library-ui/src/main/kotlin/com/leinardi/forlago/library/ui/component/CoilImage.kt
|
leinardi
| 405,185,933
| false
| null |
/*
* Copyright 2023 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.leinardi.forlago.library.ui.component
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.DefaultAlpha
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import com.leinardi.forlago.library.ui.component.placeholder.placeholder
@Suppress("ModifierReused", "ModifierNotUsedAtRoot")
@Composable
fun CoilImage(
url: String?,
contentDescription: String?,
modifier: Modifier = Modifier,
crossfade: Boolean = true,
error: @Composable (() -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Crop,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
placeholder: Boolean = false,
) {
if (placeholder) {
Box(modifier = modifier.placeholder(true)) {}
} else {
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(url)
.crossfade(crossfade)
.build(),
loading = { Box(modifier = modifier.placeholder(true)) {} },
error = { error?.invoke() },
contentDescription = contentDescription,
modifier = modifier,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
)
}
}
| 3
| null |
3
| 9
|
abe5eb3017f3365bbb1b61e74f2ef8f34097d411
| 2,229
|
Forlago
|
Apache License 2.0
|
app/src/main/java/com/muhamadzain/movie_catalog/network/ServiceApi.kt
|
Zainal21
| 571,134,695
| false
|
{"Kotlin": 26154}
|
package com.muhamadzain.movie_catalog.network
import com.muhamadzain.movie_catalog.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
object ServiceApi {
val endpoint : InterfaceApi
get() {
val interceptor= HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(
RxJava2CallAdapterFactory.create())
.client(client)
.build()
return retrofit.create(InterfaceApi::class.java)
}
}
| 0
|
Kotlin
|
0
| 1
|
21a6e13a64c1bd7da5b6a653b215c4ddf24ba9a1
| 1,005
|
Movie-catalog
|
MIT License
|
mobile_app1/module994/src/main/java/module994packageKt0/Foo192.kt
|
uber-common
| 294,831,672
| false
| null |
package module224packageKt0;
annotation class Foo192Fancy
@Foo192Fancy
class Foo192 {
fun foo0(){
module224packageKt0.Foo191().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
}
| 6
|
Java
|
6
| 72
|
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
| 237
|
android-build-eval
|
Apache License 2.0
|
src/main/kotlin/com/github/locxter/btvccntrl/ng/model/Path.kt
|
locxter
| 640,201,341
| false
|
{"Kotlin": 46472}
|
package com.github.locxter.btvccntrl.ng.model
data class Path(
val points: MutableList<Point> = mutableListOf()
)
| 0
|
Kotlin
|
0
| 1
|
de71c6aa13e09df7ef5fed4f3631baccc360633c
| 119
|
btvccntrl-ng
|
MIT License
|
gradle-dsl-kotlin/src/com/android/tools/idea/gradle/dsl/kotlin/KotlinDslNameConverter.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.dsl.parser.kotlin
import com.android.tools.idea.gradle.dsl.model.BuildModelContext
import com.android.tools.idea.gradle.dsl.parser.ExternalNameInfo
import com.android.tools.idea.gradle.dsl.parser.ExternalNameInfo.ExternalNameSyntax.ASSIGNMENT
import com.android.tools.idea.gradle.dsl.parser.ExternalNameInfo.ExternalNameSyntax.AUGMENTED_ASSIGNMENT
import com.android.tools.idea.gradle.dsl.parser.ExternalNameInfo.ExternalNameSyntax.METHOD
import com.android.tools.idea.gradle.dsl.parser.ExternalNameInfo.ExternalNameSyntax.UNKNOWN
import com.android.tools.idea.gradle.dsl.parser.GradleDslNameConverter
import com.android.tools.idea.gradle.dsl.parser.GradleDslNameConverter.Kind.KOTLIN
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslElement
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslSimpleExpression
import com.android.tools.idea.gradle.dsl.parser.elements.GradleNameElement
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import com.android.tools.idea.gradle.dsl.parser.semantics.MethodSemanticsDescription.*
import com.android.tools.idea.gradle.dsl.parser.semantics.ModelPropertyDescription
import com.android.tools.idea.gradle.dsl.parser.semantics.ModelPropertyType.MUTABLE_LIST
import com.android.tools.idea.gradle.dsl.parser.semantics.ModelPropertyType.MUTABLE_MAP
import com.android.tools.idea.gradle.dsl.parser.semantics.ModelPropertyType.MUTABLE_SET
import com.android.tools.idea.gradle.dsl.parser.semantics.PropertySemanticsDescription.*
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import java.util.regex.Pattern
interface KotlinDslNameConverter: GradleDslNameConverter {
override fun getKind() = KOTLIN
override fun psiToName(element: PsiElement): String {
return when (element) {
is KtStringTemplateExpression -> when (val contents = element.literalContents()) {
null -> element.text
else -> GradleNameElement.escape(contents)
}
is KtExpression -> gradleNameFor(element) ?: element.text
else -> element.text
}
}
override fun convertReferenceText(context: GradleDslElement, referenceText: String): String {
var result : String? = null
runReadAction {
val referencePsi = KtPsiFactory(context.dslFile.project, false).createExpression(referenceText)
result = gradleNameFor(referencePsi)
}
return result ?: referenceText
}
override fun convertReferencePsi(context: GradleDslElement, element: PsiElement): String {
return (element as? KtExpression)?.let { gradleNameFor(element) } ?: convertReferenceText(context, element.text)
}
override fun convertReferenceToExternalText(context: GradleDslElement,
referenceText: String,
forInjection: Boolean): String {
return when (context) {
is GradleDslSimpleExpression -> convertToExternalTextValue(context, context.dslFile, referenceText, forInjection)
else -> referenceText
}
}
override fun convertReferenceToExternalText(context: GradleDslElement,
dslElement: GradleDslElement,
forInjection: Boolean): String {
return when (context) {
is GradleDslSimpleExpression -> convertToExternalTextValue(dslElement, context, context.dslFile, forInjection) ?: dslElement.name
else -> dslElement.name
}
}
override fun externalNameForParent(modelName: String, context: GradleDslElement): ExternalNameInfo {
val map = context.getExternalToModelMap(this)
val defaultResult = ExternalNameInfo(modelName, UNKNOWN)
var result : ExternalNameInfo? = null
for (e in map.entrySet) {
if (e.modelEffectDescription.property.name == modelName) {
if (e.versionConstraint?.isOkWith(this.context.agpVersion) == false) continue
// prefer assignment if possible, or otherwise the first appropriate method we find
when (e.modelEffectDescription.semantics) {
VAR, VWO -> return ExternalNameInfo(e.surfaceSyntaxDescription.name, ASSIGNMENT)
SET, ADD_AS_LIST, AUGMENT_LIST, CLEAR_AND_AUGMENT_LIST, AUGMENT_MAP, OTHER ->
if (result == null) result = ExternalNameInfo(e.surfaceSyntaxDescription.name, METHOD)
VAL -> when (e.modelEffectDescription.property.type) {
MUTABLE_SET, MUTABLE_LIST, MUTABLE_MAP -> return ExternalNameInfo(e.surfaceSyntaxDescription.name, AUGMENTED_ASSIGNMENT)
else -> Unit
}
else -> Unit
}
}
}
return result ?: defaultResult
}
override fun getPatternForUnwrappedVariables(): Pattern {
return Pattern.compile("(([a-zA-Z0-9_]\\w*))")
}
override fun getPatternForWrappedVariables(): Pattern {
return Pattern.compile("\\$\\{([^}]*)}")
}
override fun modelDescriptionForParent(externalName: String, context: GradleDslElement): ModelPropertyDescription? {
val map = context.getExternalToModelMap(this)
for (e in map.entrySet) {
if (e.surfaceSyntaxDescription.name == externalName) return e.modelEffectDescription.property
}
return null
}
val internalContext: BuildModelContext
override fun getContext(): BuildModelContext = internalContext
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 6,062
|
android
|
Apache License 2.0
|
quartz/src/main/java/com/vitorpamplona/quartz/events/RepostEvent.kt
|
vitorpamplona
| 587,850,619
| false
| null |
package com.vitorpamplona.quartz.events
import androidx.compose.runtime.Immutable
import com.vitorpamplona.quartz.utils.TimeUtils
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.crypto.CryptoUtils
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.HexKey
import com.vitorpamplona.quartz.signers.NostrSigner
@Immutable
class RepostEvent(
id: HexKey,
pubKey: HexKey,
createdAt: Long,
tags: Array<Array<String>>,
content: String,
sig: HexKey
) : Event(id, pubKey, createdAt, kind, tags, content, sig) {
fun boostedPost() = taggedEvents()
fun originalAuthor() = taggedUsers()
fun containedPost() = try {
fromJson(content)
} catch (e: Exception) {
null
}
companion object {
const val kind = 6
const val alt = "Repost event"
fun create(
boostedPost: EventInterface,
signer: NostrSigner,
createdAt: Long = TimeUtils.now(),
onReady: (RepostEvent) -> Unit
) {
val content = boostedPost.toJson()
val replyToPost = arrayOf("e", boostedPost.id())
val replyToAuthor = arrayOf("p", boostedPost.pubKey())
var tags: Array<Array<String>> = arrayOf(replyToPost, replyToAuthor)
if (boostedPost is AddressableEvent) {
tags += listOf(arrayOf("a", boostedPost.address().toTag()))
}
tags += listOf(arrayOf("alt", alt))
signer.sign(createdAt, kind, tags, content, onReady)
}
}
}
| 157
| null |
141
| 981
|
2de3d19a34b97c012e39b203070d9c1c0b1f0520
| 1,605
|
amethyst
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.